blob: 51275f8f3edf0f0ef0e1ba89c40218a8c4b167b0 [file] [log] [blame]
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001//===-- SelectionDAGBuild.cpp - Selection-DAG building --------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This implements routines for translating from LLVM IR into SelectionDAG IR.
11//
12//===----------------------------------------------------------------------===//
13
14#define DEBUG_TYPE "isel"
15#include "SelectionDAGBuild.h"
16#include "llvm/ADT/BitVector.h"
Dan Gohman5b229802008-09-04 20:49:27 +000017#include "llvm/ADT/SmallSet.h"
Dan Gohmanf0cbcd42008-09-03 16:12:24 +000018#include "llvm/Analysis/AliasAnalysis.h"
19#include "llvm/Constants.h"
20#include "llvm/CallingConv.h"
21#include "llvm/DerivedTypes.h"
22#include "llvm/Function.h"
23#include "llvm/GlobalVariable.h"
24#include "llvm/InlineAsm.h"
25#include "llvm/Instructions.h"
26#include "llvm/Intrinsics.h"
27#include "llvm/IntrinsicInst.h"
Dan Gohmanf0cbcd42008-09-03 16:12:24 +000028#include "llvm/CodeGen/FastISel.h"
29#include "llvm/CodeGen/GCStrategy.h"
30#include "llvm/CodeGen/GCMetadata.h"
31#include "llvm/CodeGen/MachineFunction.h"
32#include "llvm/CodeGen/MachineFrameInfo.h"
33#include "llvm/CodeGen/MachineInstrBuilder.h"
34#include "llvm/CodeGen/MachineJumpTableInfo.h"
35#include "llvm/CodeGen/MachineModuleInfo.h"
36#include "llvm/CodeGen/MachineRegisterInfo.h"
37#include "llvm/CodeGen/SelectionDAG.h"
38#include "llvm/Target/TargetRegisterInfo.h"
39#include "llvm/Target/TargetData.h"
40#include "llvm/Target/TargetFrameInfo.h"
41#include "llvm/Target/TargetInstrInfo.h"
42#include "llvm/Target/TargetLowering.h"
43#include "llvm/Target/TargetMachine.h"
44#include "llvm/Target/TargetOptions.h"
45#include "llvm/Support/Compiler.h"
46#include "llvm/Support/Debug.h"
47#include "llvm/Support/MathExtras.h"
48#include <algorithm>
49using namespace llvm;
50
Dale Johannesen601d3c02008-09-05 01:48:15 +000051/// LimitFloatPrecision - Generate low-precision inline sequences for
52/// some float libcalls (6, 8 or 12 bits).
53static unsigned LimitFloatPrecision;
54
55static cl::opt<unsigned, true>
56LimitFPPrecision("limit-float-precision",
57 cl::desc("Generate low-precision inline sequences "
58 "for some float libcalls"),
59 cl::location(LimitFloatPrecision),
60 cl::init(0));
61
Dan Gohmanf0cbcd42008-09-03 16:12:24 +000062/// ComputeLinearIndex - Given an LLVM IR aggregate type and a sequence
63/// insertvalue or extractvalue indices that identify a member, return
64/// the linearized index of the start of the member.
65///
66static unsigned ComputeLinearIndex(const TargetLowering &TLI, const Type *Ty,
67 const unsigned *Indices,
68 const unsigned *IndicesEnd,
69 unsigned CurIndex = 0) {
70 // Base case: We're done.
71 if (Indices && Indices == IndicesEnd)
72 return CurIndex;
73
74 // Given a struct type, recursively traverse the elements.
75 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
76 for (StructType::element_iterator EB = STy->element_begin(),
77 EI = EB,
78 EE = STy->element_end();
79 EI != EE; ++EI) {
80 if (Indices && *Indices == unsigned(EI - EB))
81 return ComputeLinearIndex(TLI, *EI, Indices+1, IndicesEnd, CurIndex);
82 CurIndex = ComputeLinearIndex(TLI, *EI, 0, 0, CurIndex);
83 }
84 }
85 // Given an array type, recursively traverse the elements.
86 else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
87 const Type *EltTy = ATy->getElementType();
88 for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i) {
89 if (Indices && *Indices == i)
90 return ComputeLinearIndex(TLI, EltTy, Indices+1, IndicesEnd, CurIndex);
91 CurIndex = ComputeLinearIndex(TLI, EltTy, 0, 0, CurIndex);
92 }
93 }
94 // We haven't found the type we're looking for, so keep searching.
95 return CurIndex + 1;
96}
97
98/// ComputeValueVTs - Given an LLVM IR type, compute a sequence of
99/// MVTs that represent all the individual underlying
100/// non-aggregate types that comprise it.
101///
102/// If Offsets is non-null, it points to a vector to be filled in
103/// with the in-memory offsets of each of the individual values.
104///
105static void ComputeValueVTs(const TargetLowering &TLI, const Type *Ty,
106 SmallVectorImpl<MVT> &ValueVTs,
107 SmallVectorImpl<uint64_t> *Offsets = 0,
108 uint64_t StartingOffset = 0) {
109 // Given a struct type, recursively traverse the elements.
110 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
111 const StructLayout *SL = TLI.getTargetData()->getStructLayout(STy);
112 for (StructType::element_iterator EB = STy->element_begin(),
113 EI = EB,
114 EE = STy->element_end();
115 EI != EE; ++EI)
116 ComputeValueVTs(TLI, *EI, ValueVTs, Offsets,
117 StartingOffset + SL->getElementOffset(EI - EB));
118 return;
119 }
120 // Given an array type, recursively traverse the elements.
121 if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
122 const Type *EltTy = ATy->getElementType();
123 uint64_t EltSize = TLI.getTargetData()->getABITypeSize(EltTy);
124 for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i)
125 ComputeValueVTs(TLI, EltTy, ValueVTs, Offsets,
126 StartingOffset + i * EltSize);
127 return;
128 }
129 // Base case: we can get an MVT for this LLVM IR type.
130 ValueVTs.push_back(TLI.getValueType(Ty));
131 if (Offsets)
132 Offsets->push_back(StartingOffset);
133}
134
Dan Gohman2a7c6712008-09-03 23:18:39 +0000135namespace llvm {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000136 /// RegsForValue - This struct represents the registers (physical or virtual)
137 /// that a particular set of values is assigned, and the type information about
138 /// the value. The most common situation is to represent one value at a time,
139 /// but struct or array values are handled element-wise as multiple values.
140 /// The splitting of aggregates is performed recursively, so that we never
141 /// have aggregate-typed registers. The values at this point do not necessarily
142 /// have legal types, so each value may require one or more registers of some
143 /// legal type.
144 ///
145 struct VISIBILITY_HIDDEN RegsForValue {
146 /// TLI - The TargetLowering object.
147 ///
148 const TargetLowering *TLI;
149
150 /// ValueVTs - The value types of the values, which may not be legal, and
151 /// may need be promoted or synthesized from one or more registers.
152 ///
153 SmallVector<MVT, 4> ValueVTs;
154
155 /// RegVTs - The value types of the registers. This is the same size as
156 /// ValueVTs and it records, for each value, what the type of the assigned
157 /// register or registers are. (Individual values are never synthesized
158 /// from more than one type of register.)
159 ///
160 /// With virtual registers, the contents of RegVTs is redundant with TLI's
161 /// getRegisterType member function, however when with physical registers
162 /// it is necessary to have a separate record of the types.
163 ///
164 SmallVector<MVT, 4> RegVTs;
165
166 /// Regs - This list holds the registers assigned to the values.
167 /// Each legal or promoted value requires one register, and each
168 /// expanded value requires multiple registers.
169 ///
170 SmallVector<unsigned, 4> Regs;
171
172 RegsForValue() : TLI(0) {}
173
174 RegsForValue(const TargetLowering &tli,
175 const SmallVector<unsigned, 4> &regs,
176 MVT regvt, MVT valuevt)
177 : TLI(&tli), ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs) {}
178 RegsForValue(const TargetLowering &tli,
179 const SmallVector<unsigned, 4> &regs,
180 const SmallVector<MVT, 4> &regvts,
181 const SmallVector<MVT, 4> &valuevts)
182 : TLI(&tli), ValueVTs(valuevts), RegVTs(regvts), Regs(regs) {}
183 RegsForValue(const TargetLowering &tli,
184 unsigned Reg, const Type *Ty) : TLI(&tli) {
185 ComputeValueVTs(tli, Ty, ValueVTs);
186
187 for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
188 MVT ValueVT = ValueVTs[Value];
189 unsigned NumRegs = TLI->getNumRegisters(ValueVT);
190 MVT RegisterVT = TLI->getRegisterType(ValueVT);
191 for (unsigned i = 0; i != NumRegs; ++i)
192 Regs.push_back(Reg + i);
193 RegVTs.push_back(RegisterVT);
194 Reg += NumRegs;
195 }
196 }
197
198 /// append - Add the specified values to this one.
199 void append(const RegsForValue &RHS) {
200 TLI = RHS.TLI;
201 ValueVTs.append(RHS.ValueVTs.begin(), RHS.ValueVTs.end());
202 RegVTs.append(RHS.RegVTs.begin(), RHS.RegVTs.end());
203 Regs.append(RHS.Regs.begin(), RHS.Regs.end());
204 }
205
206
207 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
208 /// this value and returns the result as a ValueVTs value. This uses
209 /// Chain/Flag as the input and updates them for the output Chain/Flag.
210 /// If the Flag pointer is NULL, no flag is used.
211 SDValue getCopyFromRegs(SelectionDAG &DAG,
212 SDValue &Chain, SDValue *Flag) const;
213
214 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
215 /// specified value into the registers specified by this object. This uses
216 /// Chain/Flag as the input and updates them for the output Chain/Flag.
217 /// If the Flag pointer is NULL, no flag is used.
218 void getCopyToRegs(SDValue Val, SelectionDAG &DAG,
219 SDValue &Chain, SDValue *Flag) const;
220
221 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
222 /// operand list. This adds the code marker and includes the number of
223 /// values added into it.
224 void AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
225 std::vector<SDValue> &Ops) const;
226 };
227}
228
229/// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by
230/// PHI nodes or outside of the basic block that defines it, or used by a
231/// switch or atomic instruction, which may expand to multiple basic blocks.
232static bool isUsedOutsideOfDefiningBlock(Instruction *I) {
233 if (isa<PHINode>(I)) return true;
234 BasicBlock *BB = I->getParent();
235 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; ++UI)
236 if (cast<Instruction>(*UI)->getParent() != BB || isa<PHINode>(*UI) ||
237 // FIXME: Remove switchinst special case.
238 isa<SwitchInst>(*UI))
239 return true;
240 return false;
241}
242
243/// isOnlyUsedInEntryBlock - If the specified argument is only used in the
244/// entry block, return true. This includes arguments used by switches, since
245/// the switch may expand into multiple basic blocks.
246static bool isOnlyUsedInEntryBlock(Argument *A, bool EnableFastISel) {
247 // With FastISel active, we may be splitting blocks, so force creation
248 // of virtual registers for all non-dead arguments.
Dan Gohman33134c42008-09-25 17:05:24 +0000249 // Don't force virtual registers for byval arguments though, because
250 // fast-isel can't handle those in all cases.
251 if (EnableFastISel && !A->hasByValAttr())
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000252 return A->use_empty();
253
254 BasicBlock *Entry = A->getParent()->begin();
255 for (Value::use_iterator UI = A->use_begin(), E = A->use_end(); UI != E; ++UI)
256 if (cast<Instruction>(*UI)->getParent() != Entry || isa<SwitchInst>(*UI))
257 return false; // Use not in entry block.
258 return true;
259}
260
261FunctionLoweringInfo::FunctionLoweringInfo(TargetLowering &tli)
262 : TLI(tli) {
263}
264
265void FunctionLoweringInfo::set(Function &fn, MachineFunction &mf,
266 bool EnableFastISel) {
267 Fn = &fn;
268 MF = &mf;
269 RegInfo = &MF->getRegInfo();
270
271 // Create a vreg for each argument register that is not dead and is used
272 // outside of the entry block for the function.
273 for (Function::arg_iterator AI = Fn->arg_begin(), E = Fn->arg_end();
274 AI != E; ++AI)
275 if (!isOnlyUsedInEntryBlock(AI, EnableFastISel))
276 InitializeRegForValue(AI);
277
278 // Initialize the mapping of values to registers. This is only set up for
279 // instruction values that are used outside of the block that defines
280 // them.
281 Function::iterator BB = Fn->begin(), EB = Fn->end();
282 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
283 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
284 if (ConstantInt *CUI = dyn_cast<ConstantInt>(AI->getArraySize())) {
285 const Type *Ty = AI->getAllocatedType();
286 uint64_t TySize = TLI.getTargetData()->getABITypeSize(Ty);
287 unsigned Align =
288 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
289 AI->getAlignment());
290
291 TySize *= CUI->getZExtValue(); // Get total allocated size.
292 if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
293 StaticAllocaMap[AI] =
294 MF->getFrameInfo()->CreateStackObject(TySize, Align);
295 }
296
297 for (; BB != EB; ++BB)
298 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
299 if (!I->use_empty() && isUsedOutsideOfDefiningBlock(I))
300 if (!isa<AllocaInst>(I) ||
301 !StaticAllocaMap.count(cast<AllocaInst>(I)))
302 InitializeRegForValue(I);
303
304 // Create an initial MachineBasicBlock for each LLVM BasicBlock in F. This
305 // also creates the initial PHI MachineInstrs, though none of the input
306 // operands are populated.
307 for (BB = Fn->begin(), EB = Fn->end(); BB != EB; ++BB) {
308 MachineBasicBlock *MBB = mf.CreateMachineBasicBlock(BB);
309 MBBMap[BB] = MBB;
310 MF->push_back(MBB);
311
312 // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
313 // appropriate.
314 PHINode *PN;
315 for (BasicBlock::iterator I = BB->begin();(PN = dyn_cast<PHINode>(I)); ++I){
316 if (PN->use_empty()) continue;
317
318 unsigned PHIReg = ValueMap[PN];
319 assert(PHIReg && "PHI node does not have an assigned virtual register!");
320
321 SmallVector<MVT, 4> ValueVTs;
322 ComputeValueVTs(TLI, PN->getType(), ValueVTs);
323 for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
324 MVT VT = ValueVTs[vti];
325 unsigned NumRegisters = TLI.getNumRegisters(VT);
Dan Gohman6448d912008-09-04 15:39:15 +0000326 const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000327 for (unsigned i = 0; i != NumRegisters; ++i)
328 BuildMI(MBB, TII->get(TargetInstrInfo::PHI), PHIReg+i);
329 PHIReg += NumRegisters;
330 }
331 }
332 }
333}
334
335unsigned FunctionLoweringInfo::MakeReg(MVT VT) {
336 return RegInfo->createVirtualRegister(TLI.getRegClassFor(VT));
337}
338
339/// CreateRegForValue - Allocate the appropriate number of virtual registers of
340/// the correctly promoted or expanded types. Assign these registers
341/// consecutive vreg numbers and return the first assigned number.
342///
343/// In the case that the given value has struct or array type, this function
344/// will assign registers for each member or element.
345///
346unsigned FunctionLoweringInfo::CreateRegForValue(const Value *V) {
347 SmallVector<MVT, 4> ValueVTs;
348 ComputeValueVTs(TLI, V->getType(), ValueVTs);
349
350 unsigned FirstReg = 0;
351 for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
352 MVT ValueVT = ValueVTs[Value];
353 MVT RegisterVT = TLI.getRegisterType(ValueVT);
354
355 unsigned NumRegs = TLI.getNumRegisters(ValueVT);
356 for (unsigned i = 0; i != NumRegs; ++i) {
357 unsigned R = MakeReg(RegisterVT);
358 if (!FirstReg) FirstReg = R;
359 }
360 }
361 return FirstReg;
362}
363
364/// getCopyFromParts - Create a value that contains the specified legal parts
365/// combined into the value they represent. If the parts combine to a type
366/// larger then ValueVT then AssertOp can be used to specify whether the extra
367/// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
368/// (ISD::AssertSext).
369static SDValue getCopyFromParts(SelectionDAG &DAG,
370 const SDValue *Parts,
371 unsigned NumParts,
372 MVT PartVT,
373 MVT ValueVT,
374 ISD::NodeType AssertOp = ISD::DELETED_NODE) {
375 assert(NumParts > 0 && "No parts to assemble!");
376 TargetLowering &TLI = DAG.getTargetLoweringInfo();
377 SDValue Val = Parts[0];
378
379 if (NumParts > 1) {
380 // Assemble the value from multiple parts.
381 if (!ValueVT.isVector()) {
382 unsigned PartBits = PartVT.getSizeInBits();
383 unsigned ValueBits = ValueVT.getSizeInBits();
384
385 // Assemble the power of 2 part.
386 unsigned RoundParts = NumParts & (NumParts - 1) ?
387 1 << Log2_32(NumParts) : NumParts;
388 unsigned RoundBits = PartBits * RoundParts;
389 MVT RoundVT = RoundBits == ValueBits ?
390 ValueVT : MVT::getIntegerVT(RoundBits);
391 SDValue Lo, Hi;
392
393 if (RoundParts > 2) {
394 MVT HalfVT = MVT::getIntegerVT(RoundBits/2);
395 Lo = getCopyFromParts(DAG, Parts, RoundParts/2, PartVT, HalfVT);
396 Hi = getCopyFromParts(DAG, Parts+RoundParts/2, RoundParts/2,
397 PartVT, HalfVT);
398 } else {
399 Lo = Parts[0];
400 Hi = Parts[1];
401 }
402 if (TLI.isBigEndian())
403 std::swap(Lo, Hi);
404 Val = DAG.getNode(ISD::BUILD_PAIR, RoundVT, Lo, Hi);
405
406 if (RoundParts < NumParts) {
407 // Assemble the trailing non-power-of-2 part.
408 unsigned OddParts = NumParts - RoundParts;
409 MVT OddVT = MVT::getIntegerVT(OddParts * PartBits);
410 Hi = getCopyFromParts(DAG, Parts+RoundParts, OddParts, PartVT, OddVT);
411
412 // Combine the round and odd parts.
413 Lo = Val;
414 if (TLI.isBigEndian())
415 std::swap(Lo, Hi);
416 MVT TotalVT = MVT::getIntegerVT(NumParts * PartBits);
417 Hi = DAG.getNode(ISD::ANY_EXTEND, TotalVT, Hi);
418 Hi = DAG.getNode(ISD::SHL, TotalVT, Hi,
419 DAG.getConstant(Lo.getValueType().getSizeInBits(),
420 TLI.getShiftAmountTy()));
421 Lo = DAG.getNode(ISD::ZERO_EXTEND, TotalVT, Lo);
422 Val = DAG.getNode(ISD::OR, TotalVT, Lo, Hi);
423 }
424 } else {
425 // Handle a multi-element vector.
426 MVT IntermediateVT, RegisterVT;
427 unsigned NumIntermediates;
428 unsigned NumRegs =
429 TLI.getVectorTypeBreakdown(ValueVT, IntermediateVT, NumIntermediates,
430 RegisterVT);
431 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
432 NumParts = NumRegs; // Silence a compiler warning.
433 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
434 assert(RegisterVT == Parts[0].getValueType() &&
435 "Part type doesn't match part!");
436
437 // Assemble the parts into intermediate operands.
438 SmallVector<SDValue, 8> Ops(NumIntermediates);
439 if (NumIntermediates == NumParts) {
440 // If the register was not expanded, truncate or copy the value,
441 // as appropriate.
442 for (unsigned i = 0; i != NumParts; ++i)
443 Ops[i] = getCopyFromParts(DAG, &Parts[i], 1,
444 PartVT, IntermediateVT);
445 } else if (NumParts > 0) {
446 // If the intermediate type was expanded, build the intermediate operands
447 // from the parts.
448 assert(NumParts % NumIntermediates == 0 &&
449 "Must expand into a divisible number of parts!");
450 unsigned Factor = NumParts / NumIntermediates;
451 for (unsigned i = 0; i != NumIntermediates; ++i)
452 Ops[i] = getCopyFromParts(DAG, &Parts[i * Factor], Factor,
453 PartVT, IntermediateVT);
454 }
455
456 // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the intermediate
457 // operands.
458 Val = DAG.getNode(IntermediateVT.isVector() ?
459 ISD::CONCAT_VECTORS : ISD::BUILD_VECTOR,
460 ValueVT, &Ops[0], NumIntermediates);
461 }
462 }
463
464 // There is now one part, held in Val. Correct it to match ValueVT.
465 PartVT = Val.getValueType();
466
467 if (PartVT == ValueVT)
468 return Val;
469
470 if (PartVT.isVector()) {
471 assert(ValueVT.isVector() && "Unknown vector conversion!");
472 return DAG.getNode(ISD::BIT_CONVERT, ValueVT, Val);
473 }
474
475 if (ValueVT.isVector()) {
476 assert(ValueVT.getVectorElementType() == PartVT &&
477 ValueVT.getVectorNumElements() == 1 &&
478 "Only trivial scalar-to-vector conversions should get here!");
479 return DAG.getNode(ISD::BUILD_VECTOR, ValueVT, Val);
480 }
481
482 if (PartVT.isInteger() &&
483 ValueVT.isInteger()) {
484 if (ValueVT.bitsLT(PartVT)) {
485 // For a truncate, see if we have any information to
486 // indicate whether the truncated bits will always be
487 // zero or sign-extension.
488 if (AssertOp != ISD::DELETED_NODE)
489 Val = DAG.getNode(AssertOp, PartVT, Val,
490 DAG.getValueType(ValueVT));
491 return DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
492 } else {
493 return DAG.getNode(ISD::ANY_EXTEND, ValueVT, Val);
494 }
495 }
496
497 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
498 if (ValueVT.bitsLT(Val.getValueType()))
499 // FP_ROUND's are always exact here.
500 return DAG.getNode(ISD::FP_ROUND, ValueVT, Val,
501 DAG.getIntPtrConstant(1));
502 return DAG.getNode(ISD::FP_EXTEND, ValueVT, Val);
503 }
504
505 if (PartVT.getSizeInBits() == ValueVT.getSizeInBits())
506 return DAG.getNode(ISD::BIT_CONVERT, ValueVT, Val);
507
508 assert(0 && "Unknown mismatch!");
509 return SDValue();
510}
511
512/// getCopyToParts - Create a series of nodes that contain the specified value
513/// split into legal parts. If the parts contain more bits than Val, then, for
514/// integers, ExtendKind can be used to specify how to generate the extra bits.
515static void getCopyToParts(SelectionDAG &DAG,
516 SDValue Val,
517 SDValue *Parts,
518 unsigned NumParts,
519 MVT PartVT,
520 ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
521 TargetLowering &TLI = DAG.getTargetLoweringInfo();
522 MVT PtrVT = TLI.getPointerTy();
523 MVT ValueVT = Val.getValueType();
524 unsigned PartBits = PartVT.getSizeInBits();
525 assert(TLI.isTypeLegal(PartVT) && "Copying to an illegal type!");
526
527 if (!NumParts)
528 return;
529
530 if (!ValueVT.isVector()) {
531 if (PartVT == ValueVT) {
532 assert(NumParts == 1 && "No-op copy with multiple parts!");
533 Parts[0] = Val;
534 return;
535 }
536
537 if (NumParts * PartBits > ValueVT.getSizeInBits()) {
538 // If the parts cover more bits than the value has, promote the value.
539 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
540 assert(NumParts == 1 && "Do not know what to promote to!");
541 Val = DAG.getNode(ISD::FP_EXTEND, PartVT, Val);
542 } else if (PartVT.isInteger() && ValueVT.isInteger()) {
543 ValueVT = MVT::getIntegerVT(NumParts * PartBits);
544 Val = DAG.getNode(ExtendKind, ValueVT, Val);
545 } else {
546 assert(0 && "Unknown mismatch!");
547 }
548 } else if (PartBits == ValueVT.getSizeInBits()) {
549 // Different types of the same size.
550 assert(NumParts == 1 && PartVT != ValueVT);
551 Val = DAG.getNode(ISD::BIT_CONVERT, PartVT, Val);
552 } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
553 // If the parts cover less bits than value has, truncate the value.
554 if (PartVT.isInteger() && ValueVT.isInteger()) {
555 ValueVT = MVT::getIntegerVT(NumParts * PartBits);
556 Val = DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
557 } else {
558 assert(0 && "Unknown mismatch!");
559 }
560 }
561
562 // The value may have changed - recompute ValueVT.
563 ValueVT = Val.getValueType();
564 assert(NumParts * PartBits == ValueVT.getSizeInBits() &&
565 "Failed to tile the value with PartVT!");
566
567 if (NumParts == 1) {
568 assert(PartVT == ValueVT && "Type conversion failed!");
569 Parts[0] = Val;
570 return;
571 }
572
573 // Expand the value into multiple parts.
574 if (NumParts & (NumParts - 1)) {
575 // The number of parts is not a power of 2. Split off and copy the tail.
576 assert(PartVT.isInteger() && ValueVT.isInteger() &&
577 "Do not know what to expand to!");
578 unsigned RoundParts = 1 << Log2_32(NumParts);
579 unsigned RoundBits = RoundParts * PartBits;
580 unsigned OddParts = NumParts - RoundParts;
581 SDValue OddVal = DAG.getNode(ISD::SRL, ValueVT, Val,
582 DAG.getConstant(RoundBits,
583 TLI.getShiftAmountTy()));
584 getCopyToParts(DAG, OddVal, Parts + RoundParts, OddParts, PartVT);
585 if (TLI.isBigEndian())
586 // The odd parts were reversed by getCopyToParts - unreverse them.
587 std::reverse(Parts + RoundParts, Parts + NumParts);
588 NumParts = RoundParts;
589 ValueVT = MVT::getIntegerVT(NumParts * PartBits);
590 Val = DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
591 }
592
593 // The number of parts is a power of 2. Repeatedly bisect the value using
594 // EXTRACT_ELEMENT.
595 Parts[0] = DAG.getNode(ISD::BIT_CONVERT,
596 MVT::getIntegerVT(ValueVT.getSizeInBits()),
597 Val);
598 for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
599 for (unsigned i = 0; i < NumParts; i += StepSize) {
600 unsigned ThisBits = StepSize * PartBits / 2;
601 MVT ThisVT = MVT::getIntegerVT (ThisBits);
602 SDValue &Part0 = Parts[i];
603 SDValue &Part1 = Parts[i+StepSize/2];
604
605 Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, ThisVT, Part0,
606 DAG.getConstant(1, PtrVT));
607 Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, ThisVT, Part0,
608 DAG.getConstant(0, PtrVT));
609
610 if (ThisBits == PartBits && ThisVT != PartVT) {
611 Part0 = DAG.getNode(ISD::BIT_CONVERT, PartVT, Part0);
612 Part1 = DAG.getNode(ISD::BIT_CONVERT, PartVT, Part1);
613 }
614 }
615 }
616
617 if (TLI.isBigEndian())
618 std::reverse(Parts, Parts + NumParts);
619
620 return;
621 }
622
623 // Vector ValueVT.
624 if (NumParts == 1) {
625 if (PartVT != ValueVT) {
626 if (PartVT.isVector()) {
627 Val = DAG.getNode(ISD::BIT_CONVERT, PartVT, Val);
628 } else {
629 assert(ValueVT.getVectorElementType() == PartVT &&
630 ValueVT.getVectorNumElements() == 1 &&
631 "Only trivial vector-to-scalar conversions should get here!");
632 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, PartVT, Val,
633 DAG.getConstant(0, PtrVT));
634 }
635 }
636
637 Parts[0] = Val;
638 return;
639 }
640
641 // Handle a multi-element vector.
642 MVT IntermediateVT, RegisterVT;
643 unsigned NumIntermediates;
644 unsigned NumRegs =
645 DAG.getTargetLoweringInfo()
646 .getVectorTypeBreakdown(ValueVT, IntermediateVT, NumIntermediates,
647 RegisterVT);
648 unsigned NumElements = ValueVT.getVectorNumElements();
649
650 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
651 NumParts = NumRegs; // Silence a compiler warning.
652 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
653
654 // Split the vector into intermediate operands.
655 SmallVector<SDValue, 8> Ops(NumIntermediates);
656 for (unsigned i = 0; i != NumIntermediates; ++i)
657 if (IntermediateVT.isVector())
658 Ops[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR,
659 IntermediateVT, Val,
660 DAG.getConstant(i * (NumElements / NumIntermediates),
661 PtrVT));
662 else
663 Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
664 IntermediateVT, Val,
665 DAG.getConstant(i, PtrVT));
666
667 // Split the intermediate operands into legal parts.
668 if (NumParts == NumIntermediates) {
669 // If the register was not expanded, promote or copy the value,
670 // as appropriate.
671 for (unsigned i = 0; i != NumParts; ++i)
672 getCopyToParts(DAG, Ops[i], &Parts[i], 1, PartVT);
673 } else if (NumParts > 0) {
674 // If the intermediate type was expanded, split each the value into
675 // legal parts.
676 assert(NumParts % NumIntermediates == 0 &&
677 "Must expand into a divisible number of parts!");
678 unsigned Factor = NumParts / NumIntermediates;
679 for (unsigned i = 0; i != NumIntermediates; ++i)
680 getCopyToParts(DAG, Ops[i], &Parts[i * Factor], Factor, PartVT);
681 }
682}
683
684
685void SelectionDAGLowering::init(GCFunctionInfo *gfi, AliasAnalysis &aa) {
686 AA = &aa;
687 GFI = gfi;
688 TD = DAG.getTarget().getTargetData();
689}
690
691/// clear - Clear out the curret SelectionDAG and the associated
692/// state and prepare this SelectionDAGLowering object to be used
693/// for a new block. This doesn't clear out information about
694/// additional blocks that are needed to complete switch lowering
695/// or PHI node updating; that information is cleared out as it is
696/// consumed.
697void SelectionDAGLowering::clear() {
698 NodeMap.clear();
699 PendingLoads.clear();
700 PendingExports.clear();
701 DAG.clear();
702}
703
704/// getRoot - Return the current virtual root of the Selection DAG,
705/// flushing any PendingLoad items. This must be done before emitting
706/// a store or any other node that may need to be ordered after any
707/// prior load instructions.
708///
709SDValue SelectionDAGLowering::getRoot() {
710 if (PendingLoads.empty())
711 return DAG.getRoot();
712
713 if (PendingLoads.size() == 1) {
714 SDValue Root = PendingLoads[0];
715 DAG.setRoot(Root);
716 PendingLoads.clear();
717 return Root;
718 }
719
720 // Otherwise, we have to make a token factor node.
721 SDValue Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
722 &PendingLoads[0], PendingLoads.size());
723 PendingLoads.clear();
724 DAG.setRoot(Root);
725 return Root;
726}
727
728/// getControlRoot - Similar to getRoot, but instead of flushing all the
729/// PendingLoad items, flush all the PendingExports items. It is necessary
730/// to do this before emitting a terminator instruction.
731///
732SDValue SelectionDAGLowering::getControlRoot() {
733 SDValue Root = DAG.getRoot();
734
735 if (PendingExports.empty())
736 return Root;
737
738 // Turn all of the CopyToReg chains into one factored node.
739 if (Root.getOpcode() != ISD::EntryToken) {
740 unsigned i = 0, e = PendingExports.size();
741 for (; i != e; ++i) {
742 assert(PendingExports[i].getNode()->getNumOperands() > 1);
743 if (PendingExports[i].getNode()->getOperand(0) == Root)
744 break; // Don't add the root if we already indirectly depend on it.
745 }
746
747 if (i == e)
748 PendingExports.push_back(Root);
749 }
750
751 Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
752 &PendingExports[0],
753 PendingExports.size());
754 PendingExports.clear();
755 DAG.setRoot(Root);
756 return Root;
757}
758
759void SelectionDAGLowering::visit(Instruction &I) {
760 visit(I.getOpcode(), I);
761}
762
763void SelectionDAGLowering::visit(unsigned Opcode, User &I) {
764 // Note: this doesn't use InstVisitor, because it has to work with
765 // ConstantExpr's in addition to instructions.
766 switch (Opcode) {
767 default: assert(0 && "Unknown instruction type encountered!");
768 abort();
769 // Build the switch statement using the Instruction.def file.
770#define HANDLE_INST(NUM, OPCODE, CLASS) \
771 case Instruction::OPCODE:return visit##OPCODE((CLASS&)I);
772#include "llvm/Instruction.def"
773 }
774}
775
776void SelectionDAGLowering::visitAdd(User &I) {
777 if (I.getType()->isFPOrFPVector())
778 visitBinary(I, ISD::FADD);
779 else
780 visitBinary(I, ISD::ADD);
781}
782
783void SelectionDAGLowering::visitMul(User &I) {
784 if (I.getType()->isFPOrFPVector())
785 visitBinary(I, ISD::FMUL);
786 else
787 visitBinary(I, ISD::MUL);
788}
789
790SDValue SelectionDAGLowering::getValue(const Value *V) {
791 SDValue &N = NodeMap[V];
792 if (N.getNode()) return N;
793
794 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V))) {
795 MVT VT = TLI.getValueType(V->getType(), true);
796
797 if (ConstantInt *CI = dyn_cast<ConstantInt>(C))
Dan Gohman4fbd7962008-09-12 18:08:03 +0000798 return N = DAG.getConstant(*CI, VT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000799
800 if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
801 return N = DAG.getGlobalAddress(GV, VT);
802
803 if (isa<ConstantPointerNull>(C))
804 return N = DAG.getConstant(0, TLI.getPointerTy());
805
806 if (ConstantFP *CFP = dyn_cast<ConstantFP>(C))
Dan Gohman4fbd7962008-09-12 18:08:03 +0000807 return N = DAG.getConstantFP(*CFP, VT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000808
809 if (isa<UndefValue>(C) && !isa<VectorType>(V->getType()) &&
810 !V->getType()->isAggregateType())
811 return N = DAG.getNode(ISD::UNDEF, VT);
812
813 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
814 visit(CE->getOpcode(), *CE);
815 SDValue N1 = NodeMap[V];
816 assert(N1.getNode() && "visit didn't populate the ValueMap!");
817 return N1;
818 }
819
820 if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
821 SmallVector<SDValue, 4> Constants;
822 for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end();
823 OI != OE; ++OI) {
824 SDNode *Val = getValue(*OI).getNode();
825 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
826 Constants.push_back(SDValue(Val, i));
827 }
828 return DAG.getMergeValues(&Constants[0], Constants.size());
829 }
830
831 if (isa<StructType>(C->getType()) || isa<ArrayType>(C->getType())) {
832 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
833 "Unknown struct or array constant!");
834
835 SmallVector<MVT, 4> ValueVTs;
836 ComputeValueVTs(TLI, C->getType(), ValueVTs);
837 unsigned NumElts = ValueVTs.size();
838 if (NumElts == 0)
839 return SDValue(); // empty struct
840 SmallVector<SDValue, 4> Constants(NumElts);
841 for (unsigned i = 0; i != NumElts; ++i) {
842 MVT EltVT = ValueVTs[i];
843 if (isa<UndefValue>(C))
844 Constants[i] = DAG.getNode(ISD::UNDEF, EltVT);
845 else if (EltVT.isFloatingPoint())
846 Constants[i] = DAG.getConstantFP(0, EltVT);
847 else
848 Constants[i] = DAG.getConstant(0, EltVT);
849 }
850 return DAG.getMergeValues(&Constants[0], NumElts);
851 }
852
853 const VectorType *VecTy = cast<VectorType>(V->getType());
854 unsigned NumElements = VecTy->getNumElements();
855
856 // Now that we know the number and type of the elements, get that number of
857 // elements into the Ops array based on what kind of constant it is.
858 SmallVector<SDValue, 16> Ops;
859 if (ConstantVector *CP = dyn_cast<ConstantVector>(C)) {
860 for (unsigned i = 0; i != NumElements; ++i)
861 Ops.push_back(getValue(CP->getOperand(i)));
862 } else {
863 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
864 "Unknown vector constant!");
865 MVT EltVT = TLI.getValueType(VecTy->getElementType());
866
867 SDValue Op;
868 if (isa<UndefValue>(C))
869 Op = DAG.getNode(ISD::UNDEF, EltVT);
870 else if (EltVT.isFloatingPoint())
871 Op = DAG.getConstantFP(0, EltVT);
872 else
873 Op = DAG.getConstant(0, EltVT);
874 Ops.assign(NumElements, Op);
875 }
876
877 // Create a BUILD_VECTOR node.
878 return NodeMap[V] = DAG.getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
879 }
880
881 // If this is a static alloca, generate it as the frameindex instead of
882 // computation.
883 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
884 DenseMap<const AllocaInst*, int>::iterator SI =
885 FuncInfo.StaticAllocaMap.find(AI);
886 if (SI != FuncInfo.StaticAllocaMap.end())
887 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
888 }
889
890 unsigned InReg = FuncInfo.ValueMap[V];
891 assert(InReg && "Value not in map!");
892
893 RegsForValue RFV(TLI, InReg, V->getType());
894 SDValue Chain = DAG.getEntryNode();
895 return RFV.getCopyFromRegs(DAG, Chain, NULL);
896}
897
898
899void SelectionDAGLowering::visitRet(ReturnInst &I) {
900 if (I.getNumOperands() == 0) {
901 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getControlRoot()));
902 return;
903 }
904
905 SmallVector<SDValue, 8> NewValues;
906 NewValues.push_back(getControlRoot());
907 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
908 SDValue RetOp = getValue(I.getOperand(i));
909
910 SmallVector<MVT, 4> ValueVTs;
911 ComputeValueVTs(TLI, I.getOperand(i)->getType(), ValueVTs);
912 for (unsigned j = 0, f = ValueVTs.size(); j != f; ++j) {
913 MVT VT = ValueVTs[j];
914
915 // FIXME: C calling convention requires the return type to be promoted to
Dale Johannesenc9c6da62008-09-25 20:47:45 +0000916 // at least 32-bit. But this is not necessary for non-C calling
917 // conventions.
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000918 if (VT.isInteger()) {
919 MVT MinVT = TLI.getRegisterType(MVT::i32);
920 if (VT.bitsLT(MinVT))
921 VT = MinVT;
922 }
923
924 unsigned NumParts = TLI.getNumRegisters(VT);
925 MVT PartVT = TLI.getRegisterType(VT);
926 SmallVector<SDValue, 4> Parts(NumParts);
927 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
928
929 const Function *F = I.getParent()->getParent();
Devang Patel05988662008-09-25 21:00:45 +0000930 if (F->paramHasAttr(0, Attribute::SExt))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000931 ExtendKind = ISD::SIGN_EXTEND;
Devang Patel05988662008-09-25 21:00:45 +0000932 else if (F->paramHasAttr(0, Attribute::ZExt))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000933 ExtendKind = ISD::ZERO_EXTEND;
934
935 getCopyToParts(DAG, SDValue(RetOp.getNode(), RetOp.getResNo() + j),
936 &Parts[0], NumParts, PartVT, ExtendKind);
937
Dale Johannesenc9c6da62008-09-25 20:47:45 +0000938 // 'inreg' on function refers to return value
939 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
Devang Patel05988662008-09-25 21:00:45 +0000940 if (F->paramHasAttr(0, Attribute::InReg))
Dale Johannesenc9c6da62008-09-25 20:47:45 +0000941 Flags.setInReg();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000942 for (unsigned i = 0; i < NumParts; ++i) {
943 NewValues.push_back(Parts[i]);
Dale Johannesenc9c6da62008-09-25 20:47:45 +0000944 NewValues.push_back(DAG.getArgFlags(Flags));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000945 }
946 }
947 }
948 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other,
949 &NewValues[0], NewValues.size()));
950}
951
952/// ExportFromCurrentBlock - If this condition isn't known to be exported from
953/// the current basic block, add it to ValueMap now so that we'll get a
954/// CopyTo/FromReg.
955void SelectionDAGLowering::ExportFromCurrentBlock(Value *V) {
956 // No need to export constants.
957 if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
958
959 // Already exported?
960 if (FuncInfo.isExportedInst(V)) return;
961
962 unsigned Reg = FuncInfo.InitializeRegForValue(V);
963 CopyValueToVirtualRegister(V, Reg);
964}
965
966bool SelectionDAGLowering::isExportableFromCurrentBlock(Value *V,
967 const BasicBlock *FromBB) {
968 // The operands of the setcc have to be in this block. We don't know
969 // how to export them from some other block.
970 if (Instruction *VI = dyn_cast<Instruction>(V)) {
971 // Can export from current BB.
972 if (VI->getParent() == FromBB)
973 return true;
974
975 // Is already exported, noop.
976 return FuncInfo.isExportedInst(V);
977 }
978
979 // If this is an argument, we can export it if the BB is the entry block or
980 // if it is already exported.
981 if (isa<Argument>(V)) {
982 if (FromBB == &FromBB->getParent()->getEntryBlock())
983 return true;
984
985 // Otherwise, can only export this if it is already exported.
986 return FuncInfo.isExportedInst(V);
987 }
988
989 // Otherwise, constants can always be exported.
990 return true;
991}
992
993static bool InBlock(const Value *V, const BasicBlock *BB) {
994 if (const Instruction *I = dyn_cast<Instruction>(V))
995 return I->getParent() == BB;
996 return true;
997}
998
999/// FindMergedConditions - If Cond is an expression like
1000void SelectionDAGLowering::FindMergedConditions(Value *Cond,
1001 MachineBasicBlock *TBB,
1002 MachineBasicBlock *FBB,
1003 MachineBasicBlock *CurBB,
1004 unsigned Opc) {
1005 // If this node is not part of the or/and tree, emit it as a branch.
1006 Instruction *BOp = dyn_cast<Instruction>(Cond);
1007
1008 if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
1009 (unsigned)BOp->getOpcode() != Opc || !BOp->hasOneUse() ||
1010 BOp->getParent() != CurBB->getBasicBlock() ||
1011 !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
1012 !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
1013 const BasicBlock *BB = CurBB->getBasicBlock();
1014
1015 // If the leaf of the tree is a comparison, merge the condition into
1016 // the caseblock.
Chris Lattner3c261012008-10-11 00:08:02 +00001017 if (isa<CmpInst>(Cond) &&
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001018 // The operands of the cmp have to be in this block. We don't know
1019 // how to export them from some other block. If this is the first block
1020 // of the sequence, no exporting is needed.
1021 (CurBB == CurMBB ||
1022 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
1023 isExportableFromCurrentBlock(BOp->getOperand(1), BB)))) {
1024 BOp = cast<Instruction>(Cond);
1025 ISD::CondCode Condition;
1026 if (ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
1027 switch (IC->getPredicate()) {
1028 default: assert(0 && "Unknown icmp predicate opcode!");
1029 case ICmpInst::ICMP_EQ: Condition = ISD::SETEQ; break;
1030 case ICmpInst::ICMP_NE: Condition = ISD::SETNE; break;
1031 case ICmpInst::ICMP_SLE: Condition = ISD::SETLE; break;
1032 case ICmpInst::ICMP_ULE: Condition = ISD::SETULE; break;
1033 case ICmpInst::ICMP_SGE: Condition = ISD::SETGE; break;
1034 case ICmpInst::ICMP_UGE: Condition = ISD::SETUGE; break;
1035 case ICmpInst::ICMP_SLT: Condition = ISD::SETLT; break;
1036 case ICmpInst::ICMP_ULT: Condition = ISD::SETULT; break;
1037 case ICmpInst::ICMP_SGT: Condition = ISD::SETGT; break;
1038 case ICmpInst::ICMP_UGT: Condition = ISD::SETUGT; break;
1039 }
1040 } else if (FCmpInst *FC = dyn_cast<FCmpInst>(Cond)) {
1041 ISD::CondCode FPC, FOC;
1042 switch (FC->getPredicate()) {
1043 default: assert(0 && "Unknown fcmp predicate opcode!");
1044 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
1045 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
1046 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
1047 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
1048 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
1049 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
1050 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
1051 case FCmpInst::FCMP_ORD: FOC = FPC = ISD::SETO; break;
1052 case FCmpInst::FCMP_UNO: FOC = FPC = ISD::SETUO; break;
1053 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
1054 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
1055 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
1056 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
1057 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
1058 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
1059 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
1060 }
1061 if (FiniteOnlyFPMath())
1062 Condition = FOC;
1063 else
1064 Condition = FPC;
1065 } else {
1066 Condition = ISD::SETEQ; // silence warning.
1067 assert(0 && "Unknown compare instruction");
1068 }
1069
1070 CaseBlock CB(Condition, BOp->getOperand(0),
1071 BOp->getOperand(1), NULL, TBB, FBB, CurBB);
1072 SwitchCases.push_back(CB);
1073 return;
1074 }
1075
1076 // Create a CaseBlock record representing this branch.
1077 CaseBlock CB(ISD::SETEQ, Cond, ConstantInt::getTrue(),
1078 NULL, TBB, FBB, CurBB);
1079 SwitchCases.push_back(CB);
1080 return;
1081 }
1082
1083
1084 // Create TmpBB after CurBB.
1085 MachineFunction::iterator BBI = CurBB;
1086 MachineFunction &MF = DAG.getMachineFunction();
1087 MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
1088 CurBB->getParent()->insert(++BBI, TmpBB);
1089
1090 if (Opc == Instruction::Or) {
1091 // Codegen X | Y as:
1092 // jmp_if_X TBB
1093 // jmp TmpBB
1094 // TmpBB:
1095 // jmp_if_Y TBB
1096 // jmp FBB
1097 //
1098
1099 // Emit the LHS condition.
1100 FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, Opc);
1101
1102 // Emit the RHS condition into TmpBB.
1103 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
1104 } else {
1105 assert(Opc == Instruction::And && "Unknown merge op!");
1106 // Codegen X & Y as:
1107 // jmp_if_X TmpBB
1108 // jmp FBB
1109 // TmpBB:
1110 // jmp_if_Y TBB
1111 // jmp FBB
1112 //
1113 // This requires creation of TmpBB after CurBB.
1114
1115 // Emit the LHS condition.
1116 FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, Opc);
1117
1118 // Emit the RHS condition into TmpBB.
1119 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
1120 }
1121}
1122
1123/// If the set of cases should be emitted as a series of branches, return true.
1124/// If we should emit this as a bunch of and/or'd together conditions, return
1125/// false.
1126bool
1127SelectionDAGLowering::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases){
1128 if (Cases.size() != 2) return true;
1129
1130 // If this is two comparisons of the same values or'd or and'd together, they
1131 // will get folded into a single comparison, so don't emit two blocks.
1132 if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
1133 Cases[0].CmpRHS == Cases[1].CmpRHS) ||
1134 (Cases[0].CmpRHS == Cases[1].CmpLHS &&
1135 Cases[0].CmpLHS == Cases[1].CmpRHS)) {
1136 return false;
1137 }
1138
1139 return true;
1140}
1141
1142void SelectionDAGLowering::visitBr(BranchInst &I) {
1143 // Update machine-CFG edges.
1144 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
1145
1146 // Figure out which block is immediately after the current one.
1147 MachineBasicBlock *NextBlock = 0;
1148 MachineFunction::iterator BBI = CurMBB;
1149 if (++BBI != CurMBB->getParent()->end())
1150 NextBlock = BBI;
1151
1152 if (I.isUnconditional()) {
1153 // Update machine-CFG edges.
1154 CurMBB->addSuccessor(Succ0MBB);
1155
1156 // If this is not a fall-through branch, emit the branch.
1157 if (Succ0MBB != NextBlock)
1158 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getControlRoot(),
1159 DAG.getBasicBlock(Succ0MBB)));
1160 return;
1161 }
1162
1163 // If this condition is one of the special cases we handle, do special stuff
1164 // now.
1165 Value *CondVal = I.getCondition();
1166 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
1167
1168 // If this is a series of conditions that are or'd or and'd together, emit
1169 // this as a sequence of branches instead of setcc's with and/or operations.
1170 // For example, instead of something like:
1171 // cmp A, B
1172 // C = seteq
1173 // cmp D, E
1174 // F = setle
1175 // or C, F
1176 // jnz foo
1177 // Emit:
1178 // cmp A, B
1179 // je foo
1180 // cmp D, E
1181 // jle foo
1182 //
1183 if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
1184 if (BOp->hasOneUse() &&
1185 (BOp->getOpcode() == Instruction::And ||
1186 BOp->getOpcode() == Instruction::Or)) {
1187 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, CurMBB, BOp->getOpcode());
1188 // If the compares in later blocks need to use values not currently
1189 // exported from this block, export them now. This block should always
1190 // be the first entry.
1191 assert(SwitchCases[0].ThisBB == CurMBB && "Unexpected lowering!");
1192
1193 // Allow some cases to be rejected.
1194 if (ShouldEmitAsBranches(SwitchCases)) {
1195 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
1196 ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
1197 ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
1198 }
1199
1200 // Emit the branch for this block.
1201 visitSwitchCase(SwitchCases[0]);
1202 SwitchCases.erase(SwitchCases.begin());
1203 return;
1204 }
1205
1206 // Okay, we decided not to do this, remove any inserted MBB's and clear
1207 // SwitchCases.
1208 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
1209 CurMBB->getParent()->erase(SwitchCases[i].ThisBB);
1210
1211 SwitchCases.clear();
1212 }
1213 }
1214
1215 // Create a CaseBlock record representing this branch.
1216 CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(),
1217 NULL, Succ0MBB, Succ1MBB, CurMBB);
1218 // Use visitSwitchCase to actually insert the fast branch sequence for this
1219 // cond branch.
1220 visitSwitchCase(CB);
1221}
1222
1223/// visitSwitchCase - Emits the necessary code to represent a single node in
1224/// the binary search tree resulting from lowering a switch instruction.
1225void SelectionDAGLowering::visitSwitchCase(CaseBlock &CB) {
1226 SDValue Cond;
1227 SDValue CondLHS = getValue(CB.CmpLHS);
1228
1229 // Build the setcc now.
1230 if (CB.CmpMHS == NULL) {
1231 // Fold "(X == true)" to X and "(X == false)" to !X to
1232 // handle common cases produced by branch lowering.
1233 if (CB.CmpRHS == ConstantInt::getTrue() && CB.CC == ISD::SETEQ)
1234 Cond = CondLHS;
1235 else if (CB.CmpRHS == ConstantInt::getFalse() && CB.CC == ISD::SETEQ) {
1236 SDValue True = DAG.getConstant(1, CondLHS.getValueType());
1237 Cond = DAG.getNode(ISD::XOR, CondLHS.getValueType(), CondLHS, True);
1238 } else
1239 Cond = DAG.getSetCC(MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
1240 } else {
1241 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
1242
1243 uint64_t Low = cast<ConstantInt>(CB.CmpLHS)->getSExtValue();
1244 uint64_t High = cast<ConstantInt>(CB.CmpRHS)->getSExtValue();
1245
1246 SDValue CmpOp = getValue(CB.CmpMHS);
1247 MVT VT = CmpOp.getValueType();
1248
1249 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
1250 Cond = DAG.getSetCC(MVT::i1, CmpOp, DAG.getConstant(High, VT), ISD::SETLE);
1251 } else {
1252 SDValue SUB = DAG.getNode(ISD::SUB, VT, CmpOp, DAG.getConstant(Low, VT));
1253 Cond = DAG.getSetCC(MVT::i1, SUB,
1254 DAG.getConstant(High-Low, VT), ISD::SETULE);
1255 }
1256 }
1257
1258 // Update successor info
1259 CurMBB->addSuccessor(CB.TrueBB);
1260 CurMBB->addSuccessor(CB.FalseBB);
1261
1262 // Set NextBlock to be the MBB immediately after the current one, if any.
1263 // This is used to avoid emitting unnecessary branches to the next block.
1264 MachineBasicBlock *NextBlock = 0;
1265 MachineFunction::iterator BBI = CurMBB;
1266 if (++BBI != CurMBB->getParent()->end())
1267 NextBlock = BBI;
1268
1269 // If the lhs block is the next block, invert the condition so that we can
1270 // fall through to the lhs instead of the rhs block.
1271 if (CB.TrueBB == NextBlock) {
1272 std::swap(CB.TrueBB, CB.FalseBB);
1273 SDValue True = DAG.getConstant(1, Cond.getValueType());
1274 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
1275 }
1276 SDValue BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, getControlRoot(), Cond,
1277 DAG.getBasicBlock(CB.TrueBB));
1278
1279 // If the branch was constant folded, fix up the CFG.
1280 if (BrCond.getOpcode() == ISD::BR) {
1281 CurMBB->removeSuccessor(CB.FalseBB);
1282 DAG.setRoot(BrCond);
1283 } else {
1284 // Otherwise, go ahead and insert the false branch.
1285 if (BrCond == getControlRoot())
1286 CurMBB->removeSuccessor(CB.TrueBB);
1287
1288 if (CB.FalseBB == NextBlock)
1289 DAG.setRoot(BrCond);
1290 else
1291 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond,
1292 DAG.getBasicBlock(CB.FalseBB)));
1293 }
1294}
1295
1296/// visitJumpTable - Emit JumpTable node in the current MBB
1297void SelectionDAGLowering::visitJumpTable(JumpTable &JT) {
1298 // Emit the code for the jump table
1299 assert(JT.Reg != -1U && "Should lower JT Header first!");
1300 MVT PTy = TLI.getPointerTy();
1301 SDValue Index = DAG.getCopyFromReg(getControlRoot(), JT.Reg, PTy);
1302 SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
1303 DAG.setRoot(DAG.getNode(ISD::BR_JT, MVT::Other, Index.getValue(1),
1304 Table, Index));
1305 return;
1306}
1307
1308/// visitJumpTableHeader - This function emits necessary code to produce index
1309/// in the JumpTable from switch case.
1310void SelectionDAGLowering::visitJumpTableHeader(JumpTable &JT,
1311 JumpTableHeader &JTH) {
1312 // Subtract the lowest switch case value from the value being switched on
1313 // and conditional branch to default mbb if the result is greater than the
1314 // difference between smallest and largest cases.
1315 SDValue SwitchOp = getValue(JTH.SValue);
1316 MVT VT = SwitchOp.getValueType();
1317 SDValue SUB = DAG.getNode(ISD::SUB, VT, SwitchOp,
1318 DAG.getConstant(JTH.First, VT));
1319
1320 // The SDNode we just created, which holds the value being switched on
1321 // minus the the smallest case value, needs to be copied to a virtual
1322 // register so it can be used as an index into the jump table in a
1323 // subsequent basic block. This value may be smaller or larger than the
1324 // target's pointer type, and therefore require extension or truncating.
1325 if (VT.bitsGT(TLI.getPointerTy()))
1326 SwitchOp = DAG.getNode(ISD::TRUNCATE, TLI.getPointerTy(), SUB);
1327 else
1328 SwitchOp = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(), SUB);
1329
1330 unsigned JumpTableReg = FuncInfo.MakeReg(TLI.getPointerTy());
1331 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), JumpTableReg, SwitchOp);
1332 JT.Reg = JumpTableReg;
1333
1334 // Emit the range check for the jump table, and branch to the default
1335 // block for the switch statement if the value being switched on exceeds
1336 // the largest case in the switch.
1337 SDValue CMP = DAG.getSetCC(TLI.getSetCCResultType(SUB), SUB,
1338 DAG.getConstant(JTH.Last-JTH.First,VT),
1339 ISD::SETUGT);
1340
1341 // Set NextBlock to be the MBB immediately after the current one, if any.
1342 // This is used to avoid emitting unnecessary branches to the next block.
1343 MachineBasicBlock *NextBlock = 0;
1344 MachineFunction::iterator BBI = CurMBB;
1345 if (++BBI != CurMBB->getParent()->end())
1346 NextBlock = BBI;
1347
1348 SDValue BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, CopyTo, CMP,
1349 DAG.getBasicBlock(JT.Default));
1350
1351 if (JT.MBB == NextBlock)
1352 DAG.setRoot(BrCond);
1353 else
1354 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond,
1355 DAG.getBasicBlock(JT.MBB)));
1356
1357 return;
1358}
1359
1360/// visitBitTestHeader - This function emits necessary code to produce value
1361/// suitable for "bit tests"
1362void SelectionDAGLowering::visitBitTestHeader(BitTestBlock &B) {
1363 // Subtract the minimum value
1364 SDValue SwitchOp = getValue(B.SValue);
1365 MVT VT = SwitchOp.getValueType();
1366 SDValue SUB = DAG.getNode(ISD::SUB, VT, SwitchOp,
1367 DAG.getConstant(B.First, VT));
1368
1369 // Check range
1370 SDValue RangeCmp = DAG.getSetCC(TLI.getSetCCResultType(SUB), SUB,
1371 DAG.getConstant(B.Range, VT),
1372 ISD::SETUGT);
1373
1374 SDValue ShiftOp;
1375 if (VT.bitsGT(TLI.getShiftAmountTy()))
1376 ShiftOp = DAG.getNode(ISD::TRUNCATE, TLI.getShiftAmountTy(), SUB);
1377 else
1378 ShiftOp = DAG.getNode(ISD::ZERO_EXTEND, TLI.getShiftAmountTy(), SUB);
1379
1380 // Make desired shift
1381 SDValue SwitchVal = DAG.getNode(ISD::SHL, TLI.getPointerTy(),
1382 DAG.getConstant(1, TLI.getPointerTy()),
1383 ShiftOp);
1384
1385 unsigned SwitchReg = FuncInfo.MakeReg(TLI.getPointerTy());
1386 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), SwitchReg, SwitchVal);
1387 B.Reg = SwitchReg;
1388
1389 // Set NextBlock to be the MBB immediately after the current one, if any.
1390 // This is used to avoid emitting unnecessary branches to the next block.
1391 MachineBasicBlock *NextBlock = 0;
1392 MachineFunction::iterator BBI = CurMBB;
1393 if (++BBI != CurMBB->getParent()->end())
1394 NextBlock = BBI;
1395
1396 MachineBasicBlock* MBB = B.Cases[0].ThisBB;
1397
1398 CurMBB->addSuccessor(B.Default);
1399 CurMBB->addSuccessor(MBB);
1400
1401 SDValue BrRange = DAG.getNode(ISD::BRCOND, MVT::Other, CopyTo, RangeCmp,
1402 DAG.getBasicBlock(B.Default));
1403
1404 if (MBB == NextBlock)
1405 DAG.setRoot(BrRange);
1406 else
1407 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, CopyTo,
1408 DAG.getBasicBlock(MBB)));
1409
1410 return;
1411}
1412
1413/// visitBitTestCase - this function produces one "bit test"
1414void SelectionDAGLowering::visitBitTestCase(MachineBasicBlock* NextMBB,
1415 unsigned Reg,
1416 BitTestCase &B) {
1417 // Emit bit tests and jumps
1418 SDValue SwitchVal = DAG.getCopyFromReg(getControlRoot(), Reg,
1419 TLI.getPointerTy());
1420
1421 SDValue AndOp = DAG.getNode(ISD::AND, TLI.getPointerTy(), SwitchVal,
1422 DAG.getConstant(B.Mask, TLI.getPointerTy()));
1423 SDValue AndCmp = DAG.getSetCC(TLI.getSetCCResultType(AndOp), AndOp,
1424 DAG.getConstant(0, TLI.getPointerTy()),
1425 ISD::SETNE);
1426
1427 CurMBB->addSuccessor(B.TargetBB);
1428 CurMBB->addSuccessor(NextMBB);
1429
1430 SDValue BrAnd = DAG.getNode(ISD::BRCOND, MVT::Other, getControlRoot(),
1431 AndCmp, DAG.getBasicBlock(B.TargetBB));
1432
1433 // Set NextBlock to be the MBB immediately after the current one, if any.
1434 // This is used to avoid emitting unnecessary branches to the next block.
1435 MachineBasicBlock *NextBlock = 0;
1436 MachineFunction::iterator BBI = CurMBB;
1437 if (++BBI != CurMBB->getParent()->end())
1438 NextBlock = BBI;
1439
1440 if (NextMBB == NextBlock)
1441 DAG.setRoot(BrAnd);
1442 else
1443 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrAnd,
1444 DAG.getBasicBlock(NextMBB)));
1445
1446 return;
1447}
1448
1449void SelectionDAGLowering::visitInvoke(InvokeInst &I) {
1450 // Retrieve successors.
1451 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
1452 MachineBasicBlock *LandingPad = FuncInfo.MBBMap[I.getSuccessor(1)];
1453
1454 if (isa<InlineAsm>(I.getCalledValue()))
1455 visitInlineAsm(&I);
1456 else
1457 LowerCallTo(&I, getValue(I.getOperand(0)), false, LandingPad);
1458
1459 // If the value of the invoke is used outside of its defining block, make it
1460 // available as a virtual register.
1461 if (!I.use_empty()) {
1462 DenseMap<const Value*, unsigned>::iterator VMI = FuncInfo.ValueMap.find(&I);
1463 if (VMI != FuncInfo.ValueMap.end())
1464 CopyValueToVirtualRegister(&I, VMI->second);
1465 }
1466
1467 // Update successor info
1468 CurMBB->addSuccessor(Return);
1469 CurMBB->addSuccessor(LandingPad);
1470
1471 // Drop into normal successor.
1472 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getControlRoot(),
1473 DAG.getBasicBlock(Return)));
1474}
1475
1476void SelectionDAGLowering::visitUnwind(UnwindInst &I) {
1477}
1478
1479/// handleSmallSwitchCaseRange - Emit a series of specific tests (suitable for
1480/// small case ranges).
1481bool SelectionDAGLowering::handleSmallSwitchRange(CaseRec& CR,
1482 CaseRecVector& WorkList,
1483 Value* SV,
1484 MachineBasicBlock* Default) {
1485 Case& BackCase = *(CR.Range.second-1);
1486
1487 // Size is the number of Cases represented by this range.
1488 unsigned Size = CR.Range.second - CR.Range.first;
1489 if (Size > 3)
1490 return false;
1491
1492 // Get the MachineFunction which holds the current MBB. This is used when
1493 // inserting any additional MBBs necessary to represent the switch.
1494 MachineFunction *CurMF = CurMBB->getParent();
1495
1496 // Figure out which block is immediately after the current one.
1497 MachineBasicBlock *NextBlock = 0;
1498 MachineFunction::iterator BBI = CR.CaseBB;
1499
1500 if (++BBI != CurMBB->getParent()->end())
1501 NextBlock = BBI;
1502
1503 // TODO: If any two of the cases has the same destination, and if one value
1504 // is the same as the other, but has one bit unset that the other has set,
1505 // use bit manipulation to do two compares at once. For example:
1506 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
1507
1508 // Rearrange the case blocks so that the last one falls through if possible.
1509 if (NextBlock && Default != NextBlock && BackCase.BB != NextBlock) {
1510 // The last case block won't fall through into 'NextBlock' if we emit the
1511 // branches in this order. See if rearranging a case value would help.
1512 for (CaseItr I = CR.Range.first, E = CR.Range.second-1; I != E; ++I) {
1513 if (I->BB == NextBlock) {
1514 std::swap(*I, BackCase);
1515 break;
1516 }
1517 }
1518 }
1519
1520 // Create a CaseBlock record representing a conditional branch to
1521 // the Case's target mbb if the value being switched on SV is equal
1522 // to C.
1523 MachineBasicBlock *CurBlock = CR.CaseBB;
1524 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I) {
1525 MachineBasicBlock *FallThrough;
1526 if (I != E-1) {
1527 FallThrough = CurMF->CreateMachineBasicBlock(CurBlock->getBasicBlock());
1528 CurMF->insert(BBI, FallThrough);
1529 } else {
1530 // If the last case doesn't match, go to the default block.
1531 FallThrough = Default;
1532 }
1533
1534 Value *RHS, *LHS, *MHS;
1535 ISD::CondCode CC;
1536 if (I->High == I->Low) {
1537 // This is just small small case range :) containing exactly 1 case
1538 CC = ISD::SETEQ;
1539 LHS = SV; RHS = I->High; MHS = NULL;
1540 } else {
1541 CC = ISD::SETLE;
1542 LHS = I->Low; MHS = SV; RHS = I->High;
1543 }
1544 CaseBlock CB(CC, LHS, RHS, MHS, I->BB, FallThrough, CurBlock);
1545
1546 // If emitting the first comparison, just call visitSwitchCase to emit the
1547 // code into the current block. Otherwise, push the CaseBlock onto the
1548 // vector to be later processed by SDISel, and insert the node's MBB
1549 // before the next MBB.
1550 if (CurBlock == CurMBB)
1551 visitSwitchCase(CB);
1552 else
1553 SwitchCases.push_back(CB);
1554
1555 CurBlock = FallThrough;
1556 }
1557
1558 return true;
1559}
1560
1561static inline bool areJTsAllowed(const TargetLowering &TLI) {
1562 return !DisableJumpTables &&
1563 (TLI.isOperationLegal(ISD::BR_JT, MVT::Other) ||
1564 TLI.isOperationLegal(ISD::BRIND, MVT::Other));
1565}
1566
1567/// handleJTSwitchCase - Emit jumptable for current switch case range
1568bool SelectionDAGLowering::handleJTSwitchCase(CaseRec& CR,
1569 CaseRecVector& WorkList,
1570 Value* SV,
1571 MachineBasicBlock* Default) {
1572 Case& FrontCase = *CR.Range.first;
1573 Case& BackCase = *(CR.Range.second-1);
1574
1575 int64_t First = cast<ConstantInt>(FrontCase.Low)->getSExtValue();
1576 int64_t Last = cast<ConstantInt>(BackCase.High)->getSExtValue();
1577
1578 uint64_t TSize = 0;
1579 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1580 I!=E; ++I)
1581 TSize += I->size();
1582
1583 if (!areJTsAllowed(TLI) || TSize <= 3)
1584 return false;
1585
1586 double Density = (double)TSize / (double)((Last - First) + 1ULL);
1587 if (Density < 0.4)
1588 return false;
1589
1590 DOUT << "Lowering jump table\n"
1591 << "First entry: " << First << ". Last entry: " << Last << "\n"
1592 << "Size: " << TSize << ". Density: " << Density << "\n\n";
1593
1594 // Get the MachineFunction which holds the current MBB. This is used when
1595 // inserting any additional MBBs necessary to represent the switch.
1596 MachineFunction *CurMF = CurMBB->getParent();
1597
1598 // Figure out which block is immediately after the current one.
1599 MachineBasicBlock *NextBlock = 0;
1600 MachineFunction::iterator BBI = CR.CaseBB;
1601
1602 if (++BBI != CurMBB->getParent()->end())
1603 NextBlock = BBI;
1604
1605 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1606
1607 // Create a new basic block to hold the code for loading the address
1608 // of the jump table, and jumping to it. Update successor information;
1609 // we will either branch to the default case for the switch, or the jump
1610 // table.
1611 MachineBasicBlock *JumpTableBB = CurMF->CreateMachineBasicBlock(LLVMBB);
1612 CurMF->insert(BBI, JumpTableBB);
1613 CR.CaseBB->addSuccessor(Default);
1614 CR.CaseBB->addSuccessor(JumpTableBB);
1615
1616 // Build a vector of destination BBs, corresponding to each target
1617 // of the jump table. If the value of the jump table slot corresponds to
1618 // a case statement, push the case's BB onto the vector, otherwise, push
1619 // the default BB.
1620 std::vector<MachineBasicBlock*> DestBBs;
1621 int64_t TEI = First;
1622 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++TEI) {
1623 int64_t Low = cast<ConstantInt>(I->Low)->getSExtValue();
1624 int64_t High = cast<ConstantInt>(I->High)->getSExtValue();
1625
1626 if ((Low <= TEI) && (TEI <= High)) {
1627 DestBBs.push_back(I->BB);
1628 if (TEI==High)
1629 ++I;
1630 } else {
1631 DestBBs.push_back(Default);
1632 }
1633 }
1634
1635 // Update successor info. Add one edge to each unique successor.
1636 BitVector SuccsHandled(CR.CaseBB->getParent()->getNumBlockIDs());
1637 for (std::vector<MachineBasicBlock*>::iterator I = DestBBs.begin(),
1638 E = DestBBs.end(); I != E; ++I) {
1639 if (!SuccsHandled[(*I)->getNumber()]) {
1640 SuccsHandled[(*I)->getNumber()] = true;
1641 JumpTableBB->addSuccessor(*I);
1642 }
1643 }
1644
1645 // Create a jump table index for this jump table, or return an existing
1646 // one.
1647 unsigned JTI = CurMF->getJumpTableInfo()->getJumpTableIndex(DestBBs);
1648
1649 // Set the jump table information so that we can codegen it as a second
1650 // MachineBasicBlock
1651 JumpTable JT(-1U, JTI, JumpTableBB, Default);
1652 JumpTableHeader JTH(First, Last, SV, CR.CaseBB, (CR.CaseBB == CurMBB));
1653 if (CR.CaseBB == CurMBB)
1654 visitJumpTableHeader(JT, JTH);
1655
1656 JTCases.push_back(JumpTableBlock(JTH, JT));
1657
1658 return true;
1659}
1660
1661/// handleBTSplitSwitchCase - emit comparison and split binary search tree into
1662/// 2 subtrees.
1663bool SelectionDAGLowering::handleBTSplitSwitchCase(CaseRec& CR,
1664 CaseRecVector& WorkList,
1665 Value* SV,
1666 MachineBasicBlock* Default) {
1667 // Get the MachineFunction which holds the current MBB. This is used when
1668 // inserting any additional MBBs necessary to represent the switch.
1669 MachineFunction *CurMF = CurMBB->getParent();
1670
1671 // Figure out which block is immediately after the current one.
1672 MachineBasicBlock *NextBlock = 0;
1673 MachineFunction::iterator BBI = CR.CaseBB;
1674
1675 if (++BBI != CurMBB->getParent()->end())
1676 NextBlock = BBI;
1677
1678 Case& FrontCase = *CR.Range.first;
1679 Case& BackCase = *(CR.Range.second-1);
1680 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1681
1682 // Size is the number of Cases represented by this range.
1683 unsigned Size = CR.Range.second - CR.Range.first;
1684
1685 int64_t First = cast<ConstantInt>(FrontCase.Low)->getSExtValue();
1686 int64_t Last = cast<ConstantInt>(BackCase.High)->getSExtValue();
1687 double FMetric = 0;
1688 CaseItr Pivot = CR.Range.first + Size/2;
1689
1690 // Select optimal pivot, maximizing sum density of LHS and RHS. This will
1691 // (heuristically) allow us to emit JumpTable's later.
1692 uint64_t TSize = 0;
1693 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1694 I!=E; ++I)
1695 TSize += I->size();
1696
1697 uint64_t LSize = FrontCase.size();
1698 uint64_t RSize = TSize-LSize;
1699 DOUT << "Selecting best pivot: \n"
1700 << "First: " << First << ", Last: " << Last <<"\n"
1701 << "LSize: " << LSize << ", RSize: " << RSize << "\n";
1702 for (CaseItr I = CR.Range.first, J=I+1, E = CR.Range.second;
1703 J!=E; ++I, ++J) {
1704 int64_t LEnd = cast<ConstantInt>(I->High)->getSExtValue();
1705 int64_t RBegin = cast<ConstantInt>(J->Low)->getSExtValue();
1706 assert((RBegin-LEnd>=1) && "Invalid case distance");
1707 double LDensity = (double)LSize / (double)((LEnd - First) + 1ULL);
1708 double RDensity = (double)RSize / (double)((Last - RBegin) + 1ULL);
1709 double Metric = Log2_64(RBegin-LEnd)*(LDensity+RDensity);
1710 // Should always split in some non-trivial place
1711 DOUT <<"=>Step\n"
1712 << "LEnd: " << LEnd << ", RBegin: " << RBegin << "\n"
1713 << "LDensity: " << LDensity << ", RDensity: " << RDensity << "\n"
1714 << "Metric: " << Metric << "\n";
1715 if (FMetric < Metric) {
1716 Pivot = J;
1717 FMetric = Metric;
1718 DOUT << "Current metric set to: " << FMetric << "\n";
1719 }
1720
1721 LSize += J->size();
1722 RSize -= J->size();
1723 }
1724 if (areJTsAllowed(TLI)) {
1725 // If our case is dense we *really* should handle it earlier!
1726 assert((FMetric > 0) && "Should handle dense range earlier!");
1727 } else {
1728 Pivot = CR.Range.first + Size/2;
1729 }
1730
1731 CaseRange LHSR(CR.Range.first, Pivot);
1732 CaseRange RHSR(Pivot, CR.Range.second);
1733 Constant *C = Pivot->Low;
1734 MachineBasicBlock *FalseBB = 0, *TrueBB = 0;
1735
1736 // We know that we branch to the LHS if the Value being switched on is
1737 // less than the Pivot value, C. We use this to optimize our binary
1738 // tree a bit, by recognizing that if SV is greater than or equal to the
1739 // LHS's Case Value, and that Case Value is exactly one less than the
1740 // Pivot's Value, then we can branch directly to the LHS's Target,
1741 // rather than creating a leaf node for it.
1742 if ((LHSR.second - LHSR.first) == 1 &&
1743 LHSR.first->High == CR.GE &&
1744 cast<ConstantInt>(C)->getSExtValue() ==
1745 (cast<ConstantInt>(CR.GE)->getSExtValue() + 1LL)) {
1746 TrueBB = LHSR.first->BB;
1747 } else {
1748 TrueBB = CurMF->CreateMachineBasicBlock(LLVMBB);
1749 CurMF->insert(BBI, TrueBB);
1750 WorkList.push_back(CaseRec(TrueBB, C, CR.GE, LHSR));
1751 }
1752
1753 // Similar to the optimization above, if the Value being switched on is
1754 // known to be less than the Constant CR.LT, and the current Case Value
1755 // is CR.LT - 1, then we can branch directly to the target block for
1756 // the current Case Value, rather than emitting a RHS leaf node for it.
1757 if ((RHSR.second - RHSR.first) == 1 && CR.LT &&
1758 cast<ConstantInt>(RHSR.first->Low)->getSExtValue() ==
1759 (cast<ConstantInt>(CR.LT)->getSExtValue() - 1LL)) {
1760 FalseBB = RHSR.first->BB;
1761 } else {
1762 FalseBB = CurMF->CreateMachineBasicBlock(LLVMBB);
1763 CurMF->insert(BBI, FalseBB);
1764 WorkList.push_back(CaseRec(FalseBB,CR.LT,C,RHSR));
1765 }
1766
1767 // Create a CaseBlock record representing a conditional branch to
1768 // the LHS node if the value being switched on SV is less than C.
1769 // Otherwise, branch to LHS.
1770 CaseBlock CB(ISD::SETLT, SV, C, NULL, TrueBB, FalseBB, CR.CaseBB);
1771
1772 if (CR.CaseBB == CurMBB)
1773 visitSwitchCase(CB);
1774 else
1775 SwitchCases.push_back(CB);
1776
1777 return true;
1778}
1779
1780/// handleBitTestsSwitchCase - if current case range has few destination and
1781/// range span less, than machine word bitwidth, encode case range into series
1782/// of masks and emit bit tests with these masks.
1783bool SelectionDAGLowering::handleBitTestsSwitchCase(CaseRec& CR,
1784 CaseRecVector& WorkList,
1785 Value* SV,
1786 MachineBasicBlock* Default){
1787 unsigned IntPtrBits = TLI.getPointerTy().getSizeInBits();
1788
1789 Case& FrontCase = *CR.Range.first;
1790 Case& BackCase = *(CR.Range.second-1);
1791
1792 // Get the MachineFunction which holds the current MBB. This is used when
1793 // inserting any additional MBBs necessary to represent the switch.
1794 MachineFunction *CurMF = CurMBB->getParent();
1795
1796 unsigned numCmps = 0;
1797 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1798 I!=E; ++I) {
1799 // Single case counts one, case range - two.
1800 if (I->Low == I->High)
1801 numCmps +=1;
1802 else
1803 numCmps +=2;
1804 }
1805
1806 // Count unique destinations
1807 SmallSet<MachineBasicBlock*, 4> Dests;
1808 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
1809 Dests.insert(I->BB);
1810 if (Dests.size() > 3)
1811 // Don't bother the code below, if there are too much unique destinations
1812 return false;
1813 }
1814 DOUT << "Total number of unique destinations: " << Dests.size() << "\n"
1815 << "Total number of comparisons: " << numCmps << "\n";
1816
1817 // Compute span of values.
1818 Constant* minValue = FrontCase.Low;
1819 Constant* maxValue = BackCase.High;
1820 uint64_t range = cast<ConstantInt>(maxValue)->getSExtValue() -
1821 cast<ConstantInt>(minValue)->getSExtValue();
1822 DOUT << "Compare range: " << range << "\n"
1823 << "Low bound: " << cast<ConstantInt>(minValue)->getSExtValue() << "\n"
1824 << "High bound: " << cast<ConstantInt>(maxValue)->getSExtValue() << "\n";
1825
1826 if (range>=IntPtrBits ||
1827 (!(Dests.size() == 1 && numCmps >= 3) &&
1828 !(Dests.size() == 2 && numCmps >= 5) &&
1829 !(Dests.size() >= 3 && numCmps >= 6)))
1830 return false;
1831
1832 DOUT << "Emitting bit tests\n";
1833 int64_t lowBound = 0;
1834
1835 // Optimize the case where all the case values fit in a
1836 // word without having to subtract minValue. In this case,
1837 // we can optimize away the subtraction.
1838 if (cast<ConstantInt>(minValue)->getSExtValue() >= 0 &&
1839 cast<ConstantInt>(maxValue)->getSExtValue() < IntPtrBits) {
1840 range = cast<ConstantInt>(maxValue)->getSExtValue();
1841 } else {
1842 lowBound = cast<ConstantInt>(minValue)->getSExtValue();
1843 }
1844
1845 CaseBitsVector CasesBits;
1846 unsigned i, count = 0;
1847
1848 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
1849 MachineBasicBlock* Dest = I->BB;
1850 for (i = 0; i < count; ++i)
1851 if (Dest == CasesBits[i].BB)
1852 break;
1853
1854 if (i == count) {
1855 assert((count < 3) && "Too much destinations to test!");
1856 CasesBits.push_back(CaseBits(0, Dest, 0));
1857 count++;
1858 }
1859
1860 uint64_t lo = cast<ConstantInt>(I->Low)->getSExtValue() - lowBound;
1861 uint64_t hi = cast<ConstantInt>(I->High)->getSExtValue() - lowBound;
1862
1863 for (uint64_t j = lo; j <= hi; j++) {
1864 CasesBits[i].Mask |= 1ULL << j;
1865 CasesBits[i].Bits++;
1866 }
1867
1868 }
1869 std::sort(CasesBits.begin(), CasesBits.end(), CaseBitsCmp());
1870
1871 BitTestInfo BTC;
1872
1873 // Figure out which block is immediately after the current one.
1874 MachineFunction::iterator BBI = CR.CaseBB;
1875 ++BBI;
1876
1877 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1878
1879 DOUT << "Cases:\n";
1880 for (unsigned i = 0, e = CasesBits.size(); i!=e; ++i) {
1881 DOUT << "Mask: " << CasesBits[i].Mask << ", Bits: " << CasesBits[i].Bits
1882 << ", BB: " << CasesBits[i].BB << "\n";
1883
1884 MachineBasicBlock *CaseBB = CurMF->CreateMachineBasicBlock(LLVMBB);
1885 CurMF->insert(BBI, CaseBB);
1886 BTC.push_back(BitTestCase(CasesBits[i].Mask,
1887 CaseBB,
1888 CasesBits[i].BB));
1889 }
1890
1891 BitTestBlock BTB(lowBound, range, SV,
1892 -1U, (CR.CaseBB == CurMBB),
1893 CR.CaseBB, Default, BTC);
1894
1895 if (CR.CaseBB == CurMBB)
1896 visitBitTestHeader(BTB);
1897
1898 BitTestCases.push_back(BTB);
1899
1900 return true;
1901}
1902
1903
1904/// Clusterify - Transform simple list of Cases into list of CaseRange's
1905unsigned SelectionDAGLowering::Clusterify(CaseVector& Cases,
1906 const SwitchInst& SI) {
1907 unsigned numCmps = 0;
1908
1909 // Start with "simple" cases
1910 for (unsigned i = 1; i < SI.getNumSuccessors(); ++i) {
1911 MachineBasicBlock *SMBB = FuncInfo.MBBMap[SI.getSuccessor(i)];
1912 Cases.push_back(Case(SI.getSuccessorValue(i),
1913 SI.getSuccessorValue(i),
1914 SMBB));
1915 }
1916 std::sort(Cases.begin(), Cases.end(), CaseCmp());
1917
1918 // Merge case into clusters
1919 if (Cases.size()>=2)
1920 // Must recompute end() each iteration because it may be
1921 // invalidated by erase if we hold on to it
1922 for (CaseItr I=Cases.begin(), J=++(Cases.begin()); J!=Cases.end(); ) {
1923 int64_t nextValue = cast<ConstantInt>(J->Low)->getSExtValue();
1924 int64_t currentValue = cast<ConstantInt>(I->High)->getSExtValue();
1925 MachineBasicBlock* nextBB = J->BB;
1926 MachineBasicBlock* currentBB = I->BB;
1927
1928 // If the two neighboring cases go to the same destination, merge them
1929 // into a single case.
1930 if ((nextValue-currentValue==1) && (currentBB == nextBB)) {
1931 I->High = J->High;
1932 J = Cases.erase(J);
1933 } else {
1934 I = J++;
1935 }
1936 }
1937
1938 for (CaseItr I=Cases.begin(), E=Cases.end(); I!=E; ++I, ++numCmps) {
1939 if (I->Low != I->High)
1940 // A range counts double, since it requires two compares.
1941 ++numCmps;
1942 }
1943
1944 return numCmps;
1945}
1946
1947void SelectionDAGLowering::visitSwitch(SwitchInst &SI) {
1948 // Figure out which block is immediately after the current one.
1949 MachineBasicBlock *NextBlock = 0;
1950 MachineFunction::iterator BBI = CurMBB;
1951
1952 MachineBasicBlock *Default = FuncInfo.MBBMap[SI.getDefaultDest()];
1953
1954 // If there is only the default destination, branch to it if it is not the
1955 // next basic block. Otherwise, just fall through.
1956 if (SI.getNumOperands() == 2) {
1957 // Update machine-CFG edges.
1958
1959 // If this is not a fall-through branch, emit the branch.
1960 CurMBB->addSuccessor(Default);
1961 if (Default != NextBlock)
1962 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getControlRoot(),
1963 DAG.getBasicBlock(Default)));
1964
1965 return;
1966 }
1967
1968 // If there are any non-default case statements, create a vector of Cases
1969 // representing each one, and sort the vector so that we can efficiently
1970 // create a binary search tree from them.
1971 CaseVector Cases;
1972 unsigned numCmps = Clusterify(Cases, SI);
1973 DOUT << "Clusterify finished. Total clusters: " << Cases.size()
1974 << ". Total compares: " << numCmps << "\n";
1975
1976 // Get the Value to be switched on and default basic blocks, which will be
1977 // inserted into CaseBlock records, representing basic blocks in the binary
1978 // search tree.
1979 Value *SV = SI.getOperand(0);
1980
1981 // Push the initial CaseRec onto the worklist
1982 CaseRecVector WorkList;
1983 WorkList.push_back(CaseRec(CurMBB,0,0,CaseRange(Cases.begin(),Cases.end())));
1984
1985 while (!WorkList.empty()) {
1986 // Grab a record representing a case range to process off the worklist
1987 CaseRec CR = WorkList.back();
1988 WorkList.pop_back();
1989
1990 if (handleBitTestsSwitchCase(CR, WorkList, SV, Default))
1991 continue;
1992
1993 // If the range has few cases (two or less) emit a series of specific
1994 // tests.
1995 if (handleSmallSwitchRange(CR, WorkList, SV, Default))
1996 continue;
1997
1998 // If the switch has more than 5 blocks, and at least 40% dense, and the
1999 // target supports indirect branches, then emit a jump table rather than
2000 // lowering the switch to a binary tree of conditional branches.
2001 if (handleJTSwitchCase(CR, WorkList, SV, Default))
2002 continue;
2003
2004 // Emit binary tree. We need to pick a pivot, and push left and right ranges
2005 // onto the worklist. Leafs are handled via handleSmallSwitchRange() call.
2006 handleBTSplitSwitchCase(CR, WorkList, SV, Default);
2007 }
2008}
2009
2010
2011void SelectionDAGLowering::visitSub(User &I) {
2012 // -0.0 - X --> fneg
2013 const Type *Ty = I.getType();
2014 if (isa<VectorType>(Ty)) {
2015 if (ConstantVector *CV = dyn_cast<ConstantVector>(I.getOperand(0))) {
2016 const VectorType *DestTy = cast<VectorType>(I.getType());
2017 const Type *ElTy = DestTy->getElementType();
2018 if (ElTy->isFloatingPoint()) {
2019 unsigned VL = DestTy->getNumElements();
2020 std::vector<Constant*> NZ(VL, ConstantFP::getNegativeZero(ElTy));
2021 Constant *CNZ = ConstantVector::get(&NZ[0], NZ.size());
2022 if (CV == CNZ) {
2023 SDValue Op2 = getValue(I.getOperand(1));
2024 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
2025 return;
2026 }
2027 }
2028 }
2029 }
2030 if (Ty->isFloatingPoint()) {
2031 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
2032 if (CFP->isExactlyValue(ConstantFP::getNegativeZero(Ty)->getValueAPF())) {
2033 SDValue Op2 = getValue(I.getOperand(1));
2034 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
2035 return;
2036 }
2037 }
2038
2039 visitBinary(I, Ty->isFPOrFPVector() ? ISD::FSUB : ISD::SUB);
2040}
2041
2042void SelectionDAGLowering::visitBinary(User &I, unsigned OpCode) {
2043 SDValue Op1 = getValue(I.getOperand(0));
2044 SDValue Op2 = getValue(I.getOperand(1));
2045
2046 setValue(&I, DAG.getNode(OpCode, Op1.getValueType(), Op1, Op2));
2047}
2048
2049void SelectionDAGLowering::visitShift(User &I, unsigned Opcode) {
2050 SDValue Op1 = getValue(I.getOperand(0));
2051 SDValue Op2 = getValue(I.getOperand(1));
2052 if (!isa<VectorType>(I.getType())) {
2053 if (TLI.getShiftAmountTy().bitsLT(Op2.getValueType()))
2054 Op2 = DAG.getNode(ISD::TRUNCATE, TLI.getShiftAmountTy(), Op2);
2055 else if (TLI.getShiftAmountTy().bitsGT(Op2.getValueType()))
2056 Op2 = DAG.getNode(ISD::ANY_EXTEND, TLI.getShiftAmountTy(), Op2);
2057 }
2058
2059 setValue(&I, DAG.getNode(Opcode, Op1.getValueType(), Op1, Op2));
2060}
2061
2062void SelectionDAGLowering::visitICmp(User &I) {
2063 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
2064 if (ICmpInst *IC = dyn_cast<ICmpInst>(&I))
2065 predicate = IC->getPredicate();
2066 else if (ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
2067 predicate = ICmpInst::Predicate(IC->getPredicate());
2068 SDValue Op1 = getValue(I.getOperand(0));
2069 SDValue Op2 = getValue(I.getOperand(1));
2070 ISD::CondCode Opcode;
2071 switch (predicate) {
2072 case ICmpInst::ICMP_EQ : Opcode = ISD::SETEQ; break;
2073 case ICmpInst::ICMP_NE : Opcode = ISD::SETNE; break;
2074 case ICmpInst::ICMP_UGT : Opcode = ISD::SETUGT; break;
2075 case ICmpInst::ICMP_UGE : Opcode = ISD::SETUGE; break;
2076 case ICmpInst::ICMP_ULT : Opcode = ISD::SETULT; break;
2077 case ICmpInst::ICMP_ULE : Opcode = ISD::SETULE; break;
2078 case ICmpInst::ICMP_SGT : Opcode = ISD::SETGT; break;
2079 case ICmpInst::ICMP_SGE : Opcode = ISD::SETGE; break;
2080 case ICmpInst::ICMP_SLT : Opcode = ISD::SETLT; break;
2081 case ICmpInst::ICMP_SLE : Opcode = ISD::SETLE; break;
2082 default:
2083 assert(!"Invalid ICmp predicate value");
2084 Opcode = ISD::SETEQ;
2085 break;
2086 }
2087 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Opcode));
2088}
2089
2090void SelectionDAGLowering::visitFCmp(User &I) {
2091 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
2092 if (FCmpInst *FC = dyn_cast<FCmpInst>(&I))
2093 predicate = FC->getPredicate();
2094 else if (ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
2095 predicate = FCmpInst::Predicate(FC->getPredicate());
2096 SDValue Op1 = getValue(I.getOperand(0));
2097 SDValue Op2 = getValue(I.getOperand(1));
2098 ISD::CondCode Condition, FOC, FPC;
2099 switch (predicate) {
2100 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
2101 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
2102 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
2103 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
2104 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
2105 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
2106 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
2107 case FCmpInst::FCMP_ORD: FOC = FPC = ISD::SETO; break;
2108 case FCmpInst::FCMP_UNO: FOC = FPC = ISD::SETUO; break;
2109 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
2110 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
2111 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
2112 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
2113 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
2114 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
2115 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
2116 default:
2117 assert(!"Invalid FCmp predicate value");
2118 FOC = FPC = ISD::SETFALSE;
2119 break;
2120 }
2121 if (FiniteOnlyFPMath())
2122 Condition = FOC;
2123 else
2124 Condition = FPC;
2125 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Condition));
2126}
2127
2128void SelectionDAGLowering::visitVICmp(User &I) {
2129 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
2130 if (VICmpInst *IC = dyn_cast<VICmpInst>(&I))
2131 predicate = IC->getPredicate();
2132 else if (ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
2133 predicate = ICmpInst::Predicate(IC->getPredicate());
2134 SDValue Op1 = getValue(I.getOperand(0));
2135 SDValue Op2 = getValue(I.getOperand(1));
2136 ISD::CondCode Opcode;
2137 switch (predicate) {
2138 case ICmpInst::ICMP_EQ : Opcode = ISD::SETEQ; break;
2139 case ICmpInst::ICMP_NE : Opcode = ISD::SETNE; break;
2140 case ICmpInst::ICMP_UGT : Opcode = ISD::SETUGT; break;
2141 case ICmpInst::ICMP_UGE : Opcode = ISD::SETUGE; break;
2142 case ICmpInst::ICMP_ULT : Opcode = ISD::SETULT; break;
2143 case ICmpInst::ICMP_ULE : Opcode = ISD::SETULE; break;
2144 case ICmpInst::ICMP_SGT : Opcode = ISD::SETGT; break;
2145 case ICmpInst::ICMP_SGE : Opcode = ISD::SETGE; break;
2146 case ICmpInst::ICMP_SLT : Opcode = ISD::SETLT; break;
2147 case ICmpInst::ICMP_SLE : Opcode = ISD::SETLE; break;
2148 default:
2149 assert(!"Invalid ICmp predicate value");
2150 Opcode = ISD::SETEQ;
2151 break;
2152 }
2153 setValue(&I, DAG.getVSetCC(Op1.getValueType(), Op1, Op2, Opcode));
2154}
2155
2156void SelectionDAGLowering::visitVFCmp(User &I) {
2157 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
2158 if (VFCmpInst *FC = dyn_cast<VFCmpInst>(&I))
2159 predicate = FC->getPredicate();
2160 else if (ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
2161 predicate = FCmpInst::Predicate(FC->getPredicate());
2162 SDValue Op1 = getValue(I.getOperand(0));
2163 SDValue Op2 = getValue(I.getOperand(1));
2164 ISD::CondCode Condition, FOC, FPC;
2165 switch (predicate) {
2166 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
2167 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
2168 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
2169 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
2170 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
2171 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
2172 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
2173 case FCmpInst::FCMP_ORD: FOC = FPC = ISD::SETO; break;
2174 case FCmpInst::FCMP_UNO: FOC = FPC = ISD::SETUO; break;
2175 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
2176 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
2177 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
2178 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
2179 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
2180 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
2181 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
2182 default:
2183 assert(!"Invalid VFCmp predicate value");
2184 FOC = FPC = ISD::SETFALSE;
2185 break;
2186 }
2187 if (FiniteOnlyFPMath())
2188 Condition = FOC;
2189 else
2190 Condition = FPC;
2191
2192 MVT DestVT = TLI.getValueType(I.getType());
2193
2194 setValue(&I, DAG.getVSetCC(DestVT, Op1, Op2, Condition));
2195}
2196
2197void SelectionDAGLowering::visitSelect(User &I) {
2198 SDValue Cond = getValue(I.getOperand(0));
2199 SDValue TrueVal = getValue(I.getOperand(1));
2200 SDValue FalseVal = getValue(I.getOperand(2));
2201 setValue(&I, DAG.getNode(ISD::SELECT, TrueVal.getValueType(), Cond,
2202 TrueVal, FalseVal));
2203}
2204
2205
2206void SelectionDAGLowering::visitTrunc(User &I) {
2207 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
2208 SDValue N = getValue(I.getOperand(0));
2209 MVT DestVT = TLI.getValueType(I.getType());
2210 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
2211}
2212
2213void SelectionDAGLowering::visitZExt(User &I) {
2214 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2215 // ZExt also can't be a cast to bool for same reason. So, nothing much to do
2216 SDValue N = getValue(I.getOperand(0));
2217 MVT DestVT = TLI.getValueType(I.getType());
2218 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
2219}
2220
2221void SelectionDAGLowering::visitSExt(User &I) {
2222 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2223 // SExt also can't be a cast to bool for same reason. So, nothing much to do
2224 SDValue N = getValue(I.getOperand(0));
2225 MVT DestVT = TLI.getValueType(I.getType());
2226 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, DestVT, N));
2227}
2228
2229void SelectionDAGLowering::visitFPTrunc(User &I) {
2230 // FPTrunc is never a no-op cast, no need to check
2231 SDValue N = getValue(I.getOperand(0));
2232 MVT DestVT = TLI.getValueType(I.getType());
2233 setValue(&I, DAG.getNode(ISD::FP_ROUND, DestVT, N, DAG.getIntPtrConstant(0)));
2234}
2235
2236void SelectionDAGLowering::visitFPExt(User &I){
2237 // FPTrunc is never a no-op cast, no need to check
2238 SDValue N = getValue(I.getOperand(0));
2239 MVT DestVT = TLI.getValueType(I.getType());
2240 setValue(&I, DAG.getNode(ISD::FP_EXTEND, DestVT, N));
2241}
2242
2243void SelectionDAGLowering::visitFPToUI(User &I) {
2244 // FPToUI is never a no-op cast, no need to check
2245 SDValue N = getValue(I.getOperand(0));
2246 MVT DestVT = TLI.getValueType(I.getType());
2247 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, DestVT, N));
2248}
2249
2250void SelectionDAGLowering::visitFPToSI(User &I) {
2251 // FPToSI is never a no-op cast, no need to check
2252 SDValue N = getValue(I.getOperand(0));
2253 MVT DestVT = TLI.getValueType(I.getType());
2254 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, DestVT, N));
2255}
2256
2257void SelectionDAGLowering::visitUIToFP(User &I) {
2258 // UIToFP is never a no-op cast, no need to check
2259 SDValue N = getValue(I.getOperand(0));
2260 MVT DestVT = TLI.getValueType(I.getType());
2261 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, DestVT, N));
2262}
2263
2264void SelectionDAGLowering::visitSIToFP(User &I){
2265 // UIToFP is never a no-op cast, no need to check
2266 SDValue N = getValue(I.getOperand(0));
2267 MVT DestVT = TLI.getValueType(I.getType());
2268 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, DestVT, N));
2269}
2270
2271void SelectionDAGLowering::visitPtrToInt(User &I) {
2272 // What to do depends on the size of the integer and the size of the pointer.
2273 // We can either truncate, zero extend, or no-op, accordingly.
2274 SDValue N = getValue(I.getOperand(0));
2275 MVT SrcVT = N.getValueType();
2276 MVT DestVT = TLI.getValueType(I.getType());
2277 SDValue Result;
2278 if (DestVT.bitsLT(SrcVT))
2279 Result = DAG.getNode(ISD::TRUNCATE, DestVT, N);
2280 else
2281 // Note: ZERO_EXTEND can handle cases where the sizes are equal too
2282 Result = DAG.getNode(ISD::ZERO_EXTEND, DestVT, N);
2283 setValue(&I, Result);
2284}
2285
2286void SelectionDAGLowering::visitIntToPtr(User &I) {
2287 // What to do depends on the size of the integer and the size of the pointer.
2288 // We can either truncate, zero extend, or no-op, accordingly.
2289 SDValue N = getValue(I.getOperand(0));
2290 MVT SrcVT = N.getValueType();
2291 MVT DestVT = TLI.getValueType(I.getType());
2292 if (DestVT.bitsLT(SrcVT))
2293 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
2294 else
2295 // Note: ZERO_EXTEND can handle cases where the sizes are equal too
2296 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
2297}
2298
2299void SelectionDAGLowering::visitBitCast(User &I) {
2300 SDValue N = getValue(I.getOperand(0));
2301 MVT DestVT = TLI.getValueType(I.getType());
2302
2303 // BitCast assures us that source and destination are the same size so this
2304 // is either a BIT_CONVERT or a no-op.
2305 if (DestVT != N.getValueType())
2306 setValue(&I, DAG.getNode(ISD::BIT_CONVERT, DestVT, N)); // convert types
2307 else
2308 setValue(&I, N); // noop cast.
2309}
2310
2311void SelectionDAGLowering::visitInsertElement(User &I) {
2312 SDValue InVec = getValue(I.getOperand(0));
2313 SDValue InVal = getValue(I.getOperand(1));
2314 SDValue InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
2315 getValue(I.getOperand(2)));
2316
2317 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT,
2318 TLI.getValueType(I.getType()),
2319 InVec, InVal, InIdx));
2320}
2321
2322void SelectionDAGLowering::visitExtractElement(User &I) {
2323 SDValue InVec = getValue(I.getOperand(0));
2324 SDValue InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
2325 getValue(I.getOperand(1)));
2326 setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
2327 TLI.getValueType(I.getType()), InVec, InIdx));
2328}
2329
2330void SelectionDAGLowering::visitShuffleVector(User &I) {
2331 SDValue V1 = getValue(I.getOperand(0));
2332 SDValue V2 = getValue(I.getOperand(1));
2333 SDValue Mask = getValue(I.getOperand(2));
2334
2335 setValue(&I, DAG.getNode(ISD::VECTOR_SHUFFLE,
2336 TLI.getValueType(I.getType()),
2337 V1, V2, Mask));
2338}
2339
2340void SelectionDAGLowering::visitInsertValue(InsertValueInst &I) {
2341 const Value *Op0 = I.getOperand(0);
2342 const Value *Op1 = I.getOperand(1);
2343 const Type *AggTy = I.getType();
2344 const Type *ValTy = Op1->getType();
2345 bool IntoUndef = isa<UndefValue>(Op0);
2346 bool FromUndef = isa<UndefValue>(Op1);
2347
2348 unsigned LinearIndex = ComputeLinearIndex(TLI, AggTy,
2349 I.idx_begin(), I.idx_end());
2350
2351 SmallVector<MVT, 4> AggValueVTs;
2352 ComputeValueVTs(TLI, AggTy, AggValueVTs);
2353 SmallVector<MVT, 4> ValValueVTs;
2354 ComputeValueVTs(TLI, ValTy, ValValueVTs);
2355
2356 unsigned NumAggValues = AggValueVTs.size();
2357 unsigned NumValValues = ValValueVTs.size();
2358 SmallVector<SDValue, 4> Values(NumAggValues);
2359
2360 SDValue Agg = getValue(Op0);
2361 SDValue Val = getValue(Op1);
2362 unsigned i = 0;
2363 // Copy the beginning value(s) from the original aggregate.
2364 for (; i != LinearIndex; ++i)
2365 Values[i] = IntoUndef ? DAG.getNode(ISD::UNDEF, AggValueVTs[i]) :
2366 SDValue(Agg.getNode(), Agg.getResNo() + i);
2367 // Copy values from the inserted value(s).
2368 for (; i != LinearIndex + NumValValues; ++i)
2369 Values[i] = FromUndef ? DAG.getNode(ISD::UNDEF, AggValueVTs[i]) :
2370 SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
2371 // Copy remaining value(s) from the original aggregate.
2372 for (; i != NumAggValues; ++i)
2373 Values[i] = IntoUndef ? DAG.getNode(ISD::UNDEF, AggValueVTs[i]) :
2374 SDValue(Agg.getNode(), Agg.getResNo() + i);
2375
2376 setValue(&I, DAG.getMergeValues(DAG.getVTList(&AggValueVTs[0], NumAggValues),
2377 &Values[0], NumAggValues));
2378}
2379
2380void SelectionDAGLowering::visitExtractValue(ExtractValueInst &I) {
2381 const Value *Op0 = I.getOperand(0);
2382 const Type *AggTy = Op0->getType();
2383 const Type *ValTy = I.getType();
2384 bool OutOfUndef = isa<UndefValue>(Op0);
2385
2386 unsigned LinearIndex = ComputeLinearIndex(TLI, AggTy,
2387 I.idx_begin(), I.idx_end());
2388
2389 SmallVector<MVT, 4> ValValueVTs;
2390 ComputeValueVTs(TLI, ValTy, ValValueVTs);
2391
2392 unsigned NumValValues = ValValueVTs.size();
2393 SmallVector<SDValue, 4> Values(NumValValues);
2394
2395 SDValue Agg = getValue(Op0);
2396 // Copy out the selected value(s).
2397 for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
2398 Values[i - LinearIndex] =
2399 OutOfUndef ? DAG.getNode(ISD::UNDEF, Agg.getNode()->getValueType(Agg.getResNo() + i)) :
2400 SDValue(Agg.getNode(), Agg.getResNo() + i);
2401
2402 setValue(&I, DAG.getMergeValues(DAG.getVTList(&ValValueVTs[0], NumValValues),
2403 &Values[0], NumValValues));
2404}
2405
2406
2407void SelectionDAGLowering::visitGetElementPtr(User &I) {
2408 SDValue N = getValue(I.getOperand(0));
2409 const Type *Ty = I.getOperand(0)->getType();
2410
2411 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
2412 OI != E; ++OI) {
2413 Value *Idx = *OI;
2414 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
2415 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
2416 if (Field) {
2417 // N = N + Offset
2418 uint64_t Offset = TD->getStructLayout(StTy)->getElementOffset(Field);
2419 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
2420 DAG.getIntPtrConstant(Offset));
2421 }
2422 Ty = StTy->getElementType(Field);
2423 } else {
2424 Ty = cast<SequentialType>(Ty)->getElementType();
2425
2426 // If this is a constant subscript, handle it quickly.
2427 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
2428 if (CI->getZExtValue() == 0) continue;
2429 uint64_t Offs =
2430 TD->getABITypeSize(Ty)*cast<ConstantInt>(CI)->getSExtValue();
2431 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
2432 DAG.getIntPtrConstant(Offs));
2433 continue;
2434 }
2435
2436 // N = N + Idx * ElementSize;
2437 uint64_t ElementSize = TD->getABITypeSize(Ty);
2438 SDValue IdxN = getValue(Idx);
2439
2440 // If the index is smaller or larger than intptr_t, truncate or extend
2441 // it.
2442 if (IdxN.getValueType().bitsLT(N.getValueType()))
2443 IdxN = DAG.getNode(ISD::SIGN_EXTEND, N.getValueType(), IdxN);
2444 else if (IdxN.getValueType().bitsGT(N.getValueType()))
2445 IdxN = DAG.getNode(ISD::TRUNCATE, N.getValueType(), IdxN);
2446
2447 // If this is a multiply by a power of two, turn it into a shl
2448 // immediately. This is a very common case.
2449 if (ElementSize != 1) {
2450 if (isPowerOf2_64(ElementSize)) {
2451 unsigned Amt = Log2_64(ElementSize);
2452 IdxN = DAG.getNode(ISD::SHL, N.getValueType(), IdxN,
2453 DAG.getConstant(Amt, TLI.getShiftAmountTy()));
2454 } else {
2455 SDValue Scale = DAG.getIntPtrConstant(ElementSize);
2456 IdxN = DAG.getNode(ISD::MUL, N.getValueType(), IdxN, Scale);
2457 }
2458 }
2459
2460 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
2461 }
2462 }
2463 setValue(&I, N);
2464}
2465
2466void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
2467 // If this is a fixed sized alloca in the entry block of the function,
2468 // allocate it statically on the stack.
2469 if (FuncInfo.StaticAllocaMap.count(&I))
2470 return; // getValue will auto-populate this.
2471
2472 const Type *Ty = I.getAllocatedType();
2473 uint64_t TySize = TLI.getTargetData()->getABITypeSize(Ty);
2474 unsigned Align =
2475 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
2476 I.getAlignment());
2477
2478 SDValue AllocSize = getValue(I.getArraySize());
2479 MVT IntPtr = TLI.getPointerTy();
2480 if (IntPtr.bitsLT(AllocSize.getValueType()))
2481 AllocSize = DAG.getNode(ISD::TRUNCATE, IntPtr, AllocSize);
2482 else if (IntPtr.bitsGT(AllocSize.getValueType()))
2483 AllocSize = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, AllocSize);
2484
2485 AllocSize = DAG.getNode(ISD::MUL, IntPtr, AllocSize,
2486 DAG.getIntPtrConstant(TySize));
2487
2488 // Handle alignment. If the requested alignment is less than or equal to
2489 // the stack alignment, ignore it. If the size is greater than or equal to
2490 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
2491 unsigned StackAlign =
2492 TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
2493 if (Align <= StackAlign)
2494 Align = 0;
2495
2496 // Round the size of the allocation up to the stack alignment size
2497 // by add SA-1 to the size.
2498 AllocSize = DAG.getNode(ISD::ADD, AllocSize.getValueType(), AllocSize,
2499 DAG.getIntPtrConstant(StackAlign-1));
2500 // Mask out the low bits for alignment purposes.
2501 AllocSize = DAG.getNode(ISD::AND, AllocSize.getValueType(), AllocSize,
2502 DAG.getIntPtrConstant(~(uint64_t)(StackAlign-1)));
2503
2504 SDValue Ops[] = { getRoot(), AllocSize, DAG.getIntPtrConstant(Align) };
2505 const MVT *VTs = DAG.getNodeValueTypes(AllocSize.getValueType(),
2506 MVT::Other);
2507 SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, VTs, 2, Ops, 3);
2508 setValue(&I, DSA);
2509 DAG.setRoot(DSA.getValue(1));
2510
2511 // Inform the Frame Information that we have just allocated a variable-sized
2512 // object.
2513 CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
2514}
2515
2516void SelectionDAGLowering::visitLoad(LoadInst &I) {
2517 const Value *SV = I.getOperand(0);
2518 SDValue Ptr = getValue(SV);
2519
2520 const Type *Ty = I.getType();
2521 bool isVolatile = I.isVolatile();
2522 unsigned Alignment = I.getAlignment();
2523
2524 SmallVector<MVT, 4> ValueVTs;
2525 SmallVector<uint64_t, 4> Offsets;
2526 ComputeValueVTs(TLI, Ty, ValueVTs, &Offsets);
2527 unsigned NumValues = ValueVTs.size();
2528 if (NumValues == 0)
2529 return;
2530
2531 SDValue Root;
2532 bool ConstantMemory = false;
2533 if (I.isVolatile())
2534 // Serialize volatile loads with other side effects.
2535 Root = getRoot();
2536 else if (AA->pointsToConstantMemory(SV)) {
2537 // Do not serialize (non-volatile) loads of constant memory with anything.
2538 Root = DAG.getEntryNode();
2539 ConstantMemory = true;
2540 } else {
2541 // Do not serialize non-volatile loads against each other.
2542 Root = DAG.getRoot();
2543 }
2544
2545 SmallVector<SDValue, 4> Values(NumValues);
2546 SmallVector<SDValue, 4> Chains(NumValues);
2547 MVT PtrVT = Ptr.getValueType();
2548 for (unsigned i = 0; i != NumValues; ++i) {
2549 SDValue L = DAG.getLoad(ValueVTs[i], Root,
2550 DAG.getNode(ISD::ADD, PtrVT, Ptr,
2551 DAG.getConstant(Offsets[i], PtrVT)),
2552 SV, Offsets[i],
2553 isVolatile, Alignment);
2554 Values[i] = L;
2555 Chains[i] = L.getValue(1);
2556 }
2557
2558 if (!ConstantMemory) {
2559 SDValue Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
2560 &Chains[0], NumValues);
2561 if (isVolatile)
2562 DAG.setRoot(Chain);
2563 else
2564 PendingLoads.push_back(Chain);
2565 }
2566
2567 setValue(&I, DAG.getMergeValues(DAG.getVTList(&ValueVTs[0], NumValues),
2568 &Values[0], NumValues));
2569}
2570
2571
2572void SelectionDAGLowering::visitStore(StoreInst &I) {
2573 Value *SrcV = I.getOperand(0);
2574 Value *PtrV = I.getOperand(1);
2575
2576 SmallVector<MVT, 4> ValueVTs;
2577 SmallVector<uint64_t, 4> Offsets;
2578 ComputeValueVTs(TLI, SrcV->getType(), ValueVTs, &Offsets);
2579 unsigned NumValues = ValueVTs.size();
2580 if (NumValues == 0)
2581 return;
2582
2583 // Get the lowered operands. Note that we do this after
2584 // checking if NumResults is zero, because with zero results
2585 // the operands won't have values in the map.
2586 SDValue Src = getValue(SrcV);
2587 SDValue Ptr = getValue(PtrV);
2588
2589 SDValue Root = getRoot();
2590 SmallVector<SDValue, 4> Chains(NumValues);
2591 MVT PtrVT = Ptr.getValueType();
2592 bool isVolatile = I.isVolatile();
2593 unsigned Alignment = I.getAlignment();
2594 for (unsigned i = 0; i != NumValues; ++i)
2595 Chains[i] = DAG.getStore(Root, SDValue(Src.getNode(), Src.getResNo() + i),
2596 DAG.getNode(ISD::ADD, PtrVT, Ptr,
2597 DAG.getConstant(Offsets[i], PtrVT)),
2598 PtrV, Offsets[i],
2599 isVolatile, Alignment);
2600
2601 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other, &Chains[0], NumValues));
2602}
2603
2604/// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
2605/// node.
2606void SelectionDAGLowering::visitTargetIntrinsic(CallInst &I,
2607 unsigned Intrinsic) {
2608 bool HasChain = !I.doesNotAccessMemory();
2609 bool OnlyLoad = HasChain && I.onlyReadsMemory();
2610
2611 // Build the operand list.
2612 SmallVector<SDValue, 8> Ops;
2613 if (HasChain) { // If this intrinsic has side-effects, chainify it.
2614 if (OnlyLoad) {
2615 // We don't need to serialize loads against other loads.
2616 Ops.push_back(DAG.getRoot());
2617 } else {
2618 Ops.push_back(getRoot());
2619 }
2620 }
2621
2622 // Add the intrinsic ID as an integer operand.
2623 Ops.push_back(DAG.getConstant(Intrinsic, TLI.getPointerTy()));
2624
2625 // Add all operands of the call to the operand list.
2626 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
2627 SDValue Op = getValue(I.getOperand(i));
2628 assert(TLI.isTypeLegal(Op.getValueType()) &&
2629 "Intrinsic uses a non-legal type?");
2630 Ops.push_back(Op);
2631 }
2632
2633 std::vector<MVT> VTs;
2634 if (I.getType() != Type::VoidTy) {
2635 MVT VT = TLI.getValueType(I.getType());
2636 if (VT.isVector()) {
2637 const VectorType *DestTy = cast<VectorType>(I.getType());
2638 MVT EltVT = TLI.getValueType(DestTy->getElementType());
2639
2640 VT = MVT::getVectorVT(EltVT, DestTy->getNumElements());
2641 assert(VT != MVT::Other && "Intrinsic uses a non-legal type?");
2642 }
2643
2644 assert(TLI.isTypeLegal(VT) && "Intrinsic uses a non-legal type?");
2645 VTs.push_back(VT);
2646 }
2647 if (HasChain)
2648 VTs.push_back(MVT::Other);
2649
2650 const MVT *VTList = DAG.getNodeValueTypes(VTs);
2651
2652 // Create the node.
2653 SDValue Result;
2654 if (!HasChain)
2655 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VTList, VTs.size(),
2656 &Ops[0], Ops.size());
2657 else if (I.getType() != Type::VoidTy)
2658 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, VTList, VTs.size(),
2659 &Ops[0], Ops.size());
2660 else
2661 Result = DAG.getNode(ISD::INTRINSIC_VOID, VTList, VTs.size(),
2662 &Ops[0], Ops.size());
2663
2664 if (HasChain) {
2665 SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
2666 if (OnlyLoad)
2667 PendingLoads.push_back(Chain);
2668 else
2669 DAG.setRoot(Chain);
2670 }
2671 if (I.getType() != Type::VoidTy) {
2672 if (const VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
2673 MVT VT = TLI.getValueType(PTy);
2674 Result = DAG.getNode(ISD::BIT_CONVERT, VT, Result);
2675 }
2676 setValue(&I, Result);
2677 }
2678}
2679
2680/// ExtractTypeInfo - Returns the type info, possibly bitcast, encoded in V.
2681static GlobalVariable *ExtractTypeInfo(Value *V) {
2682 V = V->stripPointerCasts();
2683 GlobalVariable *GV = dyn_cast<GlobalVariable>(V);
2684 assert ((GV || isa<ConstantPointerNull>(V)) &&
2685 "TypeInfo must be a global variable or NULL");
2686 return GV;
2687}
2688
2689namespace llvm {
2690
2691/// AddCatchInfo - Extract the personality and type infos from an eh.selector
2692/// call, and add them to the specified machine basic block.
2693void AddCatchInfo(CallInst &I, MachineModuleInfo *MMI,
2694 MachineBasicBlock *MBB) {
2695 // Inform the MachineModuleInfo of the personality for this landing pad.
2696 ConstantExpr *CE = cast<ConstantExpr>(I.getOperand(2));
2697 assert(CE->getOpcode() == Instruction::BitCast &&
2698 isa<Function>(CE->getOperand(0)) &&
2699 "Personality should be a function");
2700 MMI->addPersonality(MBB, cast<Function>(CE->getOperand(0)));
2701
2702 // Gather all the type infos for this landing pad and pass them along to
2703 // MachineModuleInfo.
2704 std::vector<GlobalVariable *> TyInfo;
2705 unsigned N = I.getNumOperands();
2706
2707 for (unsigned i = N - 1; i > 2; --i) {
2708 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(i))) {
2709 unsigned FilterLength = CI->getZExtValue();
2710 unsigned FirstCatch = i + FilterLength + !FilterLength;
2711 assert (FirstCatch <= N && "Invalid filter length");
2712
2713 if (FirstCatch < N) {
2714 TyInfo.reserve(N - FirstCatch);
2715 for (unsigned j = FirstCatch; j < N; ++j)
2716 TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
2717 MMI->addCatchTypeInfo(MBB, TyInfo);
2718 TyInfo.clear();
2719 }
2720
2721 if (!FilterLength) {
2722 // Cleanup.
2723 MMI->addCleanup(MBB);
2724 } else {
2725 // Filter.
2726 TyInfo.reserve(FilterLength - 1);
2727 for (unsigned j = i + 1; j < FirstCatch; ++j)
2728 TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
2729 MMI->addFilterTypeInfo(MBB, TyInfo);
2730 TyInfo.clear();
2731 }
2732
2733 N = i;
2734 }
2735 }
2736
2737 if (N > 3) {
2738 TyInfo.reserve(N - 3);
2739 for (unsigned j = 3; j < N; ++j)
2740 TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
2741 MMI->addCatchTypeInfo(MBB, TyInfo);
2742 }
2743}
2744
2745}
2746
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00002747/// GetSignificand - Get the significand and build it into a floating-point
2748/// number with exponent of 1:
2749///
2750/// Op = (Op & 0x007fffff) | 0x3f800000;
2751///
2752/// where Op is the hexidecimal representation of floating point value.
Bill Wendling39150252008-09-09 20:39:27 +00002753static SDValue
2754GetSignificand(SelectionDAG &DAG, SDValue Op) {
2755 SDValue t1 = DAG.getNode(ISD::AND, MVT::i32, Op,
2756 DAG.getConstant(0x007fffff, MVT::i32));
2757 SDValue t2 = DAG.getNode(ISD::OR, MVT::i32, t1,
2758 DAG.getConstant(0x3f800000, MVT::i32));
2759 return DAG.getNode(ISD::BIT_CONVERT, MVT::f32, t2);
2760}
2761
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00002762/// GetExponent - Get the exponent:
2763///
2764/// (float)((Op1 >> 23) - 127);
2765///
2766/// where Op is the hexidecimal representation of floating point value.
Bill Wendling39150252008-09-09 20:39:27 +00002767static SDValue
2768GetExponent(SelectionDAG &DAG, SDValue Op) {
Bill Wendlingfc2508e2008-09-10 06:26:10 +00002769 SDValue t1 = DAG.getNode(ISD::SRL, MVT::i32, Op,
Bill Wendling39150252008-09-09 20:39:27 +00002770 DAG.getConstant(23, MVT::i32));
Bill Wendlingfc2508e2008-09-10 06:26:10 +00002771 SDValue t2 = DAG.getNode(ISD::SUB, MVT::i32, t1,
Bill Wendling39150252008-09-09 20:39:27 +00002772 DAG.getConstant(127, MVT::i32));
Bill Wendlingfc2508e2008-09-10 06:26:10 +00002773 return DAG.getNode(ISD::UINT_TO_FP, MVT::f32, t2);
Bill Wendling39150252008-09-09 20:39:27 +00002774}
2775
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00002776/// getF32Constant - Get 32-bit floating point constant.
2777static SDValue
2778getF32Constant(SelectionDAG &DAG, unsigned Flt) {
2779 return DAG.getConstantFP(APFloat(APInt(32, Flt)), MVT::f32);
2780}
2781
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002782/// Inlined utility function to implement binary input atomic intrinsics for
2783/// visitIntrinsicCall: I is a call instruction
2784/// Op is the associated NodeType for I
2785const char *
2786SelectionDAGLowering::implVisitBinaryAtomic(CallInst& I, ISD::NodeType Op) {
2787 SDValue Root = getRoot();
2788 SDValue L = DAG.getAtomic(Op, Root,
2789 getValue(I.getOperand(1)),
2790 getValue(I.getOperand(2)),
2791 I.getOperand(1));
2792 setValue(&I, L);
2793 DAG.setRoot(L.getValue(1));
2794 return 0;
2795}
2796
Bill Wendlingb4ec2832008-09-09 22:13:54 +00002797/// visitExp - Lower an exp intrinsic. Handles the special sequences for
2798/// limited-precision mode.
Dale Johannesen59e577f2008-09-05 18:38:42 +00002799void
2800SelectionDAGLowering::visitExp(CallInst &I) {
2801 SDValue result;
Bill Wendlingb4ec2832008-09-09 22:13:54 +00002802
2803 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
2804 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
2805 SDValue Op = getValue(I.getOperand(1));
2806
2807 // Put the exponent in the right bit position for later addition to the
2808 // final result:
2809 //
2810 // #define LOG2OFe 1.4426950f
2811 // IntegerPartOfX = ((int32_t)(X * LOG2OFe));
2812 SDValue t0 = DAG.getNode(ISD::FMUL, MVT::f32, Op,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00002813 getF32Constant(DAG, 0x3fb8aa3b));
Bill Wendlingb4ec2832008-09-09 22:13:54 +00002814 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, MVT::i32, t0);
2815
2816 // FractionalPartOfX = (X * LOG2OFe) - (float)IntegerPartOfX;
2817 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, MVT::f32, IntegerPartOfX);
2818 SDValue X = DAG.getNode(ISD::FSUB, MVT::f32, t0, t1);
2819
2820 // IntegerPartOfX <<= 23;
2821 IntegerPartOfX = DAG.getNode(ISD::SHL, MVT::i32, IntegerPartOfX,
2822 DAG.getConstant(23, MVT::i32));
2823
2824 if (LimitFloatPrecision <= 6) {
2825 // For floating-point precision of 6:
2826 //
2827 // TwoToFractionalPartOfX =
2828 // 0.997535578f +
2829 // (0.735607626f + 0.252464424f * x) * x;
2830 //
2831 // error 0.0144103317, which is 6 bits
2832 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00002833 getF32Constant(DAG, 0x3e814304));
Bill Wendlingb4ec2832008-09-09 22:13:54 +00002834 SDValue t3 = DAG.getNode(ISD::FADD, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00002835 getF32Constant(DAG, 0x3f3c50c8));
Bill Wendlingb4ec2832008-09-09 22:13:54 +00002836 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
2837 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00002838 getF32Constant(DAG, 0x3f7f5e7e));
Bill Wendlingb4ec2832008-09-09 22:13:54 +00002839 SDValue TwoToFracPartOfX = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, t5);
2840
2841 // Add the exponent into the result in integer domain.
2842 SDValue t6 = DAG.getNode(ISD::ADD, MVT::i32,
2843 TwoToFracPartOfX, IntegerPartOfX);
2844
2845 result = DAG.getNode(ISD::BIT_CONVERT, MVT::f32, t6);
2846 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
2847 // For floating-point precision of 12:
2848 //
2849 // TwoToFractionalPartOfX =
2850 // 0.999892986f +
2851 // (0.696457318f +
2852 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
2853 //
2854 // 0.000107046256 error, which is 13 to 14 bits
2855 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00002856 getF32Constant(DAG, 0x3da235e3));
Bill Wendlingb4ec2832008-09-09 22:13:54 +00002857 SDValue t3 = DAG.getNode(ISD::FADD, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00002858 getF32Constant(DAG, 0x3e65b8f3));
Bill Wendlingb4ec2832008-09-09 22:13:54 +00002859 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
2860 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00002861 getF32Constant(DAG, 0x3f324b07));
Bill Wendlingb4ec2832008-09-09 22:13:54 +00002862 SDValue t6 = DAG.getNode(ISD::FMUL, MVT::f32, t5, X);
2863 SDValue t7 = DAG.getNode(ISD::FADD, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00002864 getF32Constant(DAG, 0x3f7ff8fd));
Bill Wendlingb4ec2832008-09-09 22:13:54 +00002865 SDValue TwoToFracPartOfX = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, t7);
2866
2867 // Add the exponent into the result in integer domain.
2868 SDValue t8 = DAG.getNode(ISD::ADD, MVT::i32,
2869 TwoToFracPartOfX, IntegerPartOfX);
2870
2871 result = DAG.getNode(ISD::BIT_CONVERT, MVT::f32, t8);
2872 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
2873 // For floating-point precision of 18:
2874 //
2875 // TwoToFractionalPartOfX =
2876 // 0.999999982f +
2877 // (0.693148872f +
2878 // (0.240227044f +
2879 // (0.554906021e-1f +
2880 // (0.961591928e-2f +
2881 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
2882 //
2883 // error 2.47208000*10^(-7), which is better than 18 bits
2884 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00002885 getF32Constant(DAG, 0x3924b03e));
Bill Wendlingb4ec2832008-09-09 22:13:54 +00002886 SDValue t3 = DAG.getNode(ISD::FADD, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00002887 getF32Constant(DAG, 0x3ab24b87));
Bill Wendlingb4ec2832008-09-09 22:13:54 +00002888 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
2889 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00002890 getF32Constant(DAG, 0x3c1d8c17));
Bill Wendlingb4ec2832008-09-09 22:13:54 +00002891 SDValue t6 = DAG.getNode(ISD::FMUL, MVT::f32, t5, X);
2892 SDValue t7 = DAG.getNode(ISD::FADD, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00002893 getF32Constant(DAG, 0x3d634a1d));
Bill Wendlingb4ec2832008-09-09 22:13:54 +00002894 SDValue t8 = DAG.getNode(ISD::FMUL, MVT::f32, t7, X);
2895 SDValue t9 = DAG.getNode(ISD::FADD, MVT::f32, t8,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00002896 getF32Constant(DAG, 0x3e75fe14));
Bill Wendlingb4ec2832008-09-09 22:13:54 +00002897 SDValue t10 = DAG.getNode(ISD::FMUL, MVT::f32, t9, X);
2898 SDValue t11 = DAG.getNode(ISD::FADD, MVT::f32, t10,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00002899 getF32Constant(DAG, 0x3f317234));
Bill Wendlingb4ec2832008-09-09 22:13:54 +00002900 SDValue t12 = DAG.getNode(ISD::FMUL, MVT::f32, t11, X);
2901 SDValue t13 = DAG.getNode(ISD::FADD, MVT::f32, t12,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00002902 getF32Constant(DAG, 0x3f800000));
Bill Wendlingb4ec2832008-09-09 22:13:54 +00002903 SDValue TwoToFracPartOfX = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, t13);
2904
2905 // Add the exponent into the result in integer domain.
2906 SDValue t14 = DAG.getNode(ISD::ADD, MVT::i32,
2907 TwoToFracPartOfX, IntegerPartOfX);
2908
2909 result = DAG.getNode(ISD::BIT_CONVERT, MVT::f32, t14);
2910 }
2911 } else {
2912 // No special expansion.
2913 result = DAG.getNode(ISD::FEXP,
2914 getValue(I.getOperand(1)).getValueType(),
2915 getValue(I.getOperand(1)));
2916 }
2917
Dale Johannesen59e577f2008-09-05 18:38:42 +00002918 setValue(&I, result);
2919}
2920
Bill Wendling39150252008-09-09 20:39:27 +00002921/// visitLog - Lower a log intrinsic. Handles the special sequences for
2922/// limited-precision mode.
Dale Johannesen59e577f2008-09-05 18:38:42 +00002923void
2924SelectionDAGLowering::visitLog(CallInst &I) {
2925 SDValue result;
Bill Wendling39150252008-09-09 20:39:27 +00002926
2927 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
2928 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
2929 SDValue Op = getValue(I.getOperand(1));
2930 SDValue Op1 = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, Op);
2931
2932 // Scale the exponent by log(2) [0.69314718f].
2933 SDValue Exp = GetExponent(DAG, Op1);
2934 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, MVT::f32, Exp,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00002935 getF32Constant(DAG, 0x3f317218));
Bill Wendling39150252008-09-09 20:39:27 +00002936
2937 // Get the significand and build it into a floating-point number with
2938 // exponent of 1.
2939 SDValue X = GetSignificand(DAG, Op1);
2940
2941 if (LimitFloatPrecision <= 6) {
2942 // For floating-point precision of 6:
2943 //
2944 // LogofMantissa =
2945 // -1.1609546f +
2946 // (1.4034025f - 0.23903021f * x) * x;
2947 //
2948 // error 0.0034276066, which is better than 8 bits
2949 SDValue t0 = DAG.getNode(ISD::FMUL, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00002950 getF32Constant(DAG, 0xbe74c456));
Bill Wendling39150252008-09-09 20:39:27 +00002951 SDValue t1 = DAG.getNode(ISD::FADD, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00002952 getF32Constant(DAG, 0x3fb3a2b1));
Bill Wendling39150252008-09-09 20:39:27 +00002953 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, t1, X);
2954 SDValue LogOfMantissa = DAG.getNode(ISD::FSUB, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00002955 getF32Constant(DAG, 0x3f949a29));
Bill Wendling39150252008-09-09 20:39:27 +00002956
2957 result = DAG.getNode(ISD::FADD, MVT::f32, LogOfExponent, LogOfMantissa);
2958 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
2959 // For floating-point precision of 12:
2960 //
2961 // LogOfMantissa =
2962 // -1.7417939f +
2963 // (2.8212026f +
2964 // (-1.4699568f +
2965 // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
2966 //
2967 // error 0.000061011436, which is 14 bits
2968 SDValue t0 = DAG.getNode(ISD::FMUL, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00002969 getF32Constant(DAG, 0xbd67b6d6));
Bill Wendling39150252008-09-09 20:39:27 +00002970 SDValue t1 = DAG.getNode(ISD::FADD, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00002971 getF32Constant(DAG, 0x3ee4f4b8));
Bill Wendling39150252008-09-09 20:39:27 +00002972 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, t1, X);
2973 SDValue t3 = DAG.getNode(ISD::FSUB, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00002974 getF32Constant(DAG, 0x3fbc278b));
Bill Wendling39150252008-09-09 20:39:27 +00002975 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
2976 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00002977 getF32Constant(DAG, 0x40348e95));
Bill Wendling39150252008-09-09 20:39:27 +00002978 SDValue t6 = DAG.getNode(ISD::FMUL, MVT::f32, t5, X);
2979 SDValue LogOfMantissa = DAG.getNode(ISD::FSUB, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00002980 getF32Constant(DAG, 0x3fdef31a));
Bill Wendling39150252008-09-09 20:39:27 +00002981
2982 result = DAG.getNode(ISD::FADD, MVT::f32, LogOfExponent, LogOfMantissa);
2983 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
2984 // For floating-point precision of 18:
2985 //
2986 // LogOfMantissa =
2987 // -2.1072184f +
2988 // (4.2372794f +
2989 // (-3.7029485f +
2990 // (2.2781945f +
2991 // (-0.87823314f +
2992 // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
2993 //
2994 // error 0.0000023660568, which is better than 18 bits
2995 SDValue t0 = DAG.getNode(ISD::FMUL, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00002996 getF32Constant(DAG, 0xbc91e5ac));
Bill Wendling39150252008-09-09 20:39:27 +00002997 SDValue t1 = DAG.getNode(ISD::FADD, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00002998 getF32Constant(DAG, 0x3e4350aa));
Bill Wendling39150252008-09-09 20:39:27 +00002999 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, t1, X);
3000 SDValue t3 = DAG.getNode(ISD::FSUB, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003001 getF32Constant(DAG, 0x3f60d3e3));
Bill Wendling39150252008-09-09 20:39:27 +00003002 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3003 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003004 getF32Constant(DAG, 0x4011cdf0));
Bill Wendling39150252008-09-09 20:39:27 +00003005 SDValue t6 = DAG.getNode(ISD::FMUL, MVT::f32, t5, X);
3006 SDValue t7 = DAG.getNode(ISD::FSUB, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003007 getF32Constant(DAG, 0x406cfd1c));
Bill Wendling39150252008-09-09 20:39:27 +00003008 SDValue t8 = DAG.getNode(ISD::FMUL, MVT::f32, t7, X);
3009 SDValue t9 = DAG.getNode(ISD::FADD, MVT::f32, t8,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003010 getF32Constant(DAG, 0x408797cb));
Bill Wendling39150252008-09-09 20:39:27 +00003011 SDValue t10 = DAG.getNode(ISD::FMUL, MVT::f32, t9, X);
3012 SDValue LogOfMantissa = DAG.getNode(ISD::FSUB, MVT::f32, t10,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003013 getF32Constant(DAG, 0x4006dcab));
Bill Wendling39150252008-09-09 20:39:27 +00003014
3015 result = DAG.getNode(ISD::FADD, MVT::f32, LogOfExponent, LogOfMantissa);
3016 }
3017 } else {
3018 // No special expansion.
3019 result = DAG.getNode(ISD::FLOG,
3020 getValue(I.getOperand(1)).getValueType(),
3021 getValue(I.getOperand(1)));
3022 }
3023
Dale Johannesen59e577f2008-09-05 18:38:42 +00003024 setValue(&I, result);
3025}
3026
Bill Wendling3eb59402008-09-09 00:28:24 +00003027/// visitLog2 - Lower a log2 intrinsic. Handles the special sequences for
3028/// limited-precision mode.
Dale Johannesen59e577f2008-09-05 18:38:42 +00003029void
3030SelectionDAGLowering::visitLog2(CallInst &I) {
3031 SDValue result;
Bill Wendling3eb59402008-09-09 00:28:24 +00003032
Dale Johannesen853244f2008-09-05 23:49:37 +00003033 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
Bill Wendling3eb59402008-09-09 00:28:24 +00003034 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3035 SDValue Op = getValue(I.getOperand(1));
3036 SDValue Op1 = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, Op);
3037
Bill Wendling39150252008-09-09 20:39:27 +00003038 // Get the exponent.
3039 SDValue LogOfExponent = GetExponent(DAG, Op1);
Bill Wendling3eb59402008-09-09 00:28:24 +00003040
3041 // Get the significand and build it into a floating-point number with
Bill Wendling39150252008-09-09 20:39:27 +00003042 // exponent of 1.
3043 SDValue X = GetSignificand(DAG, Op1);
Bill Wendling3eb59402008-09-09 00:28:24 +00003044
3045 // Different possible minimax approximations of significand in
3046 // floating-point for various degrees of accuracy over [1,2].
3047 if (LimitFloatPrecision <= 6) {
3048 // For floating-point precision of 6:
3049 //
3050 // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
3051 //
3052 // error 0.0049451742, which is more than 7 bits
Bill Wendling39150252008-09-09 20:39:27 +00003053 SDValue t0 = DAG.getNode(ISD::FMUL, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003054 getF32Constant(DAG, 0xbeb08fe0));
Bill Wendling39150252008-09-09 20:39:27 +00003055 SDValue t1 = DAG.getNode(ISD::FADD, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003056 getF32Constant(DAG, 0x40019463));
Bill Wendling39150252008-09-09 20:39:27 +00003057 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, t1, X);
3058 SDValue Log2ofMantissa = DAG.getNode(ISD::FSUB, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003059 getF32Constant(DAG, 0x3fd6633d));
Bill Wendling3eb59402008-09-09 00:28:24 +00003060
3061 result = DAG.getNode(ISD::FADD, MVT::f32, LogOfExponent, Log2ofMantissa);
3062 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3063 // For floating-point precision of 12:
3064 //
3065 // Log2ofMantissa =
3066 // -2.51285454f +
3067 // (4.07009056f +
3068 // (-2.12067489f +
3069 // (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
3070 //
3071 // error 0.0000876136000, which is better than 13 bits
Bill Wendling39150252008-09-09 20:39:27 +00003072 SDValue t0 = DAG.getNode(ISD::FMUL, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003073 getF32Constant(DAG, 0xbda7262e));
Bill Wendling39150252008-09-09 20:39:27 +00003074 SDValue t1 = DAG.getNode(ISD::FADD, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003075 getF32Constant(DAG, 0x3f25280b));
Bill Wendling39150252008-09-09 20:39:27 +00003076 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, t1, X);
3077 SDValue t3 = DAG.getNode(ISD::FSUB, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003078 getF32Constant(DAG, 0x4007b923));
Bill Wendling39150252008-09-09 20:39:27 +00003079 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3080 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003081 getF32Constant(DAG, 0x40823e2f));
Bill Wendling39150252008-09-09 20:39:27 +00003082 SDValue t6 = DAG.getNode(ISD::FMUL, MVT::f32, t5, X);
3083 SDValue Log2ofMantissa = DAG.getNode(ISD::FSUB, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003084 getF32Constant(DAG, 0x4020d29c));
Bill Wendling3eb59402008-09-09 00:28:24 +00003085
3086 result = DAG.getNode(ISD::FADD, MVT::f32, LogOfExponent, Log2ofMantissa);
3087 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3088 // For floating-point precision of 18:
3089 //
3090 // Log2ofMantissa =
3091 // -3.0400495f +
3092 // (6.1129976f +
3093 // (-5.3420409f +
3094 // (3.2865683f +
3095 // (-1.2669343f +
3096 // (0.27515199f -
3097 // 0.25691327e-1f * x) * x) * x) * x) * x) * x;
3098 //
3099 // error 0.0000018516, which is better than 18 bits
Bill Wendling39150252008-09-09 20:39:27 +00003100 SDValue t0 = DAG.getNode(ISD::FMUL, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003101 getF32Constant(DAG, 0xbcd2769e));
Bill Wendling39150252008-09-09 20:39:27 +00003102 SDValue t1 = DAG.getNode(ISD::FADD, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003103 getF32Constant(DAG, 0x3e8ce0b9));
Bill Wendling39150252008-09-09 20:39:27 +00003104 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, t1, X);
3105 SDValue t3 = DAG.getNode(ISD::FSUB, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003106 getF32Constant(DAG, 0x3fa22ae7));
Bill Wendling39150252008-09-09 20:39:27 +00003107 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3108 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003109 getF32Constant(DAG, 0x40525723));
Bill Wendling39150252008-09-09 20:39:27 +00003110 SDValue t6 = DAG.getNode(ISD::FMUL, MVT::f32, t5, X);
3111 SDValue t7 = DAG.getNode(ISD::FSUB, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003112 getF32Constant(DAG, 0x40aaf200));
Bill Wendling39150252008-09-09 20:39:27 +00003113 SDValue t8 = DAG.getNode(ISD::FMUL, MVT::f32, t7, X);
3114 SDValue t9 = DAG.getNode(ISD::FADD, MVT::f32, t8,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003115 getF32Constant(DAG, 0x40c39dad));
Bill Wendling3eb59402008-09-09 00:28:24 +00003116 SDValue t10 = DAG.getNode(ISD::FMUL, MVT::f32, t9, X);
Bill Wendling39150252008-09-09 20:39:27 +00003117 SDValue Log2ofMantissa = DAG.getNode(ISD::FSUB, MVT::f32, t10,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003118 getF32Constant(DAG, 0x4042902c));
Bill Wendling3eb59402008-09-09 00:28:24 +00003119
3120 result = DAG.getNode(ISD::FADD, MVT::f32, LogOfExponent, Log2ofMantissa);
3121 }
Dale Johannesen853244f2008-09-05 23:49:37 +00003122 } else {
Bill Wendling3eb59402008-09-09 00:28:24 +00003123 // No special expansion.
Dale Johannesen853244f2008-09-05 23:49:37 +00003124 result = DAG.getNode(ISD::FLOG2,
3125 getValue(I.getOperand(1)).getValueType(),
3126 getValue(I.getOperand(1)));
3127 }
Bill Wendling3eb59402008-09-09 00:28:24 +00003128
Dale Johannesen59e577f2008-09-05 18:38:42 +00003129 setValue(&I, result);
3130}
3131
Bill Wendling3eb59402008-09-09 00:28:24 +00003132/// visitLog10 - Lower a log10 intrinsic. Handles the special sequences for
3133/// limited-precision mode.
Dale Johannesen59e577f2008-09-05 18:38:42 +00003134void
3135SelectionDAGLowering::visitLog10(CallInst &I) {
3136 SDValue result;
Dale Johannesen852680a2008-09-05 21:27:19 +00003137 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
Bill Wendling3eb59402008-09-09 00:28:24 +00003138 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3139 SDValue Op = getValue(I.getOperand(1));
3140 SDValue Op1 = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, Op);
3141
Bill Wendling39150252008-09-09 20:39:27 +00003142 // Scale the exponent by log10(2) [0.30102999f].
3143 SDValue Exp = GetExponent(DAG, Op1);
3144 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, MVT::f32, Exp,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003145 getF32Constant(DAG, 0x3e9a209a));
Bill Wendling3eb59402008-09-09 00:28:24 +00003146
3147 // Get the significand and build it into a floating-point number with
Bill Wendling39150252008-09-09 20:39:27 +00003148 // exponent of 1.
3149 SDValue X = GetSignificand(DAG, Op1);
Bill Wendling3eb59402008-09-09 00:28:24 +00003150
3151 if (LimitFloatPrecision <= 6) {
Bill Wendlingbd297bc2008-09-09 18:42:23 +00003152 // For floating-point precision of 6:
3153 //
3154 // Log10ofMantissa =
3155 // -0.50419619f +
3156 // (0.60948995f - 0.10380950f * x) * x;
3157 //
3158 // error 0.0014886165, which is 6 bits
Bill Wendling39150252008-09-09 20:39:27 +00003159 SDValue t0 = DAG.getNode(ISD::FMUL, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003160 getF32Constant(DAG, 0xbdd49a13));
Bill Wendling39150252008-09-09 20:39:27 +00003161 SDValue t1 = DAG.getNode(ISD::FADD, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003162 getF32Constant(DAG, 0x3f1c0789));
Bill Wendling39150252008-09-09 20:39:27 +00003163 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, t1, X);
3164 SDValue Log10ofMantissa = DAG.getNode(ISD::FSUB, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003165 getF32Constant(DAG, 0x3f011300));
Bill Wendlingbd297bc2008-09-09 18:42:23 +00003166
3167 result = DAG.getNode(ISD::FADD, MVT::f32, LogOfExponent, Log10ofMantissa);
Bill Wendling3eb59402008-09-09 00:28:24 +00003168 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3169 // For floating-point precision of 12:
3170 //
3171 // Log10ofMantissa =
3172 // -0.64831180f +
3173 // (0.91751397f +
3174 // (-0.31664806f + 0.47637168e-1f * x) * x) * x;
3175 //
3176 // error 0.00019228036, which is better than 12 bits
Bill Wendling39150252008-09-09 20:39:27 +00003177 SDValue t0 = DAG.getNode(ISD::FMUL, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003178 getF32Constant(DAG, 0x3d431f31));
Bill Wendling39150252008-09-09 20:39:27 +00003179 SDValue t1 = DAG.getNode(ISD::FSUB, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003180 getF32Constant(DAG, 0x3ea21fb2));
Bill Wendling39150252008-09-09 20:39:27 +00003181 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, t1, X);
3182 SDValue t3 = DAG.getNode(ISD::FADD, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003183 getF32Constant(DAG, 0x3f6ae232));
Bill Wendling39150252008-09-09 20:39:27 +00003184 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3185 SDValue Log10ofMantissa = DAG.getNode(ISD::FSUB, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003186 getF32Constant(DAG, 0x3f25f7c3));
Bill Wendling3eb59402008-09-09 00:28:24 +00003187
3188 result = DAG.getNode(ISD::FADD, MVT::f32, LogOfExponent, Log10ofMantissa);
3189 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
Bill Wendlingbd297bc2008-09-09 18:42:23 +00003190 // For floating-point precision of 18:
3191 //
3192 // Log10ofMantissa =
3193 // -0.84299375f +
3194 // (1.5327582f +
3195 // (-1.0688956f +
3196 // (0.49102474f +
3197 // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
3198 //
3199 // error 0.0000037995730, which is better than 18 bits
Bill Wendling39150252008-09-09 20:39:27 +00003200 SDValue t0 = DAG.getNode(ISD::FMUL, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003201 getF32Constant(DAG, 0x3c5d51ce));
Bill Wendling39150252008-09-09 20:39:27 +00003202 SDValue t1 = DAG.getNode(ISD::FSUB, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003203 getF32Constant(DAG, 0x3e00685a));
Bill Wendling39150252008-09-09 20:39:27 +00003204 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, t1, X);
3205 SDValue t3 = DAG.getNode(ISD::FADD, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003206 getF32Constant(DAG, 0x3efb6798));
Bill Wendling39150252008-09-09 20:39:27 +00003207 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3208 SDValue t5 = DAG.getNode(ISD::FSUB, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003209 getF32Constant(DAG, 0x3f88d192));
Bill Wendling39150252008-09-09 20:39:27 +00003210 SDValue t6 = DAG.getNode(ISD::FMUL, MVT::f32, t5, X);
3211 SDValue t7 = DAG.getNode(ISD::FADD, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003212 getF32Constant(DAG, 0x3fc4316c));
Bill Wendlingbd297bc2008-09-09 18:42:23 +00003213 SDValue t8 = DAG.getNode(ISD::FMUL, MVT::f32, t7, X);
Bill Wendling39150252008-09-09 20:39:27 +00003214 SDValue Log10ofMantissa = DAG.getNode(ISD::FSUB, MVT::f32, t8,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003215 getF32Constant(DAG, 0x3f57ce70));
Bill Wendlingbd297bc2008-09-09 18:42:23 +00003216
3217 result = DAG.getNode(ISD::FADD, MVT::f32, LogOfExponent, Log10ofMantissa);
Bill Wendling3eb59402008-09-09 00:28:24 +00003218 }
Dale Johannesen852680a2008-09-05 21:27:19 +00003219 } else {
Bill Wendling3eb59402008-09-09 00:28:24 +00003220 // No special expansion.
Dale Johannesen852680a2008-09-05 21:27:19 +00003221 result = DAG.getNode(ISD::FLOG10,
3222 getValue(I.getOperand(1)).getValueType(),
3223 getValue(I.getOperand(1)));
3224 }
Bill Wendling3eb59402008-09-09 00:28:24 +00003225
Dale Johannesen59e577f2008-09-05 18:38:42 +00003226 setValue(&I, result);
3227}
3228
Bill Wendlinge10c8142008-09-09 22:39:21 +00003229/// visitExp2 - Lower an exp2 intrinsic. Handles the special sequences for
3230/// limited-precision mode.
Dale Johannesen601d3c02008-09-05 01:48:15 +00003231void
3232SelectionDAGLowering::visitExp2(CallInst &I) {
3233 SDValue result;
Bill Wendlinge10c8142008-09-09 22:39:21 +00003234
Dale Johannesen601d3c02008-09-05 01:48:15 +00003235 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
Bill Wendlinge10c8142008-09-09 22:39:21 +00003236 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3237 SDValue Op = getValue(I.getOperand(1));
3238
3239 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, MVT::i32, Op);
3240
3241 // FractionalPartOfX = x - (float)IntegerPartOfX;
3242 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, MVT::f32, IntegerPartOfX);
3243 SDValue X = DAG.getNode(ISD::FSUB, MVT::f32, Op, t1);
3244
3245 // IntegerPartOfX <<= 23;
3246 IntegerPartOfX = DAG.getNode(ISD::SHL, MVT::i32, IntegerPartOfX,
3247 DAG.getConstant(23, MVT::i32));
3248
3249 if (LimitFloatPrecision <= 6) {
3250 // For floating-point precision of 6:
3251 //
3252 // TwoToFractionalPartOfX =
3253 // 0.997535578f +
3254 // (0.735607626f + 0.252464424f * x) * x;
3255 //
3256 // error 0.0144103317, which is 6 bits
3257 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003258 getF32Constant(DAG, 0x3e814304));
Bill Wendlinge10c8142008-09-09 22:39:21 +00003259 SDValue t3 = DAG.getNode(ISD::FADD, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003260 getF32Constant(DAG, 0x3f3c50c8));
Bill Wendlinge10c8142008-09-09 22:39:21 +00003261 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3262 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003263 getF32Constant(DAG, 0x3f7f5e7e));
Bill Wendlinge10c8142008-09-09 22:39:21 +00003264 SDValue t6 = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, t5);
3265 SDValue TwoToFractionalPartOfX =
3266 DAG.getNode(ISD::ADD, MVT::i32, t6, IntegerPartOfX);
3267
3268 result = DAG.getNode(ISD::BIT_CONVERT, MVT::f32, TwoToFractionalPartOfX);
3269 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3270 // For floating-point precision of 12:
3271 //
3272 // TwoToFractionalPartOfX =
3273 // 0.999892986f +
3274 // (0.696457318f +
3275 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
3276 //
3277 // error 0.000107046256, which is 13 to 14 bits
3278 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003279 getF32Constant(DAG, 0x3da235e3));
Bill Wendlinge10c8142008-09-09 22:39:21 +00003280 SDValue t3 = DAG.getNode(ISD::FADD, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003281 getF32Constant(DAG, 0x3e65b8f3));
Bill Wendlinge10c8142008-09-09 22:39:21 +00003282 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3283 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003284 getF32Constant(DAG, 0x3f324b07));
Bill Wendlinge10c8142008-09-09 22:39:21 +00003285 SDValue t6 = DAG.getNode(ISD::FMUL, MVT::f32, t5, X);
3286 SDValue t7 = DAG.getNode(ISD::FADD, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003287 getF32Constant(DAG, 0x3f7ff8fd));
Bill Wendlinge10c8142008-09-09 22:39:21 +00003288 SDValue t8 = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, t7);
3289 SDValue TwoToFractionalPartOfX =
3290 DAG.getNode(ISD::ADD, MVT::i32, t8, IntegerPartOfX);
3291
3292 result = DAG.getNode(ISD::BIT_CONVERT, MVT::f32, TwoToFractionalPartOfX);
3293 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3294 // For floating-point precision of 18:
3295 //
3296 // TwoToFractionalPartOfX =
3297 // 0.999999982f +
3298 // (0.693148872f +
3299 // (0.240227044f +
3300 // (0.554906021e-1f +
3301 // (0.961591928e-2f +
3302 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
3303 // error 2.47208000*10^(-7), which is better than 18 bits
3304 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003305 getF32Constant(DAG, 0x3924b03e));
Bill Wendlinge10c8142008-09-09 22:39:21 +00003306 SDValue t3 = DAG.getNode(ISD::FADD, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003307 getF32Constant(DAG, 0x3ab24b87));
Bill Wendlinge10c8142008-09-09 22:39:21 +00003308 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3309 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003310 getF32Constant(DAG, 0x3c1d8c17));
Bill Wendlinge10c8142008-09-09 22:39:21 +00003311 SDValue t6 = DAG.getNode(ISD::FMUL, MVT::f32, t5, X);
3312 SDValue t7 = DAG.getNode(ISD::FADD, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003313 getF32Constant(DAG, 0x3d634a1d));
Bill Wendlinge10c8142008-09-09 22:39:21 +00003314 SDValue t8 = DAG.getNode(ISD::FMUL, MVT::f32, t7, X);
3315 SDValue t9 = DAG.getNode(ISD::FADD, MVT::f32, t8,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003316 getF32Constant(DAG, 0x3e75fe14));
Bill Wendlinge10c8142008-09-09 22:39:21 +00003317 SDValue t10 = DAG.getNode(ISD::FMUL, MVT::f32, t9, X);
3318 SDValue t11 = DAG.getNode(ISD::FADD, MVT::f32, t10,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003319 getF32Constant(DAG, 0x3f317234));
Bill Wendlinge10c8142008-09-09 22:39:21 +00003320 SDValue t12 = DAG.getNode(ISD::FMUL, MVT::f32, t11, X);
3321 SDValue t13 = DAG.getNode(ISD::FADD, MVT::f32, t12,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003322 getF32Constant(DAG, 0x3f800000));
Bill Wendlinge10c8142008-09-09 22:39:21 +00003323 SDValue t14 = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, t13);
3324 SDValue TwoToFractionalPartOfX =
3325 DAG.getNode(ISD::ADD, MVT::i32, t14, IntegerPartOfX);
3326
3327 result = DAG.getNode(ISD::BIT_CONVERT, MVT::f32, TwoToFractionalPartOfX);
3328 }
Dale Johannesen601d3c02008-09-05 01:48:15 +00003329 } else {
Bill Wendling3eb59402008-09-09 00:28:24 +00003330 // No special expansion.
Dale Johannesen601d3c02008-09-05 01:48:15 +00003331 result = DAG.getNode(ISD::FEXP2,
3332 getValue(I.getOperand(1)).getValueType(),
3333 getValue(I.getOperand(1)));
3334 }
Bill Wendlinge10c8142008-09-09 22:39:21 +00003335
Dale Johannesen601d3c02008-09-05 01:48:15 +00003336 setValue(&I, result);
3337}
3338
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003339/// visitPow - Lower a pow intrinsic. Handles the special sequences for
3340/// limited-precision mode with x == 10.0f.
3341void
3342SelectionDAGLowering::visitPow(CallInst &I) {
3343 SDValue result;
3344 Value *Val = I.getOperand(1);
3345 bool IsExp10 = false;
3346
3347 if (getValue(Val).getValueType() == MVT::f32 &&
Bill Wendling277fc242008-09-10 00:24:59 +00003348 getValue(I.getOperand(2)).getValueType() == MVT::f32 &&
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003349 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3350 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(Val))) {
3351 if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
3352 APFloat Ten(10.0f);
3353 IsExp10 = CFP->getValueAPF().bitwiseIsEqual(Ten);
3354 }
3355 }
3356 }
3357
3358 if (IsExp10 && LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3359 SDValue Op = getValue(I.getOperand(2));
3360
3361 // Put the exponent in the right bit position for later addition to the
3362 // final result:
3363 //
3364 // #define LOG2OF10 3.3219281f
3365 // IntegerPartOfX = (int32_t)(x * LOG2OF10);
3366 SDValue t0 = DAG.getNode(ISD::FMUL, MVT::f32, Op,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003367 getF32Constant(DAG, 0x40549a78));
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003368 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, MVT::i32, t0);
3369
3370 // FractionalPartOfX = x - (float)IntegerPartOfX;
3371 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, MVT::f32, IntegerPartOfX);
3372 SDValue X = DAG.getNode(ISD::FSUB, MVT::f32, t0, t1);
3373
3374 // IntegerPartOfX <<= 23;
3375 IntegerPartOfX = DAG.getNode(ISD::SHL, MVT::i32, IntegerPartOfX,
3376 DAG.getConstant(23, MVT::i32));
3377
3378 if (LimitFloatPrecision <= 6) {
3379 // For floating-point precision of 6:
3380 //
3381 // twoToFractionalPartOfX =
3382 // 0.997535578f +
3383 // (0.735607626f + 0.252464424f * x) * x;
3384 //
3385 // error 0.0144103317, which is 6 bits
3386 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003387 getF32Constant(DAG, 0x3e814304));
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003388 SDValue t3 = DAG.getNode(ISD::FADD, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003389 getF32Constant(DAG, 0x3f3c50c8));
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003390 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3391 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003392 getF32Constant(DAG, 0x3f7f5e7e));
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003393 SDValue t6 = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, t5);
3394 SDValue TwoToFractionalPartOfX =
3395 DAG.getNode(ISD::ADD, MVT::i32, t6, IntegerPartOfX);
3396
3397 result = DAG.getNode(ISD::BIT_CONVERT, MVT::f32, TwoToFractionalPartOfX);
3398 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3399 // For floating-point precision of 12:
3400 //
3401 // TwoToFractionalPartOfX =
3402 // 0.999892986f +
3403 // (0.696457318f +
3404 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
3405 //
3406 // error 0.000107046256, which is 13 to 14 bits
3407 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003408 getF32Constant(DAG, 0x3da235e3));
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003409 SDValue t3 = DAG.getNode(ISD::FADD, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003410 getF32Constant(DAG, 0x3e65b8f3));
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003411 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3412 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003413 getF32Constant(DAG, 0x3f324b07));
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003414 SDValue t6 = DAG.getNode(ISD::FMUL, MVT::f32, t5, X);
3415 SDValue t7 = DAG.getNode(ISD::FADD, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003416 getF32Constant(DAG, 0x3f7ff8fd));
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003417 SDValue t8 = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, t7);
3418 SDValue TwoToFractionalPartOfX =
3419 DAG.getNode(ISD::ADD, MVT::i32, t8, IntegerPartOfX);
3420
3421 result = DAG.getNode(ISD::BIT_CONVERT, MVT::f32, TwoToFractionalPartOfX);
3422 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3423 // For floating-point precision of 18:
3424 //
3425 // TwoToFractionalPartOfX =
3426 // 0.999999982f +
3427 // (0.693148872f +
3428 // (0.240227044f +
3429 // (0.554906021e-1f +
3430 // (0.961591928e-2f +
3431 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
3432 // error 2.47208000*10^(-7), which is better than 18 bits
3433 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003434 getF32Constant(DAG, 0x3924b03e));
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003435 SDValue t3 = DAG.getNode(ISD::FADD, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003436 getF32Constant(DAG, 0x3ab24b87));
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003437 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3438 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003439 getF32Constant(DAG, 0x3c1d8c17));
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003440 SDValue t6 = DAG.getNode(ISD::FMUL, MVT::f32, t5, X);
3441 SDValue t7 = DAG.getNode(ISD::FADD, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003442 getF32Constant(DAG, 0x3d634a1d));
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003443 SDValue t8 = DAG.getNode(ISD::FMUL, MVT::f32, t7, X);
3444 SDValue t9 = DAG.getNode(ISD::FADD, MVT::f32, t8,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003445 getF32Constant(DAG, 0x3e75fe14));
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003446 SDValue t10 = DAG.getNode(ISD::FMUL, MVT::f32, t9, X);
3447 SDValue t11 = DAG.getNode(ISD::FADD, MVT::f32, t10,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003448 getF32Constant(DAG, 0x3f317234));
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003449 SDValue t12 = DAG.getNode(ISD::FMUL, MVT::f32, t11, X);
3450 SDValue t13 = DAG.getNode(ISD::FADD, MVT::f32, t12,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003451 getF32Constant(DAG, 0x3f800000));
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003452 SDValue t14 = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, t13);
3453 SDValue TwoToFractionalPartOfX =
3454 DAG.getNode(ISD::ADD, MVT::i32, t14, IntegerPartOfX);
3455
3456 result = DAG.getNode(ISD::BIT_CONVERT, MVT::f32, TwoToFractionalPartOfX);
3457 }
3458 } else {
3459 // No special expansion.
3460 result = DAG.getNode(ISD::FPOW,
3461 getValue(I.getOperand(1)).getValueType(),
3462 getValue(I.getOperand(1)),
3463 getValue(I.getOperand(2)));
3464 }
3465
3466 setValue(&I, result);
3467}
3468
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003469/// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
3470/// we want to emit this as a call to a named external function, return the name
3471/// otherwise lower it and return null.
3472const char *
3473SelectionDAGLowering::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
3474 switch (Intrinsic) {
3475 default:
3476 // By default, turn this into a target intrinsic node.
3477 visitTargetIntrinsic(I, Intrinsic);
3478 return 0;
3479 case Intrinsic::vastart: visitVAStart(I); return 0;
3480 case Intrinsic::vaend: visitVAEnd(I); return 0;
3481 case Intrinsic::vacopy: visitVACopy(I); return 0;
3482 case Intrinsic::returnaddress:
3483 setValue(&I, DAG.getNode(ISD::RETURNADDR, TLI.getPointerTy(),
3484 getValue(I.getOperand(1))));
3485 return 0;
Bill Wendlingd5d81912008-09-26 22:10:44 +00003486 case Intrinsic::frameaddress:
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003487 setValue(&I, DAG.getNode(ISD::FRAMEADDR, TLI.getPointerTy(),
3488 getValue(I.getOperand(1))));
3489 return 0;
3490 case Intrinsic::setjmp:
3491 return "_setjmp"+!TLI.usesUnderscoreSetJmp();
3492 break;
3493 case Intrinsic::longjmp:
3494 return "_longjmp"+!TLI.usesUnderscoreLongJmp();
3495 break;
3496 case Intrinsic::memcpy_i32:
3497 case Intrinsic::memcpy_i64: {
3498 SDValue Op1 = getValue(I.getOperand(1));
3499 SDValue Op2 = getValue(I.getOperand(2));
3500 SDValue Op3 = getValue(I.getOperand(3));
3501 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
3502 DAG.setRoot(DAG.getMemcpy(getRoot(), Op1, Op2, Op3, Align, false,
3503 I.getOperand(1), 0, I.getOperand(2), 0));
3504 return 0;
3505 }
3506 case Intrinsic::memset_i32:
3507 case Intrinsic::memset_i64: {
3508 SDValue Op1 = getValue(I.getOperand(1));
3509 SDValue Op2 = getValue(I.getOperand(2));
3510 SDValue Op3 = getValue(I.getOperand(3));
3511 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
3512 DAG.setRoot(DAG.getMemset(getRoot(), Op1, Op2, Op3, Align,
3513 I.getOperand(1), 0));
3514 return 0;
3515 }
3516 case Intrinsic::memmove_i32:
3517 case Intrinsic::memmove_i64: {
3518 SDValue Op1 = getValue(I.getOperand(1));
3519 SDValue Op2 = getValue(I.getOperand(2));
3520 SDValue Op3 = getValue(I.getOperand(3));
3521 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
3522
3523 // If the source and destination are known to not be aliases, we can
3524 // lower memmove as memcpy.
3525 uint64_t Size = -1ULL;
3526 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op3))
Dan Gohmanf5aeb1a2008-09-12 16:56:44 +00003527 Size = C->getZExtValue();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003528 if (AA->alias(I.getOperand(1), Size, I.getOperand(2), Size) ==
3529 AliasAnalysis::NoAlias) {
3530 DAG.setRoot(DAG.getMemcpy(getRoot(), Op1, Op2, Op3, Align, false,
3531 I.getOperand(1), 0, I.getOperand(2), 0));
3532 return 0;
3533 }
3534
3535 DAG.setRoot(DAG.getMemmove(getRoot(), Op1, Op2, Op3, Align,
3536 I.getOperand(1), 0, I.getOperand(2), 0));
3537 return 0;
3538 }
3539 case Intrinsic::dbg_stoppoint: {
3540 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3541 DbgStopPointInst &SPI = cast<DbgStopPointInst>(I);
3542 if (MMI && SPI.getContext() && MMI->Verify(SPI.getContext())) {
3543 DebugInfoDesc *DD = MMI->getDescFor(SPI.getContext());
3544 assert(DD && "Not a debug information descriptor");
3545 DAG.setRoot(DAG.getDbgStopPoint(getRoot(),
3546 SPI.getLine(),
3547 SPI.getColumn(),
3548 cast<CompileUnitDesc>(DD)));
3549 }
3550
3551 return 0;
3552 }
3553 case Intrinsic::dbg_region_start: {
3554 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3555 DbgRegionStartInst &RSI = cast<DbgRegionStartInst>(I);
3556 if (MMI && RSI.getContext() && MMI->Verify(RSI.getContext())) {
3557 unsigned LabelID = MMI->RecordRegionStart(RSI.getContext());
3558 DAG.setRoot(DAG.getLabel(ISD::DBG_LABEL, getRoot(), LabelID));
3559 }
3560
3561 return 0;
3562 }
3563 case Intrinsic::dbg_region_end: {
3564 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3565 DbgRegionEndInst &REI = cast<DbgRegionEndInst>(I);
3566 if (MMI && REI.getContext() && MMI->Verify(REI.getContext())) {
3567 unsigned LabelID = MMI->RecordRegionEnd(REI.getContext());
3568 DAG.setRoot(DAG.getLabel(ISD::DBG_LABEL, getRoot(), LabelID));
3569 }
3570
3571 return 0;
3572 }
3573 case Intrinsic::dbg_func_start: {
3574 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3575 if (!MMI) return 0;
3576 DbgFuncStartInst &FSI = cast<DbgFuncStartInst>(I);
3577 Value *SP = FSI.getSubprogram();
3578 if (SP && MMI->Verify(SP)) {
3579 // llvm.dbg.func.start implicitly defines a dbg_stoppoint which is
3580 // what (most?) gdb expects.
3581 DebugInfoDesc *DD = MMI->getDescFor(SP);
3582 assert(DD && "Not a debug information descriptor");
3583 SubprogramDesc *Subprogram = cast<SubprogramDesc>(DD);
3584 const CompileUnitDesc *CompileUnit = Subprogram->getFile();
3585 unsigned SrcFile = MMI->RecordSource(CompileUnit);
3586 // Record the source line but does create a label. It will be emitted
3587 // at asm emission time.
3588 MMI->RecordSourceLine(Subprogram->getLine(), 0, SrcFile);
3589 }
3590
3591 return 0;
3592 }
3593 case Intrinsic::dbg_declare: {
3594 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3595 DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
3596 Value *Variable = DI.getVariable();
3597 if (MMI && Variable && MMI->Verify(Variable))
3598 DAG.setRoot(DAG.getNode(ISD::DECLARE, MVT::Other, getRoot(),
3599 getValue(DI.getAddress()), getValue(Variable)));
3600 return 0;
3601 }
3602
3603 case Intrinsic::eh_exception: {
3604 if (!CurMBB->isLandingPad()) {
3605 // FIXME: Mark exception register as live in. Hack for PR1508.
3606 unsigned Reg = TLI.getExceptionAddressRegister();
3607 if (Reg) CurMBB->addLiveIn(Reg);
3608 }
3609 // Insert the EXCEPTIONADDR instruction.
3610 SDVTList VTs = DAG.getVTList(TLI.getPointerTy(), MVT::Other);
3611 SDValue Ops[1];
3612 Ops[0] = DAG.getRoot();
3613 SDValue Op = DAG.getNode(ISD::EXCEPTIONADDR, VTs, Ops, 1);
3614 setValue(&I, Op);
3615 DAG.setRoot(Op.getValue(1));
3616 return 0;
3617 }
3618
3619 case Intrinsic::eh_selector_i32:
3620 case Intrinsic::eh_selector_i64: {
3621 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3622 MVT VT = (Intrinsic == Intrinsic::eh_selector_i32 ?
3623 MVT::i32 : MVT::i64);
3624
3625 if (MMI) {
3626 if (CurMBB->isLandingPad())
3627 AddCatchInfo(I, MMI, CurMBB);
3628 else {
3629#ifndef NDEBUG
3630 FuncInfo.CatchInfoLost.insert(&I);
3631#endif
3632 // FIXME: Mark exception selector register as live in. Hack for PR1508.
3633 unsigned Reg = TLI.getExceptionSelectorRegister();
3634 if (Reg) CurMBB->addLiveIn(Reg);
3635 }
3636
3637 // Insert the EHSELECTION instruction.
3638 SDVTList VTs = DAG.getVTList(VT, MVT::Other);
3639 SDValue Ops[2];
3640 Ops[0] = getValue(I.getOperand(1));
3641 Ops[1] = getRoot();
3642 SDValue Op = DAG.getNode(ISD::EHSELECTION, VTs, Ops, 2);
3643 setValue(&I, Op);
3644 DAG.setRoot(Op.getValue(1));
3645 } else {
3646 setValue(&I, DAG.getConstant(0, VT));
3647 }
3648
3649 return 0;
3650 }
3651
3652 case Intrinsic::eh_typeid_for_i32:
3653 case Intrinsic::eh_typeid_for_i64: {
3654 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3655 MVT VT = (Intrinsic == Intrinsic::eh_typeid_for_i32 ?
3656 MVT::i32 : MVT::i64);
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00003657
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003658 if (MMI) {
3659 // Find the type id for the given typeinfo.
3660 GlobalVariable *GV = ExtractTypeInfo(I.getOperand(1));
3661
3662 unsigned TypeID = MMI->getTypeIDFor(GV);
3663 setValue(&I, DAG.getConstant(TypeID, VT));
3664 } else {
3665 // Return something different to eh_selector.
3666 setValue(&I, DAG.getConstant(1, VT));
3667 }
3668
3669 return 0;
3670 }
3671
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00003672 case Intrinsic::eh_return_i32:
3673 case Intrinsic::eh_return_i64:
3674 if (MachineModuleInfo *MMI = DAG.getMachineModuleInfo()) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003675 MMI->setCallsEHReturn(true);
3676 DAG.setRoot(DAG.getNode(ISD::EH_RETURN,
3677 MVT::Other,
3678 getControlRoot(),
3679 getValue(I.getOperand(1)),
3680 getValue(I.getOperand(2))));
3681 } else {
3682 setValue(&I, DAG.getConstant(0, TLI.getPointerTy()));
3683 }
3684
3685 return 0;
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00003686 case Intrinsic::eh_unwind_init:
3687 if (MachineModuleInfo *MMI = DAG.getMachineModuleInfo()) {
3688 MMI->setCallsUnwindInit(true);
3689 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003690
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00003691 return 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003692
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00003693 case Intrinsic::eh_dwarf_cfa: {
3694 MVT VT = getValue(I.getOperand(1)).getValueType();
3695 SDValue CfaArg;
3696 if (VT.bitsGT(TLI.getPointerTy()))
3697 CfaArg = DAG.getNode(ISD::TRUNCATE,
3698 TLI.getPointerTy(), getValue(I.getOperand(1)));
3699 else
3700 CfaArg = DAG.getNode(ISD::SIGN_EXTEND,
3701 TLI.getPointerTy(), getValue(I.getOperand(1)));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003702
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00003703 SDValue Offset = DAG.getNode(ISD::ADD,
3704 TLI.getPointerTy(),
3705 DAG.getNode(ISD::FRAME_TO_ARGS_OFFSET,
3706 TLI.getPointerTy()),
3707 CfaArg);
3708 setValue(&I, DAG.getNode(ISD::ADD,
3709 TLI.getPointerTy(),
3710 DAG.getNode(ISD::FRAMEADDR,
3711 TLI.getPointerTy(),
3712 DAG.getConstant(0,
3713 TLI.getPointerTy())),
3714 Offset));
3715 return 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003716 }
3717
3718 case Intrinsic::sqrt:
3719 setValue(&I, DAG.getNode(ISD::FSQRT,
3720 getValue(I.getOperand(1)).getValueType(),
3721 getValue(I.getOperand(1))));
3722 return 0;
3723 case Intrinsic::powi:
3724 setValue(&I, DAG.getNode(ISD::FPOWI,
3725 getValue(I.getOperand(1)).getValueType(),
3726 getValue(I.getOperand(1)),
3727 getValue(I.getOperand(2))));
3728 return 0;
3729 case Intrinsic::sin:
3730 setValue(&I, DAG.getNode(ISD::FSIN,
3731 getValue(I.getOperand(1)).getValueType(),
3732 getValue(I.getOperand(1))));
3733 return 0;
3734 case Intrinsic::cos:
3735 setValue(&I, DAG.getNode(ISD::FCOS,
3736 getValue(I.getOperand(1)).getValueType(),
3737 getValue(I.getOperand(1))));
3738 return 0;
Dale Johannesen7794f2a2008-09-04 00:47:13 +00003739 case Intrinsic::log:
Dale Johannesen59e577f2008-09-05 18:38:42 +00003740 visitLog(I);
Dale Johannesen7794f2a2008-09-04 00:47:13 +00003741 return 0;
3742 case Intrinsic::log2:
Dale Johannesen59e577f2008-09-05 18:38:42 +00003743 visitLog2(I);
Dale Johannesen7794f2a2008-09-04 00:47:13 +00003744 return 0;
3745 case Intrinsic::log10:
Dale Johannesen59e577f2008-09-05 18:38:42 +00003746 visitLog10(I);
Dale Johannesen7794f2a2008-09-04 00:47:13 +00003747 return 0;
3748 case Intrinsic::exp:
Dale Johannesen59e577f2008-09-05 18:38:42 +00003749 visitExp(I);
Dale Johannesen7794f2a2008-09-04 00:47:13 +00003750 return 0;
3751 case Intrinsic::exp2:
Dale Johannesen601d3c02008-09-05 01:48:15 +00003752 visitExp2(I);
Dale Johannesen7794f2a2008-09-04 00:47:13 +00003753 return 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003754 case Intrinsic::pow:
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003755 visitPow(I);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003756 return 0;
3757 case Intrinsic::pcmarker: {
3758 SDValue Tmp = getValue(I.getOperand(1));
3759 DAG.setRoot(DAG.getNode(ISD::PCMARKER, MVT::Other, getRoot(), Tmp));
3760 return 0;
3761 }
3762 case Intrinsic::readcyclecounter: {
3763 SDValue Op = getRoot();
3764 SDValue Tmp = DAG.getNode(ISD::READCYCLECOUNTER,
3765 DAG.getNodeValueTypes(MVT::i64, MVT::Other), 2,
3766 &Op, 1);
3767 setValue(&I, Tmp);
3768 DAG.setRoot(Tmp.getValue(1));
3769 return 0;
3770 }
3771 case Intrinsic::part_select: {
3772 // Currently not implemented: just abort
3773 assert(0 && "part_select intrinsic not implemented");
3774 abort();
3775 }
3776 case Intrinsic::part_set: {
3777 // Currently not implemented: just abort
3778 assert(0 && "part_set intrinsic not implemented");
3779 abort();
3780 }
3781 case Intrinsic::bswap:
3782 setValue(&I, DAG.getNode(ISD::BSWAP,
3783 getValue(I.getOperand(1)).getValueType(),
3784 getValue(I.getOperand(1))));
3785 return 0;
3786 case Intrinsic::cttz: {
3787 SDValue Arg = getValue(I.getOperand(1));
3788 MVT Ty = Arg.getValueType();
3789 SDValue result = DAG.getNode(ISD::CTTZ, Ty, Arg);
3790 setValue(&I, result);
3791 return 0;
3792 }
3793 case Intrinsic::ctlz: {
3794 SDValue Arg = getValue(I.getOperand(1));
3795 MVT Ty = Arg.getValueType();
3796 SDValue result = DAG.getNode(ISD::CTLZ, Ty, Arg);
3797 setValue(&I, result);
3798 return 0;
3799 }
3800 case Intrinsic::ctpop: {
3801 SDValue Arg = getValue(I.getOperand(1));
3802 MVT Ty = Arg.getValueType();
3803 SDValue result = DAG.getNode(ISD::CTPOP, Ty, Arg);
3804 setValue(&I, result);
3805 return 0;
3806 }
3807 case Intrinsic::stacksave: {
3808 SDValue Op = getRoot();
3809 SDValue Tmp = DAG.getNode(ISD::STACKSAVE,
3810 DAG.getNodeValueTypes(TLI.getPointerTy(), MVT::Other), 2, &Op, 1);
3811 setValue(&I, Tmp);
3812 DAG.setRoot(Tmp.getValue(1));
3813 return 0;
3814 }
3815 case Intrinsic::stackrestore: {
3816 SDValue Tmp = getValue(I.getOperand(1));
3817 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, MVT::Other, getRoot(), Tmp));
3818 return 0;
3819 }
3820 case Intrinsic::var_annotation:
3821 // Discard annotate attributes
3822 return 0;
3823
3824 case Intrinsic::init_trampoline: {
3825 const Function *F = cast<Function>(I.getOperand(2)->stripPointerCasts());
3826
3827 SDValue Ops[6];
3828 Ops[0] = getRoot();
3829 Ops[1] = getValue(I.getOperand(1));
3830 Ops[2] = getValue(I.getOperand(2));
3831 Ops[3] = getValue(I.getOperand(3));
3832 Ops[4] = DAG.getSrcValue(I.getOperand(1));
3833 Ops[5] = DAG.getSrcValue(F);
3834
3835 SDValue Tmp = DAG.getNode(ISD::TRAMPOLINE,
3836 DAG.getNodeValueTypes(TLI.getPointerTy(),
3837 MVT::Other), 2,
3838 Ops, 6);
3839
3840 setValue(&I, Tmp);
3841 DAG.setRoot(Tmp.getValue(1));
3842 return 0;
3843 }
3844
3845 case Intrinsic::gcroot:
3846 if (GFI) {
3847 Value *Alloca = I.getOperand(1);
3848 Constant *TypeMap = cast<Constant>(I.getOperand(2));
3849
3850 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
3851 GFI->addStackRoot(FI->getIndex(), TypeMap);
3852 }
3853 return 0;
3854
3855 case Intrinsic::gcread:
3856 case Intrinsic::gcwrite:
3857 assert(0 && "GC failed to lower gcread/gcwrite intrinsics!");
3858 return 0;
3859
3860 case Intrinsic::flt_rounds: {
3861 setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, MVT::i32));
3862 return 0;
3863 }
3864
3865 case Intrinsic::trap: {
3866 DAG.setRoot(DAG.getNode(ISD::TRAP, MVT::Other, getRoot()));
3867 return 0;
3868 }
3869 case Intrinsic::prefetch: {
3870 SDValue Ops[4];
3871 Ops[0] = getRoot();
3872 Ops[1] = getValue(I.getOperand(1));
3873 Ops[2] = getValue(I.getOperand(2));
3874 Ops[3] = getValue(I.getOperand(3));
3875 DAG.setRoot(DAG.getNode(ISD::PREFETCH, MVT::Other, &Ops[0], 4));
3876 return 0;
3877 }
3878
3879 case Intrinsic::memory_barrier: {
3880 SDValue Ops[6];
3881 Ops[0] = getRoot();
3882 for (int x = 1; x < 6; ++x)
3883 Ops[x] = getValue(I.getOperand(x));
3884
3885 DAG.setRoot(DAG.getNode(ISD::MEMBARRIER, MVT::Other, &Ops[0], 6));
3886 return 0;
3887 }
3888 case Intrinsic::atomic_cmp_swap: {
3889 SDValue Root = getRoot();
3890 SDValue L;
3891 switch (getValue(I.getOperand(2)).getValueType().getSimpleVT()) {
3892 case MVT::i8:
3893 L = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP_8, Root,
3894 getValue(I.getOperand(1)),
3895 getValue(I.getOperand(2)),
3896 getValue(I.getOperand(3)),
3897 I.getOperand(1));
3898 break;
3899 case MVT::i16:
3900 L = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP_16, Root,
3901 getValue(I.getOperand(1)),
3902 getValue(I.getOperand(2)),
3903 getValue(I.getOperand(3)),
3904 I.getOperand(1));
3905 break;
3906 case MVT::i32:
3907 L = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP_32, Root,
3908 getValue(I.getOperand(1)),
3909 getValue(I.getOperand(2)),
3910 getValue(I.getOperand(3)),
3911 I.getOperand(1));
3912 break;
3913 case MVT::i64:
3914 L = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP_64, Root,
3915 getValue(I.getOperand(1)),
3916 getValue(I.getOperand(2)),
3917 getValue(I.getOperand(3)),
3918 I.getOperand(1));
3919 break;
3920 default:
3921 assert(0 && "Invalid atomic type");
3922 abort();
3923 }
3924 setValue(&I, L);
3925 DAG.setRoot(L.getValue(1));
3926 return 0;
3927 }
3928 case Intrinsic::atomic_load_add:
3929 switch (getValue(I.getOperand(2)).getValueType().getSimpleVT()) {
3930 case MVT::i8:
3931 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_ADD_8);
3932 case MVT::i16:
3933 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_ADD_16);
3934 case MVT::i32:
3935 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_ADD_32);
3936 case MVT::i64:
3937 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_ADD_64);
3938 default:
3939 assert(0 && "Invalid atomic type");
3940 abort();
3941 }
3942 case Intrinsic::atomic_load_sub:
3943 switch (getValue(I.getOperand(2)).getValueType().getSimpleVT()) {
3944 case MVT::i8:
3945 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_SUB_8);
3946 case MVT::i16:
3947 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_SUB_16);
3948 case MVT::i32:
3949 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_SUB_32);
3950 case MVT::i64:
3951 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_SUB_64);
3952 default:
3953 assert(0 && "Invalid atomic type");
3954 abort();
3955 }
3956 case Intrinsic::atomic_load_or:
3957 switch (getValue(I.getOperand(2)).getValueType().getSimpleVT()) {
3958 case MVT::i8:
3959 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_OR_8);
3960 case MVT::i16:
3961 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_OR_16);
3962 case MVT::i32:
3963 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_OR_32);
3964 case MVT::i64:
3965 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_OR_64);
3966 default:
3967 assert(0 && "Invalid atomic type");
3968 abort();
3969 }
3970 case Intrinsic::atomic_load_xor:
3971 switch (getValue(I.getOperand(2)).getValueType().getSimpleVT()) {
3972 case MVT::i8:
3973 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_XOR_8);
3974 case MVT::i16:
3975 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_XOR_16);
3976 case MVT::i32:
3977 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_XOR_32);
3978 case MVT::i64:
3979 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_XOR_64);
3980 default:
3981 assert(0 && "Invalid atomic type");
3982 abort();
3983 }
3984 case Intrinsic::atomic_load_and:
3985 switch (getValue(I.getOperand(2)).getValueType().getSimpleVT()) {
3986 case MVT::i8:
3987 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_AND_8);
3988 case MVT::i16:
3989 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_AND_16);
3990 case MVT::i32:
3991 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_AND_32);
3992 case MVT::i64:
3993 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_AND_64);
3994 default:
3995 assert(0 && "Invalid atomic type");
3996 abort();
3997 }
3998 case Intrinsic::atomic_load_nand:
3999 switch (getValue(I.getOperand(2)).getValueType().getSimpleVT()) {
4000 case MVT::i8:
4001 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_NAND_8);
4002 case MVT::i16:
4003 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_NAND_16);
4004 case MVT::i32:
4005 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_NAND_32);
4006 case MVT::i64:
4007 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_NAND_64);
4008 default:
4009 assert(0 && "Invalid atomic type");
4010 abort();
4011 }
4012 case Intrinsic::atomic_load_max:
4013 switch (getValue(I.getOperand(2)).getValueType().getSimpleVT()) {
4014 case MVT::i8:
4015 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MAX_8);
4016 case MVT::i16:
4017 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MAX_16);
4018 case MVT::i32:
4019 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MAX_32);
4020 case MVT::i64:
4021 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MAX_64);
4022 default:
4023 assert(0 && "Invalid atomic type");
4024 abort();
4025 }
4026 case Intrinsic::atomic_load_min:
4027 switch (getValue(I.getOperand(2)).getValueType().getSimpleVT()) {
4028 case MVT::i8:
4029 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MIN_8);
4030 case MVT::i16:
4031 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MIN_16);
4032 case MVT::i32:
4033 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MIN_32);
4034 case MVT::i64:
4035 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MIN_64);
4036 default:
4037 assert(0 && "Invalid atomic type");
4038 abort();
4039 }
4040 case Intrinsic::atomic_load_umin:
4041 switch (getValue(I.getOperand(2)).getValueType().getSimpleVT()) {
4042 case MVT::i8:
4043 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMIN_8);
4044 case MVT::i16:
4045 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMIN_16);
4046 case MVT::i32:
4047 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMIN_32);
4048 case MVT::i64:
4049 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMIN_64);
4050 default:
4051 assert(0 && "Invalid atomic type");
4052 abort();
4053 }
4054 case Intrinsic::atomic_load_umax:
4055 switch (getValue(I.getOperand(2)).getValueType().getSimpleVT()) {
4056 case MVT::i8:
4057 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMAX_8);
4058 case MVT::i16:
4059 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMAX_16);
4060 case MVT::i32:
4061 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMAX_32);
4062 case MVT::i64:
4063 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMAX_64);
4064 default:
4065 assert(0 && "Invalid atomic type");
4066 abort();
4067 }
4068 case Intrinsic::atomic_swap:
4069 switch (getValue(I.getOperand(2)).getValueType().getSimpleVT()) {
4070 case MVT::i8:
4071 return implVisitBinaryAtomic(I, ISD::ATOMIC_SWAP_8);
4072 case MVT::i16:
4073 return implVisitBinaryAtomic(I, ISD::ATOMIC_SWAP_16);
4074 case MVT::i32:
4075 return implVisitBinaryAtomic(I, ISD::ATOMIC_SWAP_32);
4076 case MVT::i64:
4077 return implVisitBinaryAtomic(I, ISD::ATOMIC_SWAP_64);
4078 default:
4079 assert(0 && "Invalid atomic type");
4080 abort();
4081 }
4082 }
4083}
4084
4085
4086void SelectionDAGLowering::LowerCallTo(CallSite CS, SDValue Callee,
4087 bool IsTailCall,
4088 MachineBasicBlock *LandingPad) {
4089 const PointerType *PT = cast<PointerType>(CS.getCalledValue()->getType());
4090 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
4091 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
4092 unsigned BeginLabel = 0, EndLabel = 0;
4093
4094 TargetLowering::ArgListTy Args;
4095 TargetLowering::ArgListEntry Entry;
4096 Args.reserve(CS.arg_size());
4097 for (CallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
4098 i != e; ++i) {
4099 SDValue ArgNode = getValue(*i);
4100 Entry.Node = ArgNode; Entry.Ty = (*i)->getType();
4101
4102 unsigned attrInd = i - CS.arg_begin() + 1;
Devang Patel05988662008-09-25 21:00:45 +00004103 Entry.isSExt = CS.paramHasAttr(attrInd, Attribute::SExt);
4104 Entry.isZExt = CS.paramHasAttr(attrInd, Attribute::ZExt);
4105 Entry.isInReg = CS.paramHasAttr(attrInd, Attribute::InReg);
4106 Entry.isSRet = CS.paramHasAttr(attrInd, Attribute::StructRet);
4107 Entry.isNest = CS.paramHasAttr(attrInd, Attribute::Nest);
4108 Entry.isByVal = CS.paramHasAttr(attrInd, Attribute::ByVal);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004109 Entry.Alignment = CS.getParamAlignment(attrInd);
4110 Args.push_back(Entry);
4111 }
4112
4113 if (LandingPad && MMI) {
4114 // Insert a label before the invoke call to mark the try range. This can be
4115 // used to detect deletion of the invoke via the MachineModuleInfo.
4116 BeginLabel = MMI->NextLabelID();
4117 // Both PendingLoads and PendingExports must be flushed here;
4118 // this call might not return.
4119 (void)getRoot();
4120 DAG.setRoot(DAG.getLabel(ISD::EH_LABEL, getControlRoot(), BeginLabel));
4121 }
4122
4123 std::pair<SDValue,SDValue> Result =
4124 TLI.LowerCallTo(getRoot(), CS.getType(),
Devang Patel05988662008-09-25 21:00:45 +00004125 CS.paramHasAttr(0, Attribute::SExt),
Dale Johannesen86098bd2008-09-26 19:31:26 +00004126 CS.paramHasAttr(0, Attribute::ZExt), FTy->isVarArg(),
4127 CS.paramHasAttr(0, Attribute::InReg),
4128 CS.getCallingConv(),
Dan Gohman1937e2f2008-09-16 01:42:28 +00004129 IsTailCall && PerformTailCallOpt,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004130 Callee, Args, DAG);
4131 if (CS.getType() != Type::VoidTy)
4132 setValue(CS.getInstruction(), Result.first);
4133 DAG.setRoot(Result.second);
4134
4135 if (LandingPad && MMI) {
4136 // Insert a label at the end of the invoke call to mark the try range. This
4137 // can be used to detect deletion of the invoke via the MachineModuleInfo.
4138 EndLabel = MMI->NextLabelID();
4139 DAG.setRoot(DAG.getLabel(ISD::EH_LABEL, getRoot(), EndLabel));
4140
4141 // Inform MachineModuleInfo of range.
4142 MMI->addInvoke(LandingPad, BeginLabel, EndLabel);
4143 }
4144}
4145
4146
4147void SelectionDAGLowering::visitCall(CallInst &I) {
4148 const char *RenameFn = 0;
4149 if (Function *F = I.getCalledFunction()) {
4150 if (F->isDeclaration()) {
4151 if (unsigned IID = F->getIntrinsicID()) {
4152 RenameFn = visitIntrinsicCall(I, IID);
4153 if (!RenameFn)
4154 return;
4155 }
4156 }
4157
4158 // Check for well-known libc/libm calls. If the function is internal, it
4159 // can't be a library call.
4160 unsigned NameLen = F->getNameLen();
4161 if (!F->hasInternalLinkage() && NameLen) {
4162 const char *NameStr = F->getNameStart();
4163 if (NameStr[0] == 'c' &&
4164 ((NameLen == 8 && !strcmp(NameStr, "copysign")) ||
4165 (NameLen == 9 && !strcmp(NameStr, "copysignf")))) {
4166 if (I.getNumOperands() == 3 && // Basic sanity checks.
4167 I.getOperand(1)->getType()->isFloatingPoint() &&
4168 I.getType() == I.getOperand(1)->getType() &&
4169 I.getType() == I.getOperand(2)->getType()) {
4170 SDValue LHS = getValue(I.getOperand(1));
4171 SDValue RHS = getValue(I.getOperand(2));
4172 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, LHS.getValueType(),
4173 LHS, RHS));
4174 return;
4175 }
4176 } else if (NameStr[0] == 'f' &&
4177 ((NameLen == 4 && !strcmp(NameStr, "fabs")) ||
4178 (NameLen == 5 && !strcmp(NameStr, "fabsf")) ||
4179 (NameLen == 5 && !strcmp(NameStr, "fabsl")))) {
4180 if (I.getNumOperands() == 2 && // Basic sanity checks.
4181 I.getOperand(1)->getType()->isFloatingPoint() &&
4182 I.getType() == I.getOperand(1)->getType()) {
4183 SDValue Tmp = getValue(I.getOperand(1));
4184 setValue(&I, DAG.getNode(ISD::FABS, Tmp.getValueType(), Tmp));
4185 return;
4186 }
4187 } else if (NameStr[0] == 's' &&
4188 ((NameLen == 3 && !strcmp(NameStr, "sin")) ||
4189 (NameLen == 4 && !strcmp(NameStr, "sinf")) ||
4190 (NameLen == 4 && !strcmp(NameStr, "sinl")))) {
4191 if (I.getNumOperands() == 2 && // Basic sanity checks.
4192 I.getOperand(1)->getType()->isFloatingPoint() &&
4193 I.getType() == I.getOperand(1)->getType()) {
4194 SDValue Tmp = getValue(I.getOperand(1));
4195 setValue(&I, DAG.getNode(ISD::FSIN, Tmp.getValueType(), Tmp));
4196 return;
4197 }
4198 } else if (NameStr[0] == 'c' &&
4199 ((NameLen == 3 && !strcmp(NameStr, "cos")) ||
4200 (NameLen == 4 && !strcmp(NameStr, "cosf")) ||
4201 (NameLen == 4 && !strcmp(NameStr, "cosl")))) {
4202 if (I.getNumOperands() == 2 && // Basic sanity checks.
4203 I.getOperand(1)->getType()->isFloatingPoint() &&
4204 I.getType() == I.getOperand(1)->getType()) {
4205 SDValue Tmp = getValue(I.getOperand(1));
4206 setValue(&I, DAG.getNode(ISD::FCOS, Tmp.getValueType(), Tmp));
4207 return;
4208 }
4209 }
4210 }
4211 } else if (isa<InlineAsm>(I.getOperand(0))) {
4212 visitInlineAsm(&I);
4213 return;
4214 }
4215
4216 SDValue Callee;
4217 if (!RenameFn)
4218 Callee = getValue(I.getOperand(0));
4219 else
Bill Wendling056292f2008-09-16 21:48:12 +00004220 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004221
4222 LowerCallTo(&I, Callee, I.isTailCall());
4223}
4224
4225
4226/// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
4227/// this value and returns the result as a ValueVT value. This uses
4228/// Chain/Flag as the input and updates them for the output Chain/Flag.
4229/// If the Flag pointer is NULL, no flag is used.
4230SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
4231 SDValue &Chain,
4232 SDValue *Flag) const {
4233 // Assemble the legal parts into the final values.
4234 SmallVector<SDValue, 4> Values(ValueVTs.size());
4235 SmallVector<SDValue, 8> Parts;
4236 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
4237 // Copy the legal parts from the registers.
4238 MVT ValueVT = ValueVTs[Value];
4239 unsigned NumRegs = TLI->getNumRegisters(ValueVT);
4240 MVT RegisterVT = RegVTs[Value];
4241
4242 Parts.resize(NumRegs);
4243 for (unsigned i = 0; i != NumRegs; ++i) {
4244 SDValue P;
4245 if (Flag == 0)
4246 P = DAG.getCopyFromReg(Chain, Regs[Part+i], RegisterVT);
4247 else {
4248 P = DAG.getCopyFromReg(Chain, Regs[Part+i], RegisterVT, *Flag);
4249 *Flag = P.getValue(2);
4250 }
4251 Chain = P.getValue(1);
4252
4253 // If the source register was virtual and if we know something about it,
4254 // add an assert node.
4255 if (TargetRegisterInfo::isVirtualRegister(Regs[Part+i]) &&
4256 RegisterVT.isInteger() && !RegisterVT.isVector()) {
4257 unsigned SlotNo = Regs[Part+i]-TargetRegisterInfo::FirstVirtualRegister;
4258 FunctionLoweringInfo &FLI = DAG.getFunctionLoweringInfo();
4259 if (FLI.LiveOutRegInfo.size() > SlotNo) {
4260 FunctionLoweringInfo::LiveOutInfo &LOI = FLI.LiveOutRegInfo[SlotNo];
4261
4262 unsigned RegSize = RegisterVT.getSizeInBits();
4263 unsigned NumSignBits = LOI.NumSignBits;
4264 unsigned NumZeroBits = LOI.KnownZero.countLeadingOnes();
4265
4266 // FIXME: We capture more information than the dag can represent. For
4267 // now, just use the tightest assertzext/assertsext possible.
4268 bool isSExt = true;
4269 MVT FromVT(MVT::Other);
4270 if (NumSignBits == RegSize)
4271 isSExt = true, FromVT = MVT::i1; // ASSERT SEXT 1
4272 else if (NumZeroBits >= RegSize-1)
4273 isSExt = false, FromVT = MVT::i1; // ASSERT ZEXT 1
4274 else if (NumSignBits > RegSize-8)
4275 isSExt = true, FromVT = MVT::i8; // ASSERT SEXT 8
4276 else if (NumZeroBits >= RegSize-9)
4277 isSExt = false, FromVT = MVT::i8; // ASSERT ZEXT 8
4278 else if (NumSignBits > RegSize-16)
4279 isSExt = true, FromVT = MVT::i16; // ASSERT SEXT 16
4280 else if (NumZeroBits >= RegSize-17)
4281 isSExt = false, FromVT = MVT::i16; // ASSERT ZEXT 16
4282 else if (NumSignBits > RegSize-32)
4283 isSExt = true, FromVT = MVT::i32; // ASSERT SEXT 32
4284 else if (NumZeroBits >= RegSize-33)
4285 isSExt = false, FromVT = MVT::i32; // ASSERT ZEXT 32
4286
4287 if (FromVT != MVT::Other) {
4288 P = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext,
4289 RegisterVT, P, DAG.getValueType(FromVT));
4290
4291 }
4292 }
4293 }
4294
4295 Parts[i] = P;
4296 }
4297
4298 Values[Value] = getCopyFromParts(DAG, Parts.begin(), NumRegs, RegisterVT,
4299 ValueVT);
4300 Part += NumRegs;
4301 Parts.clear();
4302 }
4303
4304 return DAG.getMergeValues(DAG.getVTList(&ValueVTs[0], ValueVTs.size()),
4305 &Values[0], ValueVTs.size());
4306}
4307
4308/// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
4309/// specified value into the registers specified by this object. This uses
4310/// Chain/Flag as the input and updates them for the output Chain/Flag.
4311/// If the Flag pointer is NULL, no flag is used.
4312void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG,
4313 SDValue &Chain, SDValue *Flag) const {
4314 // Get the list of the values's legal parts.
4315 unsigned NumRegs = Regs.size();
4316 SmallVector<SDValue, 8> Parts(NumRegs);
4317 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
4318 MVT ValueVT = ValueVTs[Value];
4319 unsigned NumParts = TLI->getNumRegisters(ValueVT);
4320 MVT RegisterVT = RegVTs[Value];
4321
4322 getCopyToParts(DAG, Val.getValue(Val.getResNo() + Value),
4323 &Parts[Part], NumParts, RegisterVT);
4324 Part += NumParts;
4325 }
4326
4327 // Copy the parts into the registers.
4328 SmallVector<SDValue, 8> Chains(NumRegs);
4329 for (unsigned i = 0; i != NumRegs; ++i) {
4330 SDValue Part;
4331 if (Flag == 0)
4332 Part = DAG.getCopyToReg(Chain, Regs[i], Parts[i]);
4333 else {
4334 Part = DAG.getCopyToReg(Chain, Regs[i], Parts[i], *Flag);
4335 *Flag = Part.getValue(1);
4336 }
4337 Chains[i] = Part.getValue(0);
4338 }
4339
4340 if (NumRegs == 1 || Flag)
4341 // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is
4342 // flagged to it. That is the CopyToReg nodes and the user are considered
4343 // a single scheduling unit. If we create a TokenFactor and return it as
4344 // chain, then the TokenFactor is both a predecessor (operand) of the
4345 // user as well as a successor (the TF operands are flagged to the user).
4346 // c1, f1 = CopyToReg
4347 // c2, f2 = CopyToReg
4348 // c3 = TokenFactor c1, c2
4349 // ...
4350 // = op c3, ..., f2
4351 Chain = Chains[NumRegs-1];
4352 else
4353 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other, &Chains[0], NumRegs);
4354}
4355
4356/// AddInlineAsmOperands - Add this value to the specified inlineasm node
4357/// operand list. This adds the code marker and includes the number of
4358/// values added into it.
4359void RegsForValue::AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
4360 std::vector<SDValue> &Ops) const {
4361 MVT IntPtrTy = DAG.getTargetLoweringInfo().getPointerTy();
4362 Ops.push_back(DAG.getTargetConstant(Code | (Regs.size() << 3), IntPtrTy));
4363 for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
4364 unsigned NumRegs = TLI->getNumRegisters(ValueVTs[Value]);
4365 MVT RegisterVT = RegVTs[Value];
Chris Lattner58f15c42008-10-17 16:21:11 +00004366 for (unsigned i = 0; i != NumRegs; ++i) {
4367 assert(Reg < Regs.size() && "Mismatch in # registers expected");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004368 Ops.push_back(DAG.getRegister(Regs[Reg++], RegisterVT));
Chris Lattner58f15c42008-10-17 16:21:11 +00004369 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004370 }
4371}
4372
4373/// isAllocatableRegister - If the specified register is safe to allocate,
4374/// i.e. it isn't a stack pointer or some other special register, return the
4375/// register class for the register. Otherwise, return null.
4376static const TargetRegisterClass *
4377isAllocatableRegister(unsigned Reg, MachineFunction &MF,
4378 const TargetLowering &TLI,
4379 const TargetRegisterInfo *TRI) {
4380 MVT FoundVT = MVT::Other;
4381 const TargetRegisterClass *FoundRC = 0;
4382 for (TargetRegisterInfo::regclass_iterator RCI = TRI->regclass_begin(),
4383 E = TRI->regclass_end(); RCI != E; ++RCI) {
4384 MVT ThisVT = MVT::Other;
4385
4386 const TargetRegisterClass *RC = *RCI;
4387 // If none of the the value types for this register class are valid, we
4388 // can't use it. For example, 64-bit reg classes on 32-bit targets.
4389 for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
4390 I != E; ++I) {
4391 if (TLI.isTypeLegal(*I)) {
4392 // If we have already found this register in a different register class,
4393 // choose the one with the largest VT specified. For example, on
4394 // PowerPC, we favor f64 register classes over f32.
4395 if (FoundVT == MVT::Other || FoundVT.bitsLT(*I)) {
4396 ThisVT = *I;
4397 break;
4398 }
4399 }
4400 }
4401
4402 if (ThisVT == MVT::Other) continue;
4403
4404 // NOTE: This isn't ideal. In particular, this might allocate the
4405 // frame pointer in functions that need it (due to them not being taken
4406 // out of allocation, because a variable sized allocation hasn't been seen
4407 // yet). This is a slight code pessimization, but should still work.
4408 for (TargetRegisterClass::iterator I = RC->allocation_order_begin(MF),
4409 E = RC->allocation_order_end(MF); I != E; ++I)
4410 if (*I == Reg) {
4411 // We found a matching register class. Keep looking at others in case
4412 // we find one with larger registers that this physreg is also in.
4413 FoundRC = RC;
4414 FoundVT = ThisVT;
4415 break;
4416 }
4417 }
4418 return FoundRC;
4419}
4420
4421
4422namespace llvm {
4423/// AsmOperandInfo - This contains information for each constraint that we are
4424/// lowering.
Daniel Dunbarc0c3b9a2008-09-10 04:16:29 +00004425struct VISIBILITY_HIDDEN SDISelAsmOperandInfo :
4426 public TargetLowering::AsmOperandInfo {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004427 /// CallOperand - If this is the result output operand or a clobber
4428 /// this is null, otherwise it is the incoming operand to the CallInst.
4429 /// This gets modified as the asm is processed.
4430 SDValue CallOperand;
4431
4432 /// AssignedRegs - If this is a register or register class operand, this
4433 /// contains the set of register corresponding to the operand.
4434 RegsForValue AssignedRegs;
4435
4436 explicit SDISelAsmOperandInfo(const InlineAsm::ConstraintInfo &info)
4437 : TargetLowering::AsmOperandInfo(info), CallOperand(0,0) {
4438 }
4439
4440 /// MarkAllocatedRegs - Once AssignedRegs is set, mark the assigned registers
4441 /// busy in OutputRegs/InputRegs.
4442 void MarkAllocatedRegs(bool isOutReg, bool isInReg,
4443 std::set<unsigned> &OutputRegs,
4444 std::set<unsigned> &InputRegs,
4445 const TargetRegisterInfo &TRI) const {
4446 if (isOutReg) {
4447 for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i)
4448 MarkRegAndAliases(AssignedRegs.Regs[i], OutputRegs, TRI);
4449 }
4450 if (isInReg) {
4451 for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i)
4452 MarkRegAndAliases(AssignedRegs.Regs[i], InputRegs, TRI);
4453 }
4454 }
Chris Lattner81249c92008-10-17 17:05:25 +00004455
4456 /// getCallOperandValMVT - Return the MVT of the Value* that this operand
4457 /// corresponds to. If there is no Value* for this operand, it returns
4458 /// MVT::Other.
4459 MVT getCallOperandValMVT(const TargetLowering &TLI,
4460 const TargetData *TD) const {
4461 if (CallOperandVal == 0) return MVT::Other;
4462
4463 if (isa<BasicBlock>(CallOperandVal))
4464 return TLI.getPointerTy();
4465
4466 const llvm::Type *OpTy = CallOperandVal->getType();
4467
4468 // If this is an indirect operand, the operand is a pointer to the
4469 // accessed type.
4470 if (isIndirect)
4471 OpTy = cast<PointerType>(OpTy)->getElementType();
4472
4473 // If OpTy is not a single value, it may be a struct/union that we
4474 // can tile with integers.
4475 if (!OpTy->isSingleValueType() && OpTy->isSized()) {
4476 unsigned BitSize = TD->getTypeSizeInBits(OpTy);
4477 switch (BitSize) {
4478 default: break;
4479 case 1:
4480 case 8:
4481 case 16:
4482 case 32:
4483 case 64:
4484 OpTy = IntegerType::get(BitSize);
4485 break;
4486 }
4487 }
4488
4489 return TLI.getValueType(OpTy, true);
4490 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004491
4492private:
4493 /// MarkRegAndAliases - Mark the specified register and all aliases in the
4494 /// specified set.
4495 static void MarkRegAndAliases(unsigned Reg, std::set<unsigned> &Regs,
4496 const TargetRegisterInfo &TRI) {
4497 assert(TargetRegisterInfo::isPhysicalRegister(Reg) && "Isn't a physreg");
4498 Regs.insert(Reg);
4499 if (const unsigned *Aliases = TRI.getAliasSet(Reg))
4500 for (; *Aliases; ++Aliases)
4501 Regs.insert(*Aliases);
4502 }
4503};
4504} // end llvm namespace.
4505
4506
4507/// GetRegistersForValue - Assign registers (virtual or physical) for the
4508/// specified operand. We prefer to assign virtual registers, to allow the
4509/// register allocator handle the assignment process. However, if the asm uses
4510/// features that we can't model on machineinstrs, we have SDISel do the
4511/// allocation. This produces generally horrible, but correct, code.
4512///
4513/// OpInfo describes the operand.
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004514/// Input and OutputRegs are the set of already allocated physical registers.
4515///
4516void SelectionDAGLowering::
Dale Johannesen8e3455b2008-09-24 23:13:09 +00004517GetRegistersForValue(SDISelAsmOperandInfo &OpInfo,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004518 std::set<unsigned> &OutputRegs,
4519 std::set<unsigned> &InputRegs) {
4520 // Compute whether this value requires an input register, an output register,
4521 // or both.
4522 bool isOutReg = false;
4523 bool isInReg = false;
4524 switch (OpInfo.Type) {
4525 case InlineAsm::isOutput:
4526 isOutReg = true;
4527
Dale Johannesen8e3455b2008-09-24 23:13:09 +00004528 // If there is an input constraint that matches this, we need to reserve
4529 // the input register so no other inputs allocate to it.
Chris Lattner6bdcda32008-10-17 16:47:46 +00004530 isInReg = OpInfo.hasMatchingInput();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004531 break;
4532 case InlineAsm::isInput:
4533 isInReg = true;
4534 isOutReg = false;
4535 break;
4536 case InlineAsm::isClobber:
4537 isOutReg = true;
4538 isInReg = true;
4539 break;
4540 }
4541
4542
4543 MachineFunction &MF = DAG.getMachineFunction();
4544 SmallVector<unsigned, 4> Regs;
4545
4546 // If this is a constraint for a single physreg, or a constraint for a
4547 // register class, find it.
4548 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
4549 TLI.getRegForInlineAsmConstraint(OpInfo.ConstraintCode,
4550 OpInfo.ConstraintVT);
4551
4552 unsigned NumRegs = 1;
4553 if (OpInfo.ConstraintVT != MVT::Other)
4554 NumRegs = TLI.getNumRegisters(OpInfo.ConstraintVT);
4555 MVT RegVT;
4556 MVT ValueVT = OpInfo.ConstraintVT;
4557
4558
4559 // If this is a constraint for a specific physical register, like {r17},
4560 // assign it now.
4561 if (PhysReg.first) {
4562 if (OpInfo.ConstraintVT == MVT::Other)
4563 ValueVT = *PhysReg.second->vt_begin();
4564
4565 // Get the actual register value type. This is important, because the user
4566 // may have asked for (e.g.) the AX register in i32 type. We need to
4567 // remember that AX is actually i16 to get the right extension.
4568 RegVT = *PhysReg.second->vt_begin();
4569
4570 // This is a explicit reference to a physical register.
4571 Regs.push_back(PhysReg.first);
4572
4573 // If this is an expanded reference, add the rest of the regs to Regs.
4574 if (NumRegs != 1) {
4575 TargetRegisterClass::iterator I = PhysReg.second->begin();
4576 for (; *I != PhysReg.first; ++I)
4577 assert(I != PhysReg.second->end() && "Didn't find reg!");
4578
4579 // Already added the first reg.
4580 --NumRegs; ++I;
4581 for (; NumRegs; --NumRegs, ++I) {
4582 assert(I != PhysReg.second->end() && "Ran out of registers to allocate!");
4583 Regs.push_back(*I);
4584 }
4585 }
4586 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, RegVT, ValueVT);
4587 const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
4588 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TRI);
4589 return;
4590 }
4591
4592 // Otherwise, if this was a reference to an LLVM register class, create vregs
4593 // for this reference.
4594 std::vector<unsigned> RegClassRegs;
4595 const TargetRegisterClass *RC = PhysReg.second;
4596 if (RC) {
Dale Johannesen8e3455b2008-09-24 23:13:09 +00004597 // If this is a tied register, our regalloc doesn't know how to maintain
Chris Lattner58f15c42008-10-17 16:21:11 +00004598 // the constraint, so we have to pick a register to pin the input/output to.
4599 // If it isn't a matched constraint, go ahead and create vreg and let the
4600 // regalloc do its thing.
Chris Lattner6bdcda32008-10-17 16:47:46 +00004601 if (!OpInfo.hasMatchingInput()) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004602 RegVT = *PhysReg.second->vt_begin();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004603 if (OpInfo.ConstraintVT == MVT::Other)
4604 ValueVT = RegVT;
4605
4606 // Create the appropriate number of virtual registers.
4607 MachineRegisterInfo &RegInfo = MF.getRegInfo();
4608 for (; NumRegs; --NumRegs)
4609 Regs.push_back(RegInfo.createVirtualRegister(PhysReg.second));
4610
4611 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, RegVT, ValueVT);
4612 return;
4613 }
4614
4615 // Otherwise, we can't allocate it. Let the code below figure out how to
4616 // maintain these constraints.
4617 RegClassRegs.assign(PhysReg.second->begin(), PhysReg.second->end());
4618
4619 } else {
4620 // This is a reference to a register class that doesn't directly correspond
4621 // to an LLVM register class. Allocate NumRegs consecutive, available,
4622 // registers from the class.
4623 RegClassRegs = TLI.getRegClassForInlineAsmConstraint(OpInfo.ConstraintCode,
4624 OpInfo.ConstraintVT);
4625 }
4626
4627 const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
4628 unsigned NumAllocated = 0;
4629 for (unsigned i = 0, e = RegClassRegs.size(); i != e; ++i) {
4630 unsigned Reg = RegClassRegs[i];
4631 // See if this register is available.
4632 if ((isOutReg && OutputRegs.count(Reg)) || // Already used.
4633 (isInReg && InputRegs.count(Reg))) { // Already used.
4634 // Make sure we find consecutive registers.
4635 NumAllocated = 0;
4636 continue;
4637 }
4638
4639 // Check to see if this register is allocatable (i.e. don't give out the
4640 // stack pointer).
4641 if (RC == 0) {
4642 RC = isAllocatableRegister(Reg, MF, TLI, TRI);
4643 if (!RC) { // Couldn't allocate this register.
4644 // Reset NumAllocated to make sure we return consecutive registers.
4645 NumAllocated = 0;
4646 continue;
4647 }
4648 }
4649
4650 // Okay, this register is good, we can use it.
4651 ++NumAllocated;
4652
4653 // If we allocated enough consecutive registers, succeed.
4654 if (NumAllocated == NumRegs) {
4655 unsigned RegStart = (i-NumAllocated)+1;
4656 unsigned RegEnd = i+1;
4657 // Mark all of the allocated registers used.
4658 for (unsigned i = RegStart; i != RegEnd; ++i)
4659 Regs.push_back(RegClassRegs[i]);
4660
4661 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, *RC->vt_begin(),
4662 OpInfo.ConstraintVT);
4663 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TRI);
4664 return;
4665 }
4666 }
4667
4668 // Otherwise, we couldn't allocate enough registers for this.
4669}
4670
Evan Chengda43bcf2008-09-24 00:05:32 +00004671/// hasInlineAsmMemConstraint - Return true if the inline asm instruction being
4672/// processed uses a memory 'm' constraint.
4673static bool
4674hasInlineAsmMemConstraint(std::vector<InlineAsm::ConstraintInfo> &CInfos,
4675 TargetLowering &TLI) {
4676 for (unsigned i = 0, e = CInfos.size(); i != e; ++i) {
4677 InlineAsm::ConstraintInfo &CI = CInfos[i];
4678 for (unsigned j = 0, ee = CI.Codes.size(); j != ee; ++j) {
4679 TargetLowering::ConstraintType CType = TLI.getConstraintType(CI.Codes[j]);
4680 if (CType == TargetLowering::C_Memory)
4681 return true;
4682 }
4683 }
4684
4685 return false;
4686}
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004687
4688/// visitInlineAsm - Handle a call to an InlineAsm object.
4689///
4690void SelectionDAGLowering::visitInlineAsm(CallSite CS) {
4691 InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
4692
4693 /// ConstraintOperands - Information about all of the constraints.
4694 std::vector<SDISelAsmOperandInfo> ConstraintOperands;
4695
4696 SDValue Chain = getRoot();
4697 SDValue Flag;
4698
4699 std::set<unsigned> OutputRegs, InputRegs;
4700
4701 // Do a prepass over the constraints, canonicalizing them, and building up the
4702 // ConstraintOperands list.
4703 std::vector<InlineAsm::ConstraintInfo>
4704 ConstraintInfos = IA->ParseConstraints();
4705
Evan Chengda43bcf2008-09-24 00:05:32 +00004706 bool hasMemory = hasInlineAsmMemConstraint(ConstraintInfos, TLI);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004707
4708 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst.
4709 unsigned ResNo = 0; // ResNo - The result number of the next output.
4710 for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) {
4711 ConstraintOperands.push_back(SDISelAsmOperandInfo(ConstraintInfos[i]));
4712 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
4713
4714 MVT OpVT = MVT::Other;
4715
4716 // Compute the value type for each operand.
4717 switch (OpInfo.Type) {
4718 case InlineAsm::isOutput:
4719 // Indirect outputs just consume an argument.
4720 if (OpInfo.isIndirect) {
4721 OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
4722 break;
4723 }
4724 // The return value of the call is this value. As such, there is no
4725 // corresponding argument.
4726 assert(CS.getType() != Type::VoidTy && "Bad inline asm!");
4727 if (const StructType *STy = dyn_cast<StructType>(CS.getType())) {
4728 OpVT = TLI.getValueType(STy->getElementType(ResNo));
4729 } else {
4730 assert(ResNo == 0 && "Asm only has one result!");
4731 OpVT = TLI.getValueType(CS.getType());
4732 }
4733 ++ResNo;
4734 break;
4735 case InlineAsm::isInput:
4736 OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
4737 break;
4738 case InlineAsm::isClobber:
4739 // Nothing to do.
4740 break;
4741 }
4742
4743 // If this is an input or an indirect output, process the call argument.
4744 // BasicBlocks are labels, currently appearing only in asm's.
4745 if (OpInfo.CallOperandVal) {
Chris Lattner81249c92008-10-17 17:05:25 +00004746 if (BasicBlock *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004747 OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
Chris Lattner81249c92008-10-17 17:05:25 +00004748 } else {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004749 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004750 }
Chris Lattner81249c92008-10-17 17:05:25 +00004751
4752 OpVT = OpInfo.getCallOperandValMVT(TLI, TD);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004753 }
4754
4755 OpInfo.ConstraintVT = OpVT;
4756
4757 // Compute the constraint code and ConstraintType to use.
Evan Chengda43bcf2008-09-24 00:05:32 +00004758 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, hasMemory, &DAG);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004759
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004760 // If this is a memory input, and if the operand is not indirect, do what we
4761 // need to to provide an address for the memory input.
4762 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
4763 !OpInfo.isIndirect) {
4764 assert(OpInfo.Type == InlineAsm::isInput &&
4765 "Can only indirectify direct input operands!");
4766
4767 // Memory operands really want the address of the value. If we don't have
4768 // an indirect input, put it in the constpool if we can, otherwise spill
4769 // it to a stack slot.
4770
4771 // If the operand is a float, integer, or vector constant, spill to a
4772 // constant pool entry to get its address.
4773 Value *OpVal = OpInfo.CallOperandVal;
4774 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
4775 isa<ConstantVector>(OpVal)) {
4776 OpInfo.CallOperand = DAG.getConstantPool(cast<Constant>(OpVal),
4777 TLI.getPointerTy());
4778 } else {
4779 // Otherwise, create a stack slot and emit a store to it before the
4780 // asm.
4781 const Type *Ty = OpVal->getType();
4782 uint64_t TySize = TLI.getTargetData()->getABITypeSize(Ty);
4783 unsigned Align = TLI.getTargetData()->getPrefTypeAlignment(Ty);
4784 MachineFunction &MF = DAG.getMachineFunction();
4785 int SSFI = MF.getFrameInfo()->CreateStackObject(TySize, Align);
4786 SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getPointerTy());
4787 Chain = DAG.getStore(Chain, OpInfo.CallOperand, StackSlot, NULL, 0);
4788 OpInfo.CallOperand = StackSlot;
4789 }
4790
4791 // There is no longer a Value* corresponding to this operand.
4792 OpInfo.CallOperandVal = 0;
4793 // It is now an indirect operand.
4794 OpInfo.isIndirect = true;
4795 }
4796
4797 // If this constraint is for a specific register, allocate it before
4798 // anything else.
4799 if (OpInfo.ConstraintType == TargetLowering::C_Register)
Dale Johannesen8e3455b2008-09-24 23:13:09 +00004800 GetRegistersForValue(OpInfo, OutputRegs, InputRegs);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004801 }
4802 ConstraintInfos.clear();
4803
4804
4805 // Second pass - Loop over all of the operands, assigning virtual or physregs
Chris Lattner58f15c42008-10-17 16:21:11 +00004806 // to register class operands.
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004807 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
4808 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
4809
4810 // C_Register operands have already been allocated, Other/Memory don't need
4811 // to be.
4812 if (OpInfo.ConstraintType == TargetLowering::C_RegisterClass)
Dale Johannesen8e3455b2008-09-24 23:13:09 +00004813 GetRegistersForValue(OpInfo, OutputRegs, InputRegs);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004814 }
4815
4816 // AsmNodeOperands - The operands for the ISD::INLINEASM node.
4817 std::vector<SDValue> AsmNodeOperands;
4818 AsmNodeOperands.push_back(SDValue()); // reserve space for input chain
4819 AsmNodeOperands.push_back(
Bill Wendling056292f2008-09-16 21:48:12 +00004820 DAG.getTargetExternalSymbol(IA->getAsmString().c_str(), MVT::Other));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004821
4822
4823 // Loop over all of the inputs, copying the operand values into the
4824 // appropriate registers and processing the output regs.
4825 RegsForValue RetValRegs;
4826
4827 // IndirectStoresToEmit - The set of stores to emit after the inline asm node.
4828 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
4829
4830 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
4831 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
4832
4833 switch (OpInfo.Type) {
4834 case InlineAsm::isOutput: {
4835 if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass &&
4836 OpInfo.ConstraintType != TargetLowering::C_Register) {
4837 // Memory output, or 'other' output (e.g. 'X' constraint).
4838 assert(OpInfo.isIndirect && "Memory output must be indirect operand");
4839
4840 // Add information to the INLINEASM node to know about this output.
Dale Johannesen86b49f82008-09-24 01:07:17 +00004841 unsigned ResOpType = 4/*MEM*/ | (1<<3);
4842 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004843 TLI.getPointerTy()));
4844 AsmNodeOperands.push_back(OpInfo.CallOperand);
4845 break;
4846 }
4847
4848 // Otherwise, this is a register or register class output.
4849
4850 // Copy the output from the appropriate register. Find a register that
4851 // we can use.
4852 if (OpInfo.AssignedRegs.Regs.empty()) {
4853 cerr << "Couldn't allocate output reg for constraint '"
4854 << OpInfo.ConstraintCode << "'!\n";
4855 exit(1);
4856 }
4857
4858 // If this is an indirect operand, store through the pointer after the
4859 // asm.
4860 if (OpInfo.isIndirect) {
4861 IndirectStoresToEmit.push_back(std::make_pair(OpInfo.AssignedRegs,
4862 OpInfo.CallOperandVal));
4863 } else {
4864 // This is the result value of the call.
4865 assert(CS.getType() != Type::VoidTy && "Bad inline asm!");
4866 // Concatenate this output onto the outputs list.
4867 RetValRegs.append(OpInfo.AssignedRegs);
4868 }
4869
4870 // Add information to the INLINEASM node to know that this register is
4871 // set.
Dale Johannesen913d3df2008-09-12 17:49:03 +00004872 OpInfo.AssignedRegs.AddInlineAsmOperands(OpInfo.isEarlyClobber ?
4873 6 /* EARLYCLOBBER REGDEF */ :
4874 2 /* REGDEF */ ,
4875 DAG, AsmNodeOperands);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004876 break;
4877 }
4878 case InlineAsm::isInput: {
4879 SDValue InOperandVal = OpInfo.CallOperand;
4880
Chris Lattner6bdcda32008-10-17 16:47:46 +00004881 if (OpInfo.isMatchingInputConstraint()) { // Matching constraint?
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004882 // If this is required to match an output register we have already set,
4883 // just use its register.
Chris Lattner58f15c42008-10-17 16:21:11 +00004884 unsigned OperandNo = OpInfo.getMatchedOperand();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004885
4886 // Scan until we find the definition we already emitted of this operand.
4887 // When we find it, create a RegsForValue operand.
4888 unsigned CurOp = 2; // The first operand.
4889 for (; OperandNo; --OperandNo) {
4890 // Advance to the next operand.
4891 unsigned NumOps =
Dan Gohmanf5aeb1a2008-09-12 16:56:44 +00004892 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004893 assert(((NumOps & 7) == 2 /*REGDEF*/ ||
Dale Johannesen913d3df2008-09-12 17:49:03 +00004894 (NumOps & 7) == 6 /*EARLYCLOBBER REGDEF*/ ||
Dale Johannesen86b49f82008-09-24 01:07:17 +00004895 (NumOps & 7) == 4 /*MEM*/) &&
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004896 "Skipped past definitions?");
4897 CurOp += (NumOps>>3)+1;
4898 }
4899
4900 unsigned NumOps =
Dan Gohmanf5aeb1a2008-09-12 16:56:44 +00004901 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
Dale Johannesen913d3df2008-09-12 17:49:03 +00004902 if ((NumOps & 7) == 2 /*REGDEF*/
4903 || (NumOps & 7) == 6 /* EARLYCLOBBER REGDEF */) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004904 // Add NumOps>>3 registers to MatchedRegs.
4905 RegsForValue MatchedRegs;
4906 MatchedRegs.TLI = &TLI;
4907 MatchedRegs.ValueVTs.push_back(InOperandVal.getValueType());
4908 MatchedRegs.RegVTs.push_back(AsmNodeOperands[CurOp+1].getValueType());
4909 for (unsigned i = 0, e = NumOps>>3; i != e; ++i) {
4910 unsigned Reg =
4911 cast<RegisterSDNode>(AsmNodeOperands[++CurOp])->getReg();
4912 MatchedRegs.Regs.push_back(Reg);
4913 }
4914
4915 // Use the produced MatchedRegs object to
4916 MatchedRegs.getCopyToRegs(InOperandVal, DAG, Chain, &Flag);
Dale Johannesen86b49f82008-09-24 01:07:17 +00004917 MatchedRegs.AddInlineAsmOperands(1 /*REGUSE*/, DAG, AsmNodeOperands);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004918 break;
4919 } else {
Dale Johannesen86b49f82008-09-24 01:07:17 +00004920 assert(((NumOps & 7) == 4) && "Unknown matching constraint!");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004921 assert((NumOps >> 3) == 1 && "Unexpected number of operands");
4922 // Add information to the INLINEASM node to know about this input.
Dale Johannesen91aac102008-09-17 21:13:11 +00004923 AsmNodeOperands.push_back(DAG.getTargetConstant(NumOps,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004924 TLI.getPointerTy()));
4925 AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
4926 break;
4927 }
4928 }
4929
4930 if (OpInfo.ConstraintType == TargetLowering::C_Other) {
4931 assert(!OpInfo.isIndirect &&
4932 "Don't know how to handle indirect other inputs yet!");
4933
4934 std::vector<SDValue> Ops;
4935 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode[0],
Evan Chengda43bcf2008-09-24 00:05:32 +00004936 hasMemory, Ops, DAG);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004937 if (Ops.empty()) {
4938 cerr << "Invalid operand for inline asm constraint '"
4939 << OpInfo.ConstraintCode << "'!\n";
4940 exit(1);
4941 }
4942
4943 // Add information to the INLINEASM node to know about this input.
4944 unsigned ResOpType = 3 /*IMM*/ | (Ops.size() << 3);
4945 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
4946 TLI.getPointerTy()));
4947 AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end());
4948 break;
4949 } else if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
4950 assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
4951 assert(InOperandVal.getValueType() == TLI.getPointerTy() &&
4952 "Memory operands expect pointer values");
4953
4954 // Add information to the INLINEASM node to know about this input.
Dale Johannesen86b49f82008-09-24 01:07:17 +00004955 unsigned ResOpType = 4/*MEM*/ | (1<<3);
4956 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004957 TLI.getPointerTy()));
4958 AsmNodeOperands.push_back(InOperandVal);
4959 break;
4960 }
4961
4962 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
4963 OpInfo.ConstraintType == TargetLowering::C_Register) &&
4964 "Unknown constraint type!");
4965 assert(!OpInfo.isIndirect &&
4966 "Don't know how to handle indirect register inputs yet!");
4967
4968 // Copy the input into the appropriate registers.
Evan Chengaa765b82008-09-25 00:14:04 +00004969 if (OpInfo.AssignedRegs.Regs.empty()) {
4970 cerr << "Couldn't allocate output reg for constraint '"
4971 << OpInfo.ConstraintCode << "'!\n";
4972 exit(1);
4973 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004974
4975 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, Chain, &Flag);
4976
Dale Johannesen86b49f82008-09-24 01:07:17 +00004977 OpInfo.AssignedRegs.AddInlineAsmOperands(1/*REGUSE*/,
4978 DAG, AsmNodeOperands);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004979 break;
4980 }
4981 case InlineAsm::isClobber: {
4982 // Add the clobbered value to the operand list, so that the register
4983 // allocator is aware that the physreg got clobbered.
4984 if (!OpInfo.AssignedRegs.Regs.empty())
Dale Johannesen91aac102008-09-17 21:13:11 +00004985 OpInfo.AssignedRegs.AddInlineAsmOperands(6 /* EARLYCLOBBER REGDEF */,
4986 DAG, AsmNodeOperands);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004987 break;
4988 }
4989 }
4990 }
4991
4992 // Finish up input operands.
4993 AsmNodeOperands[0] = Chain;
4994 if (Flag.getNode()) AsmNodeOperands.push_back(Flag);
4995
4996 Chain = DAG.getNode(ISD::INLINEASM,
4997 DAG.getNodeValueTypes(MVT::Other, MVT::Flag), 2,
4998 &AsmNodeOperands[0], AsmNodeOperands.size());
4999 Flag = Chain.getValue(1);
5000
5001 // If this asm returns a register value, copy the result from that register
5002 // and set it as the value of the call.
5003 if (!RetValRegs.Regs.empty()) {
5004 SDValue Val = RetValRegs.getCopyFromRegs(DAG, Chain, &Flag);
5005
5006 // If any of the results of the inline asm is a vector, it may have the
5007 // wrong width/num elts. This can happen for register classes that can
5008 // contain multiple different value types. The preg or vreg allocated may
5009 // not have the same VT as was expected. Convert it to the right type with
5010 // bit_convert.
5011 if (const StructType *ResSTy = dyn_cast<StructType>(CS.getType())) {
5012 for (unsigned i = 0, e = ResSTy->getNumElements(); i != e; ++i) {
5013 if (Val.getNode()->getValueType(i).isVector())
5014 Val = DAG.getNode(ISD::BIT_CONVERT,
5015 TLI.getValueType(ResSTy->getElementType(i)), Val);
5016 }
5017 } else {
5018 if (Val.getValueType().isVector())
5019 Val = DAG.getNode(ISD::BIT_CONVERT, TLI.getValueType(CS.getType()),
5020 Val);
5021 }
5022
5023 setValue(CS.getInstruction(), Val);
5024 }
5025
5026 std::vector<std::pair<SDValue, Value*> > StoresToEmit;
5027
5028 // Process indirect outputs, first output all of the flagged copies out of
5029 // physregs.
5030 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
5031 RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
5032 Value *Ptr = IndirectStoresToEmit[i].second;
5033 SDValue OutVal = OutRegs.getCopyFromRegs(DAG, Chain, &Flag);
5034 StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
5035 }
5036
5037 // Emit the non-flagged stores from the physregs.
5038 SmallVector<SDValue, 8> OutChains;
5039 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i)
5040 OutChains.push_back(DAG.getStore(Chain, StoresToEmit[i].first,
5041 getValue(StoresToEmit[i].second),
5042 StoresToEmit[i].second, 0));
5043 if (!OutChains.empty())
5044 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
5045 &OutChains[0], OutChains.size());
5046 DAG.setRoot(Chain);
5047}
5048
5049
5050void SelectionDAGLowering::visitMalloc(MallocInst &I) {
5051 SDValue Src = getValue(I.getOperand(0));
5052
5053 MVT IntPtr = TLI.getPointerTy();
5054
5055 if (IntPtr.bitsLT(Src.getValueType()))
5056 Src = DAG.getNode(ISD::TRUNCATE, IntPtr, Src);
5057 else if (IntPtr.bitsGT(Src.getValueType()))
5058 Src = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, Src);
5059
5060 // Scale the source by the type size.
5061 uint64_t ElementSize = TD->getABITypeSize(I.getType()->getElementType());
5062 Src = DAG.getNode(ISD::MUL, Src.getValueType(),
5063 Src, DAG.getIntPtrConstant(ElementSize));
5064
5065 TargetLowering::ArgListTy Args;
5066 TargetLowering::ArgListEntry Entry;
5067 Entry.Node = Src;
5068 Entry.Ty = TLI.getTargetData()->getIntPtrType();
5069 Args.push_back(Entry);
5070
5071 std::pair<SDValue,SDValue> Result =
Dale Johannesen86098bd2008-09-26 19:31:26 +00005072 TLI.LowerCallTo(getRoot(), I.getType(), false, false, false, false,
5073 CallingConv::C, PerformTailCallOpt,
5074 DAG.getExternalSymbol("malloc", IntPtr),
Dan Gohman1937e2f2008-09-16 01:42:28 +00005075 Args, DAG);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005076 setValue(&I, Result.first); // Pointers always fit in registers
5077 DAG.setRoot(Result.second);
5078}
5079
5080void SelectionDAGLowering::visitFree(FreeInst &I) {
5081 TargetLowering::ArgListTy Args;
5082 TargetLowering::ArgListEntry Entry;
5083 Entry.Node = getValue(I.getOperand(0));
5084 Entry.Ty = TLI.getTargetData()->getIntPtrType();
5085 Args.push_back(Entry);
5086 MVT IntPtr = TLI.getPointerTy();
5087 std::pair<SDValue,SDValue> Result =
Dale Johannesen86098bd2008-09-26 19:31:26 +00005088 TLI.LowerCallTo(getRoot(), Type::VoidTy, false, false, false, false,
Dan Gohman1937e2f2008-09-16 01:42:28 +00005089 CallingConv::C, PerformTailCallOpt,
Bill Wendling056292f2008-09-16 21:48:12 +00005090 DAG.getExternalSymbol("free", IntPtr), Args, DAG);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005091 DAG.setRoot(Result.second);
5092}
5093
5094void SelectionDAGLowering::visitVAStart(CallInst &I) {
5095 DAG.setRoot(DAG.getNode(ISD::VASTART, MVT::Other, getRoot(),
5096 getValue(I.getOperand(1)),
5097 DAG.getSrcValue(I.getOperand(1))));
5098}
5099
5100void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
5101 SDValue V = DAG.getVAArg(TLI.getValueType(I.getType()), getRoot(),
5102 getValue(I.getOperand(0)),
5103 DAG.getSrcValue(I.getOperand(0)));
5104 setValue(&I, V);
5105 DAG.setRoot(V.getValue(1));
5106}
5107
5108void SelectionDAGLowering::visitVAEnd(CallInst &I) {
5109 DAG.setRoot(DAG.getNode(ISD::VAEND, MVT::Other, getRoot(),
5110 getValue(I.getOperand(1)),
5111 DAG.getSrcValue(I.getOperand(1))));
5112}
5113
5114void SelectionDAGLowering::visitVACopy(CallInst &I) {
5115 DAG.setRoot(DAG.getNode(ISD::VACOPY, MVT::Other, getRoot(),
5116 getValue(I.getOperand(1)),
5117 getValue(I.getOperand(2)),
5118 DAG.getSrcValue(I.getOperand(1)),
5119 DAG.getSrcValue(I.getOperand(2))));
5120}
5121
5122/// TargetLowering::LowerArguments - This is the default LowerArguments
5123/// implementation, which just inserts a FORMAL_ARGUMENTS node. FIXME: When all
5124/// targets are migrated to using FORMAL_ARGUMENTS, this hook should be
5125/// integrated into SDISel.
5126void TargetLowering::LowerArguments(Function &F, SelectionDAG &DAG,
5127 SmallVectorImpl<SDValue> &ArgValues) {
5128 // Add CC# and isVararg as operands to the FORMAL_ARGUMENTS node.
5129 SmallVector<SDValue, 3+16> Ops;
5130 Ops.push_back(DAG.getRoot());
5131 Ops.push_back(DAG.getConstant(F.getCallingConv(), getPointerTy()));
5132 Ops.push_back(DAG.getConstant(F.isVarArg(), getPointerTy()));
5133
5134 // Add one result value for each formal argument.
5135 SmallVector<MVT, 16> RetVals;
5136 unsigned j = 1;
5137 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end();
5138 I != E; ++I, ++j) {
5139 SmallVector<MVT, 4> ValueVTs;
5140 ComputeValueVTs(*this, I->getType(), ValueVTs);
5141 for (unsigned Value = 0, NumValues = ValueVTs.size();
5142 Value != NumValues; ++Value) {
5143 MVT VT = ValueVTs[Value];
5144 const Type *ArgTy = VT.getTypeForMVT();
5145 ISD::ArgFlagsTy Flags;
5146 unsigned OriginalAlignment =
5147 getTargetData()->getABITypeAlignment(ArgTy);
5148
Devang Patel05988662008-09-25 21:00:45 +00005149 if (F.paramHasAttr(j, Attribute::ZExt))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005150 Flags.setZExt();
Devang Patel05988662008-09-25 21:00:45 +00005151 if (F.paramHasAttr(j, Attribute::SExt))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005152 Flags.setSExt();
Devang Patel05988662008-09-25 21:00:45 +00005153 if (F.paramHasAttr(j, Attribute::InReg))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005154 Flags.setInReg();
Devang Patel05988662008-09-25 21:00:45 +00005155 if (F.paramHasAttr(j, Attribute::StructRet))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005156 Flags.setSRet();
Devang Patel05988662008-09-25 21:00:45 +00005157 if (F.paramHasAttr(j, Attribute::ByVal)) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005158 Flags.setByVal();
5159 const PointerType *Ty = cast<PointerType>(I->getType());
5160 const Type *ElementTy = Ty->getElementType();
5161 unsigned FrameAlign = getByValTypeAlignment(ElementTy);
5162 unsigned FrameSize = getTargetData()->getABITypeSize(ElementTy);
5163 // For ByVal, alignment should be passed from FE. BE will guess if
5164 // this info is not there but there are cases it cannot get right.
5165 if (F.getParamAlignment(j))
5166 FrameAlign = F.getParamAlignment(j);
5167 Flags.setByValAlign(FrameAlign);
5168 Flags.setByValSize(FrameSize);
5169 }
Devang Patel05988662008-09-25 21:00:45 +00005170 if (F.paramHasAttr(j, Attribute::Nest))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005171 Flags.setNest();
5172 Flags.setOrigAlign(OriginalAlignment);
5173
5174 MVT RegisterVT = getRegisterType(VT);
5175 unsigned NumRegs = getNumRegisters(VT);
5176 for (unsigned i = 0; i != NumRegs; ++i) {
5177 RetVals.push_back(RegisterVT);
5178 ISD::ArgFlagsTy MyFlags = Flags;
5179 if (NumRegs > 1 && i == 0)
5180 MyFlags.setSplit();
5181 // if it isn't first piece, alignment must be 1
5182 else if (i > 0)
5183 MyFlags.setOrigAlign(1);
5184 Ops.push_back(DAG.getArgFlags(MyFlags));
5185 }
5186 }
5187 }
5188
5189 RetVals.push_back(MVT::Other);
5190
5191 // Create the node.
5192 SDNode *Result = DAG.getNode(ISD::FORMAL_ARGUMENTS,
5193 DAG.getVTList(&RetVals[0], RetVals.size()),
5194 &Ops[0], Ops.size()).getNode();
5195
5196 // Prelower FORMAL_ARGUMENTS. This isn't required for functionality, but
5197 // allows exposing the loads that may be part of the argument access to the
5198 // first DAGCombiner pass.
5199 SDValue TmpRes = LowerOperation(SDValue(Result, 0), DAG);
5200
5201 // The number of results should match up, except that the lowered one may have
5202 // an extra flag result.
5203 assert((Result->getNumValues() == TmpRes.getNode()->getNumValues() ||
5204 (Result->getNumValues()+1 == TmpRes.getNode()->getNumValues() &&
5205 TmpRes.getValue(Result->getNumValues()).getValueType() == MVT::Flag))
5206 && "Lowering produced unexpected number of results!");
5207
5208 // The FORMAL_ARGUMENTS node itself is likely no longer needed.
5209 if (Result != TmpRes.getNode() && Result->use_empty()) {
5210 HandleSDNode Dummy(DAG.getRoot());
5211 DAG.RemoveDeadNode(Result);
5212 }
5213
5214 Result = TmpRes.getNode();
5215
5216 unsigned NumArgRegs = Result->getNumValues() - 1;
5217 DAG.setRoot(SDValue(Result, NumArgRegs));
5218
5219 // Set up the return result vector.
5220 unsigned i = 0;
5221 unsigned Idx = 1;
5222 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E;
5223 ++I, ++Idx) {
5224 SmallVector<MVT, 4> ValueVTs;
5225 ComputeValueVTs(*this, I->getType(), ValueVTs);
5226 for (unsigned Value = 0, NumValues = ValueVTs.size();
5227 Value != NumValues; ++Value) {
5228 MVT VT = ValueVTs[Value];
5229 MVT PartVT = getRegisterType(VT);
5230
5231 unsigned NumParts = getNumRegisters(VT);
5232 SmallVector<SDValue, 4> Parts(NumParts);
5233 for (unsigned j = 0; j != NumParts; ++j)
5234 Parts[j] = SDValue(Result, i++);
5235
5236 ISD::NodeType AssertOp = ISD::DELETED_NODE;
Devang Patel05988662008-09-25 21:00:45 +00005237 if (F.paramHasAttr(Idx, Attribute::SExt))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005238 AssertOp = ISD::AssertSext;
Devang Patel05988662008-09-25 21:00:45 +00005239 else if (F.paramHasAttr(Idx, Attribute::ZExt))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005240 AssertOp = ISD::AssertZext;
5241
5242 ArgValues.push_back(getCopyFromParts(DAG, &Parts[0], NumParts, PartVT, VT,
5243 AssertOp));
5244 }
5245 }
5246 assert(i == NumArgRegs && "Argument register count mismatch!");
5247}
5248
5249
5250/// TargetLowering::LowerCallTo - This is the default LowerCallTo
5251/// implementation, which just inserts an ISD::CALL node, which is later custom
5252/// lowered by the target to something concrete. FIXME: When all targets are
5253/// migrated to using ISD::CALL, this hook should be integrated into SDISel.
5254std::pair<SDValue, SDValue>
5255TargetLowering::LowerCallTo(SDValue Chain, const Type *RetTy,
5256 bool RetSExt, bool RetZExt, bool isVarArg,
Dale Johannesen86098bd2008-09-26 19:31:26 +00005257 bool isInreg,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005258 unsigned CallingConv, bool isTailCall,
5259 SDValue Callee,
5260 ArgListTy &Args, SelectionDAG &DAG) {
Dan Gohman1937e2f2008-09-16 01:42:28 +00005261 assert((!isTailCall || PerformTailCallOpt) &&
5262 "isTailCall set when tail-call optimizations are disabled!");
5263
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005264 SmallVector<SDValue, 32> Ops;
5265 Ops.push_back(Chain); // Op#0 - Chain
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005266 Ops.push_back(Callee);
5267
5268 // Handle all of the outgoing arguments.
5269 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
5270 SmallVector<MVT, 4> ValueVTs;
5271 ComputeValueVTs(*this, Args[i].Ty, ValueVTs);
5272 for (unsigned Value = 0, NumValues = ValueVTs.size();
5273 Value != NumValues; ++Value) {
5274 MVT VT = ValueVTs[Value];
5275 const Type *ArgTy = VT.getTypeForMVT();
5276 SDValue Op = SDValue(Args[i].Node.getNode(), Args[i].Node.getResNo() + Value);
5277 ISD::ArgFlagsTy Flags;
5278 unsigned OriginalAlignment =
5279 getTargetData()->getABITypeAlignment(ArgTy);
5280
5281 if (Args[i].isZExt)
5282 Flags.setZExt();
5283 if (Args[i].isSExt)
5284 Flags.setSExt();
5285 if (Args[i].isInReg)
5286 Flags.setInReg();
5287 if (Args[i].isSRet)
5288 Flags.setSRet();
5289 if (Args[i].isByVal) {
5290 Flags.setByVal();
5291 const PointerType *Ty = cast<PointerType>(Args[i].Ty);
5292 const Type *ElementTy = Ty->getElementType();
5293 unsigned FrameAlign = getByValTypeAlignment(ElementTy);
5294 unsigned FrameSize = getTargetData()->getABITypeSize(ElementTy);
5295 // For ByVal, alignment should come from FE. BE will guess if this
5296 // info is not there but there are cases it cannot get right.
5297 if (Args[i].Alignment)
5298 FrameAlign = Args[i].Alignment;
5299 Flags.setByValAlign(FrameAlign);
5300 Flags.setByValSize(FrameSize);
5301 }
5302 if (Args[i].isNest)
5303 Flags.setNest();
5304 Flags.setOrigAlign(OriginalAlignment);
5305
5306 MVT PartVT = getRegisterType(VT);
5307 unsigned NumParts = getNumRegisters(VT);
5308 SmallVector<SDValue, 4> Parts(NumParts);
5309 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
5310
5311 if (Args[i].isSExt)
5312 ExtendKind = ISD::SIGN_EXTEND;
5313 else if (Args[i].isZExt)
5314 ExtendKind = ISD::ZERO_EXTEND;
5315
5316 getCopyToParts(DAG, Op, &Parts[0], NumParts, PartVT, ExtendKind);
5317
5318 for (unsigned i = 0; i != NumParts; ++i) {
5319 // if it isn't first piece, alignment must be 1
5320 ISD::ArgFlagsTy MyFlags = Flags;
5321 if (NumParts > 1 && i == 0)
5322 MyFlags.setSplit();
5323 else if (i != 0)
5324 MyFlags.setOrigAlign(1);
5325
5326 Ops.push_back(Parts[i]);
5327 Ops.push_back(DAG.getArgFlags(MyFlags));
5328 }
5329 }
5330 }
5331
5332 // Figure out the result value types. We start by making a list of
5333 // the potentially illegal return value types.
5334 SmallVector<MVT, 4> LoweredRetTys;
5335 SmallVector<MVT, 4> RetTys;
5336 ComputeValueVTs(*this, RetTy, RetTys);
5337
5338 // Then we translate that to a list of legal types.
5339 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
5340 MVT VT = RetTys[I];
5341 MVT RegisterVT = getRegisterType(VT);
5342 unsigned NumRegs = getNumRegisters(VT);
5343 for (unsigned i = 0; i != NumRegs; ++i)
5344 LoweredRetTys.push_back(RegisterVT);
5345 }
5346
5347 LoweredRetTys.push_back(MVT::Other); // Always has a chain.
5348
5349 // Create the CALL node.
Dale Johannesen86098bd2008-09-26 19:31:26 +00005350 SDValue Res = DAG.getCall(CallingConv, isVarArg, isTailCall, isInreg,
Dan Gohman095cc292008-09-13 01:54:27 +00005351 DAG.getVTList(&LoweredRetTys[0],
5352 LoweredRetTys.size()),
Dale Johannesen86098bd2008-09-26 19:31:26 +00005353 &Ops[0], Ops.size()
5354 );
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005355 Chain = Res.getValue(LoweredRetTys.size() - 1);
5356
5357 // Gather up the call result into a single value.
Dan Gohmanb5cc34d2008-10-07 00:12:37 +00005358 if (RetTy != Type::VoidTy && !RetTys.empty()) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005359 ISD::NodeType AssertOp = ISD::DELETED_NODE;
5360
5361 if (RetSExt)
5362 AssertOp = ISD::AssertSext;
5363 else if (RetZExt)
5364 AssertOp = ISD::AssertZext;
5365
5366 SmallVector<SDValue, 4> ReturnValues;
5367 unsigned RegNo = 0;
5368 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
5369 MVT VT = RetTys[I];
5370 MVT RegisterVT = getRegisterType(VT);
5371 unsigned NumRegs = getNumRegisters(VT);
5372 unsigned RegNoEnd = NumRegs + RegNo;
5373 SmallVector<SDValue, 4> Results;
5374 for (; RegNo != RegNoEnd; ++RegNo)
5375 Results.push_back(Res.getValue(RegNo));
5376 SDValue ReturnValue =
5377 getCopyFromParts(DAG, &Results[0], NumRegs, RegisterVT, VT,
5378 AssertOp);
5379 ReturnValues.push_back(ReturnValue);
5380 }
5381 Res = DAG.getMergeValues(DAG.getVTList(&RetTys[0], RetTys.size()),
5382 &ReturnValues[0], ReturnValues.size());
5383 }
5384
5385 return std::make_pair(Res, Chain);
5386}
5387
5388SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) {
5389 assert(0 && "LowerOperation not implemented for this target!");
5390 abort();
5391 return SDValue();
5392}
5393
5394
5395void SelectionDAGLowering::CopyValueToVirtualRegister(Value *V, unsigned Reg) {
5396 SDValue Op = getValue(V);
5397 assert((Op.getOpcode() != ISD::CopyFromReg ||
5398 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
5399 "Copy from a reg to the same reg!");
5400 assert(!TargetRegisterInfo::isPhysicalRegister(Reg) && "Is a physreg");
5401
5402 RegsForValue RFV(TLI, Reg, V->getType());
5403 SDValue Chain = DAG.getEntryNode();
5404 RFV.getCopyToRegs(Op, DAG, Chain, 0);
5405 PendingExports.push_back(Chain);
5406}
5407
5408#include "llvm/CodeGen/SelectionDAGISel.h"
5409
5410void SelectionDAGISel::
5411LowerArguments(BasicBlock *LLVMBB) {
5412 // If this is the entry block, emit arguments.
5413 Function &F = *LLVMBB->getParent();
5414 SDValue OldRoot = SDL->DAG.getRoot();
5415 SmallVector<SDValue, 16> Args;
5416 TLI.LowerArguments(F, SDL->DAG, Args);
5417
5418 unsigned a = 0;
5419 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
5420 AI != E; ++AI) {
5421 SmallVector<MVT, 4> ValueVTs;
5422 ComputeValueVTs(TLI, AI->getType(), ValueVTs);
5423 unsigned NumValues = ValueVTs.size();
5424 if (!AI->use_empty()) {
5425 SDL->setValue(AI, SDL->DAG.getMergeValues(&Args[a], NumValues));
5426 // If this argument is live outside of the entry block, insert a copy from
5427 // whereever we got it to the vreg that other BB's will reference it as.
5428 DenseMap<const Value*, unsigned>::iterator VMI=FuncInfo->ValueMap.find(AI);
5429 if (VMI != FuncInfo->ValueMap.end()) {
5430 SDL->CopyValueToVirtualRegister(AI, VMI->second);
5431 }
5432 }
5433 a += NumValues;
5434 }
5435
5436 // Finally, if the target has anything special to do, allow it to do so.
5437 // FIXME: this should insert code into the DAG!
5438 EmitFunctionEntryCode(F, SDL->DAG.getMachineFunction());
5439}
5440
5441/// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
5442/// ensure constants are generated when needed. Remember the virtual registers
5443/// that need to be added to the Machine PHI nodes as input. We cannot just
5444/// directly add them, because expansion might result in multiple MBB's for one
5445/// BB. As such, the start of the BB might correspond to a different MBB than
5446/// the end.
5447///
5448void
5449SelectionDAGISel::HandlePHINodesInSuccessorBlocks(BasicBlock *LLVMBB) {
5450 TerminatorInst *TI = LLVMBB->getTerminator();
5451
5452 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
5453
5454 // Check successor nodes' PHI nodes that expect a constant to be available
5455 // from this block.
5456 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
5457 BasicBlock *SuccBB = TI->getSuccessor(succ);
5458 if (!isa<PHINode>(SuccBB->begin())) continue;
5459 MachineBasicBlock *SuccMBB = FuncInfo->MBBMap[SuccBB];
5460
5461 // If this terminator has multiple identical successors (common for
5462 // switches), only handle each succ once.
5463 if (!SuccsHandled.insert(SuccMBB)) continue;
5464
5465 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
5466 PHINode *PN;
5467
5468 // At this point we know that there is a 1-1 correspondence between LLVM PHI
5469 // nodes and Machine PHI nodes, but the incoming operands have not been
5470 // emitted yet.
5471 for (BasicBlock::iterator I = SuccBB->begin();
5472 (PN = dyn_cast<PHINode>(I)); ++I) {
5473 // Ignore dead phi's.
5474 if (PN->use_empty()) continue;
5475
5476 unsigned Reg;
5477 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
5478
5479 if (Constant *C = dyn_cast<Constant>(PHIOp)) {
5480 unsigned &RegOut = SDL->ConstantsOut[C];
5481 if (RegOut == 0) {
5482 RegOut = FuncInfo->CreateRegForValue(C);
5483 SDL->CopyValueToVirtualRegister(C, RegOut);
5484 }
5485 Reg = RegOut;
5486 } else {
5487 Reg = FuncInfo->ValueMap[PHIOp];
5488 if (Reg == 0) {
5489 assert(isa<AllocaInst>(PHIOp) &&
5490 FuncInfo->StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
5491 "Didn't codegen value into a register!??");
5492 Reg = FuncInfo->CreateRegForValue(PHIOp);
5493 SDL->CopyValueToVirtualRegister(PHIOp, Reg);
5494 }
5495 }
5496
5497 // Remember that this register needs to added to the machine PHI node as
5498 // the input for this MBB.
5499 SmallVector<MVT, 4> ValueVTs;
5500 ComputeValueVTs(TLI, PN->getType(), ValueVTs);
5501 for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
5502 MVT VT = ValueVTs[vti];
5503 unsigned NumRegisters = TLI.getNumRegisters(VT);
5504 for (unsigned i = 0, e = NumRegisters; i != e; ++i)
5505 SDL->PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
5506 Reg += NumRegisters;
5507 }
5508 }
5509 }
5510 SDL->ConstantsOut.clear();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005511}
5512
Dan Gohman3df24e62008-09-03 23:12:08 +00005513/// This is the Fast-ISel version of HandlePHINodesInSuccessorBlocks. It only
5514/// supports legal types, and it emits MachineInstrs directly instead of
5515/// creating SelectionDAG nodes.
5516///
5517bool
5518SelectionDAGISel::HandlePHINodesInSuccessorBlocksFast(BasicBlock *LLVMBB,
5519 FastISel *F) {
5520 TerminatorInst *TI = LLVMBB->getTerminator();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005521
Dan Gohman3df24e62008-09-03 23:12:08 +00005522 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
5523 unsigned OrigNumPHINodesToUpdate = SDL->PHINodesToUpdate.size();
5524
5525 // Check successor nodes' PHI nodes that expect a constant to be available
5526 // from this block.
5527 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
5528 BasicBlock *SuccBB = TI->getSuccessor(succ);
5529 if (!isa<PHINode>(SuccBB->begin())) continue;
5530 MachineBasicBlock *SuccMBB = FuncInfo->MBBMap[SuccBB];
5531
5532 // If this terminator has multiple identical successors (common for
5533 // switches), only handle each succ once.
5534 if (!SuccsHandled.insert(SuccMBB)) continue;
5535
5536 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
5537 PHINode *PN;
5538
5539 // At this point we know that there is a 1-1 correspondence between LLVM PHI
5540 // nodes and Machine PHI nodes, but the incoming operands have not been
5541 // emitted yet.
5542 for (BasicBlock::iterator I = SuccBB->begin();
5543 (PN = dyn_cast<PHINode>(I)); ++I) {
5544 // Ignore dead phi's.
5545 if (PN->use_empty()) continue;
5546
5547 // Only handle legal types. Two interesting things to note here. First,
5548 // by bailing out early, we may leave behind some dead instructions,
5549 // since SelectionDAG's HandlePHINodesInSuccessorBlocks will insert its
5550 // own moves. Second, this check is necessary becuase FastISel doesn't
5551 // use CreateRegForValue to create registers, so it always creates
5552 // exactly one register for each non-void instruction.
5553 MVT VT = TLI.getValueType(PN->getType(), /*AllowUnknown=*/true);
5554 if (VT == MVT::Other || !TLI.isTypeLegal(VT)) {
Dan Gohman74321ab2008-09-10 21:01:31 +00005555 // Promote MVT::i1.
5556 if (VT == MVT::i1)
5557 VT = TLI.getTypeToTransformTo(VT);
5558 else {
5559 SDL->PHINodesToUpdate.resize(OrigNumPHINodesToUpdate);
5560 return false;
5561 }
Dan Gohman3df24e62008-09-03 23:12:08 +00005562 }
5563
5564 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
5565
5566 unsigned Reg = F->getRegForValue(PHIOp);
5567 if (Reg == 0) {
5568 SDL->PHINodesToUpdate.resize(OrigNumPHINodesToUpdate);
5569 return false;
5570 }
5571 SDL->PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg));
5572 }
5573 }
5574
5575 return true;
5576}