blob: ed9edf1067248f402021bc652e4e76c40baaa318 [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.
Chris Lattner01426e12008-10-21 00:45:36 +0000515static void getCopyToParts(SelectionDAG &DAG, SDValue Val,
516 SDValue *Parts, unsigned NumParts, MVT PartVT,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000517 ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
518 TargetLowering &TLI = DAG.getTargetLoweringInfo();
519 MVT PtrVT = TLI.getPointerTy();
520 MVT ValueVT = Val.getValueType();
521 unsigned PartBits = PartVT.getSizeInBits();
522 assert(TLI.isTypeLegal(PartVT) && "Copying to an illegal type!");
523
524 if (!NumParts)
525 return;
526
527 if (!ValueVT.isVector()) {
528 if (PartVT == ValueVT) {
529 assert(NumParts == 1 && "No-op copy with multiple parts!");
530 Parts[0] = Val;
531 return;
532 }
533
534 if (NumParts * PartBits > ValueVT.getSizeInBits()) {
535 // If the parts cover more bits than the value has, promote the value.
536 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
537 assert(NumParts == 1 && "Do not know what to promote to!");
538 Val = DAG.getNode(ISD::FP_EXTEND, PartVT, Val);
539 } else if (PartVT.isInteger() && ValueVT.isInteger()) {
540 ValueVT = MVT::getIntegerVT(NumParts * PartBits);
541 Val = DAG.getNode(ExtendKind, ValueVT, Val);
542 } else {
543 assert(0 && "Unknown mismatch!");
544 }
545 } else if (PartBits == ValueVT.getSizeInBits()) {
546 // Different types of the same size.
547 assert(NumParts == 1 && PartVT != ValueVT);
548 Val = DAG.getNode(ISD::BIT_CONVERT, PartVT, Val);
549 } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
550 // If the parts cover less bits than value has, truncate the value.
551 if (PartVT.isInteger() && ValueVT.isInteger()) {
552 ValueVT = MVT::getIntegerVT(NumParts * PartBits);
553 Val = DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
554 } else {
555 assert(0 && "Unknown mismatch!");
556 }
557 }
558
559 // The value may have changed - recompute ValueVT.
560 ValueVT = Val.getValueType();
561 assert(NumParts * PartBits == ValueVT.getSizeInBits() &&
562 "Failed to tile the value with PartVT!");
563
564 if (NumParts == 1) {
565 assert(PartVT == ValueVT && "Type conversion failed!");
566 Parts[0] = Val;
567 return;
568 }
569
570 // Expand the value into multiple parts.
571 if (NumParts & (NumParts - 1)) {
572 // The number of parts is not a power of 2. Split off and copy the tail.
573 assert(PartVT.isInteger() && ValueVT.isInteger() &&
574 "Do not know what to expand to!");
575 unsigned RoundParts = 1 << Log2_32(NumParts);
576 unsigned RoundBits = RoundParts * PartBits;
577 unsigned OddParts = NumParts - RoundParts;
578 SDValue OddVal = DAG.getNode(ISD::SRL, ValueVT, Val,
579 DAG.getConstant(RoundBits,
580 TLI.getShiftAmountTy()));
581 getCopyToParts(DAG, OddVal, Parts + RoundParts, OddParts, PartVT);
582 if (TLI.isBigEndian())
583 // The odd parts were reversed by getCopyToParts - unreverse them.
584 std::reverse(Parts + RoundParts, Parts + NumParts);
585 NumParts = RoundParts;
586 ValueVT = MVT::getIntegerVT(NumParts * PartBits);
587 Val = DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
588 }
589
590 // The number of parts is a power of 2. Repeatedly bisect the value using
591 // EXTRACT_ELEMENT.
592 Parts[0] = DAG.getNode(ISD::BIT_CONVERT,
593 MVT::getIntegerVT(ValueVT.getSizeInBits()),
594 Val);
595 for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
596 for (unsigned i = 0; i < NumParts; i += StepSize) {
597 unsigned ThisBits = StepSize * PartBits / 2;
598 MVT ThisVT = MVT::getIntegerVT (ThisBits);
599 SDValue &Part0 = Parts[i];
600 SDValue &Part1 = Parts[i+StepSize/2];
601
602 Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, ThisVT, Part0,
603 DAG.getConstant(1, PtrVT));
604 Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, ThisVT, Part0,
605 DAG.getConstant(0, PtrVT));
606
607 if (ThisBits == PartBits && ThisVT != PartVT) {
608 Part0 = DAG.getNode(ISD::BIT_CONVERT, PartVT, Part0);
609 Part1 = DAG.getNode(ISD::BIT_CONVERT, PartVT, Part1);
610 }
611 }
612 }
613
614 if (TLI.isBigEndian())
615 std::reverse(Parts, Parts + NumParts);
616
617 return;
618 }
619
620 // Vector ValueVT.
621 if (NumParts == 1) {
622 if (PartVT != ValueVT) {
623 if (PartVT.isVector()) {
624 Val = DAG.getNode(ISD::BIT_CONVERT, PartVT, Val);
625 } else {
626 assert(ValueVT.getVectorElementType() == PartVT &&
627 ValueVT.getVectorNumElements() == 1 &&
628 "Only trivial vector-to-scalar conversions should get here!");
629 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, PartVT, Val,
630 DAG.getConstant(0, PtrVT));
631 }
632 }
633
634 Parts[0] = Val;
635 return;
636 }
637
638 // Handle a multi-element vector.
639 MVT IntermediateVT, RegisterVT;
640 unsigned NumIntermediates;
641 unsigned NumRegs =
642 DAG.getTargetLoweringInfo()
643 .getVectorTypeBreakdown(ValueVT, IntermediateVT, NumIntermediates,
644 RegisterVT);
645 unsigned NumElements = ValueVT.getVectorNumElements();
646
647 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
648 NumParts = NumRegs; // Silence a compiler warning.
649 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
650
651 // Split the vector into intermediate operands.
652 SmallVector<SDValue, 8> Ops(NumIntermediates);
653 for (unsigned i = 0; i != NumIntermediates; ++i)
654 if (IntermediateVT.isVector())
655 Ops[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR,
656 IntermediateVT, Val,
657 DAG.getConstant(i * (NumElements / NumIntermediates),
658 PtrVT));
659 else
660 Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
661 IntermediateVT, Val,
662 DAG.getConstant(i, PtrVT));
663
664 // Split the intermediate operands into legal parts.
665 if (NumParts == NumIntermediates) {
666 // If the register was not expanded, promote or copy the value,
667 // as appropriate.
668 for (unsigned i = 0; i != NumParts; ++i)
669 getCopyToParts(DAG, Ops[i], &Parts[i], 1, PartVT);
670 } else if (NumParts > 0) {
671 // If the intermediate type was expanded, split each the value into
672 // legal parts.
673 assert(NumParts % NumIntermediates == 0 &&
674 "Must expand into a divisible number of parts!");
675 unsigned Factor = NumParts / NumIntermediates;
676 for (unsigned i = 0; i != NumIntermediates; ++i)
677 getCopyToParts(DAG, Ops[i], &Parts[i * Factor], Factor, PartVT);
678 }
679}
680
681
682void SelectionDAGLowering::init(GCFunctionInfo *gfi, AliasAnalysis &aa) {
683 AA = &aa;
684 GFI = gfi;
685 TD = DAG.getTarget().getTargetData();
686}
687
688/// clear - Clear out the curret SelectionDAG and the associated
689/// state and prepare this SelectionDAGLowering object to be used
690/// for a new block. This doesn't clear out information about
691/// additional blocks that are needed to complete switch lowering
692/// or PHI node updating; that information is cleared out as it is
693/// consumed.
694void SelectionDAGLowering::clear() {
695 NodeMap.clear();
696 PendingLoads.clear();
697 PendingExports.clear();
698 DAG.clear();
699}
700
701/// getRoot - Return the current virtual root of the Selection DAG,
702/// flushing any PendingLoad items. This must be done before emitting
703/// a store or any other node that may need to be ordered after any
704/// prior load instructions.
705///
706SDValue SelectionDAGLowering::getRoot() {
707 if (PendingLoads.empty())
708 return DAG.getRoot();
709
710 if (PendingLoads.size() == 1) {
711 SDValue Root = PendingLoads[0];
712 DAG.setRoot(Root);
713 PendingLoads.clear();
714 return Root;
715 }
716
717 // Otherwise, we have to make a token factor node.
718 SDValue Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
719 &PendingLoads[0], PendingLoads.size());
720 PendingLoads.clear();
721 DAG.setRoot(Root);
722 return Root;
723}
724
725/// getControlRoot - Similar to getRoot, but instead of flushing all the
726/// PendingLoad items, flush all the PendingExports items. It is necessary
727/// to do this before emitting a terminator instruction.
728///
729SDValue SelectionDAGLowering::getControlRoot() {
730 SDValue Root = DAG.getRoot();
731
732 if (PendingExports.empty())
733 return Root;
734
735 // Turn all of the CopyToReg chains into one factored node.
736 if (Root.getOpcode() != ISD::EntryToken) {
737 unsigned i = 0, e = PendingExports.size();
738 for (; i != e; ++i) {
739 assert(PendingExports[i].getNode()->getNumOperands() > 1);
740 if (PendingExports[i].getNode()->getOperand(0) == Root)
741 break; // Don't add the root if we already indirectly depend on it.
742 }
743
744 if (i == e)
745 PendingExports.push_back(Root);
746 }
747
748 Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
749 &PendingExports[0],
750 PendingExports.size());
751 PendingExports.clear();
752 DAG.setRoot(Root);
753 return Root;
754}
755
756void SelectionDAGLowering::visit(Instruction &I) {
757 visit(I.getOpcode(), I);
758}
759
760void SelectionDAGLowering::visit(unsigned Opcode, User &I) {
761 // Note: this doesn't use InstVisitor, because it has to work with
762 // ConstantExpr's in addition to instructions.
763 switch (Opcode) {
764 default: assert(0 && "Unknown instruction type encountered!");
765 abort();
766 // Build the switch statement using the Instruction.def file.
767#define HANDLE_INST(NUM, OPCODE, CLASS) \
768 case Instruction::OPCODE:return visit##OPCODE((CLASS&)I);
769#include "llvm/Instruction.def"
770 }
771}
772
773void SelectionDAGLowering::visitAdd(User &I) {
774 if (I.getType()->isFPOrFPVector())
775 visitBinary(I, ISD::FADD);
776 else
777 visitBinary(I, ISD::ADD);
778}
779
780void SelectionDAGLowering::visitMul(User &I) {
781 if (I.getType()->isFPOrFPVector())
782 visitBinary(I, ISD::FMUL);
783 else
784 visitBinary(I, ISD::MUL);
785}
786
787SDValue SelectionDAGLowering::getValue(const Value *V) {
788 SDValue &N = NodeMap[V];
789 if (N.getNode()) return N;
790
791 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V))) {
792 MVT VT = TLI.getValueType(V->getType(), true);
793
794 if (ConstantInt *CI = dyn_cast<ConstantInt>(C))
Dan Gohman4fbd7962008-09-12 18:08:03 +0000795 return N = DAG.getConstant(*CI, VT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000796
797 if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
798 return N = DAG.getGlobalAddress(GV, VT);
799
800 if (isa<ConstantPointerNull>(C))
801 return N = DAG.getConstant(0, TLI.getPointerTy());
802
803 if (ConstantFP *CFP = dyn_cast<ConstantFP>(C))
Dan Gohman4fbd7962008-09-12 18:08:03 +0000804 return N = DAG.getConstantFP(*CFP, VT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000805
806 if (isa<UndefValue>(C) && !isa<VectorType>(V->getType()) &&
807 !V->getType()->isAggregateType())
808 return N = DAG.getNode(ISD::UNDEF, VT);
809
810 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
811 visit(CE->getOpcode(), *CE);
812 SDValue N1 = NodeMap[V];
813 assert(N1.getNode() && "visit didn't populate the ValueMap!");
814 return N1;
815 }
816
817 if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
818 SmallVector<SDValue, 4> Constants;
819 for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end();
820 OI != OE; ++OI) {
821 SDNode *Val = getValue(*OI).getNode();
822 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
823 Constants.push_back(SDValue(Val, i));
824 }
825 return DAG.getMergeValues(&Constants[0], Constants.size());
826 }
827
828 if (isa<StructType>(C->getType()) || isa<ArrayType>(C->getType())) {
829 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
830 "Unknown struct or array constant!");
831
832 SmallVector<MVT, 4> ValueVTs;
833 ComputeValueVTs(TLI, C->getType(), ValueVTs);
834 unsigned NumElts = ValueVTs.size();
835 if (NumElts == 0)
836 return SDValue(); // empty struct
837 SmallVector<SDValue, 4> Constants(NumElts);
838 for (unsigned i = 0; i != NumElts; ++i) {
839 MVT EltVT = ValueVTs[i];
840 if (isa<UndefValue>(C))
841 Constants[i] = DAG.getNode(ISD::UNDEF, EltVT);
842 else if (EltVT.isFloatingPoint())
843 Constants[i] = DAG.getConstantFP(0, EltVT);
844 else
845 Constants[i] = DAG.getConstant(0, EltVT);
846 }
847 return DAG.getMergeValues(&Constants[0], NumElts);
848 }
849
850 const VectorType *VecTy = cast<VectorType>(V->getType());
851 unsigned NumElements = VecTy->getNumElements();
852
853 // Now that we know the number and type of the elements, get that number of
854 // elements into the Ops array based on what kind of constant it is.
855 SmallVector<SDValue, 16> Ops;
856 if (ConstantVector *CP = dyn_cast<ConstantVector>(C)) {
857 for (unsigned i = 0; i != NumElements; ++i)
858 Ops.push_back(getValue(CP->getOperand(i)));
859 } else {
860 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
861 "Unknown vector constant!");
862 MVT EltVT = TLI.getValueType(VecTy->getElementType());
863
864 SDValue Op;
865 if (isa<UndefValue>(C))
866 Op = DAG.getNode(ISD::UNDEF, EltVT);
867 else if (EltVT.isFloatingPoint())
868 Op = DAG.getConstantFP(0, EltVT);
869 else
870 Op = DAG.getConstant(0, EltVT);
871 Ops.assign(NumElements, Op);
872 }
873
874 // Create a BUILD_VECTOR node.
875 return NodeMap[V] = DAG.getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
876 }
877
878 // If this is a static alloca, generate it as the frameindex instead of
879 // computation.
880 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
881 DenseMap<const AllocaInst*, int>::iterator SI =
882 FuncInfo.StaticAllocaMap.find(AI);
883 if (SI != FuncInfo.StaticAllocaMap.end())
884 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
885 }
886
887 unsigned InReg = FuncInfo.ValueMap[V];
888 assert(InReg && "Value not in map!");
889
890 RegsForValue RFV(TLI, InReg, V->getType());
891 SDValue Chain = DAG.getEntryNode();
892 return RFV.getCopyFromRegs(DAG, Chain, NULL);
893}
894
895
896void SelectionDAGLowering::visitRet(ReturnInst &I) {
897 if (I.getNumOperands() == 0) {
898 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getControlRoot()));
899 return;
900 }
901
902 SmallVector<SDValue, 8> NewValues;
903 NewValues.push_back(getControlRoot());
904 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
905 SDValue RetOp = getValue(I.getOperand(i));
906
907 SmallVector<MVT, 4> ValueVTs;
908 ComputeValueVTs(TLI, I.getOperand(i)->getType(), ValueVTs);
909 for (unsigned j = 0, f = ValueVTs.size(); j != f; ++j) {
910 MVT VT = ValueVTs[j];
911
912 // FIXME: C calling convention requires the return type to be promoted to
Dale Johannesenc9c6da62008-09-25 20:47:45 +0000913 // at least 32-bit. But this is not necessary for non-C calling
914 // conventions.
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000915 if (VT.isInteger()) {
916 MVT MinVT = TLI.getRegisterType(MVT::i32);
917 if (VT.bitsLT(MinVT))
918 VT = MinVT;
919 }
920
921 unsigned NumParts = TLI.getNumRegisters(VT);
922 MVT PartVT = TLI.getRegisterType(VT);
923 SmallVector<SDValue, 4> Parts(NumParts);
924 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
925
926 const Function *F = I.getParent()->getParent();
Devang Patel05988662008-09-25 21:00:45 +0000927 if (F->paramHasAttr(0, Attribute::SExt))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000928 ExtendKind = ISD::SIGN_EXTEND;
Devang Patel05988662008-09-25 21:00:45 +0000929 else if (F->paramHasAttr(0, Attribute::ZExt))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000930 ExtendKind = ISD::ZERO_EXTEND;
931
932 getCopyToParts(DAG, SDValue(RetOp.getNode(), RetOp.getResNo() + j),
933 &Parts[0], NumParts, PartVT, ExtendKind);
934
Dale Johannesenc9c6da62008-09-25 20:47:45 +0000935 // 'inreg' on function refers to return value
936 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
Devang Patel05988662008-09-25 21:00:45 +0000937 if (F->paramHasAttr(0, Attribute::InReg))
Dale Johannesenc9c6da62008-09-25 20:47:45 +0000938 Flags.setInReg();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000939 for (unsigned i = 0; i < NumParts; ++i) {
940 NewValues.push_back(Parts[i]);
Dale Johannesenc9c6da62008-09-25 20:47:45 +0000941 NewValues.push_back(DAG.getArgFlags(Flags));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000942 }
943 }
944 }
945 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other,
946 &NewValues[0], NewValues.size()));
947}
948
949/// ExportFromCurrentBlock - If this condition isn't known to be exported from
950/// the current basic block, add it to ValueMap now so that we'll get a
951/// CopyTo/FromReg.
952void SelectionDAGLowering::ExportFromCurrentBlock(Value *V) {
953 // No need to export constants.
954 if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
955
956 // Already exported?
957 if (FuncInfo.isExportedInst(V)) return;
958
959 unsigned Reg = FuncInfo.InitializeRegForValue(V);
960 CopyValueToVirtualRegister(V, Reg);
961}
962
963bool SelectionDAGLowering::isExportableFromCurrentBlock(Value *V,
964 const BasicBlock *FromBB) {
965 // The operands of the setcc have to be in this block. We don't know
966 // how to export them from some other block.
967 if (Instruction *VI = dyn_cast<Instruction>(V)) {
968 // Can export from current BB.
969 if (VI->getParent() == FromBB)
970 return true;
971
972 // Is already exported, noop.
973 return FuncInfo.isExportedInst(V);
974 }
975
976 // If this is an argument, we can export it if the BB is the entry block or
977 // if it is already exported.
978 if (isa<Argument>(V)) {
979 if (FromBB == &FromBB->getParent()->getEntryBlock())
980 return true;
981
982 // Otherwise, can only export this if it is already exported.
983 return FuncInfo.isExportedInst(V);
984 }
985
986 // Otherwise, constants can always be exported.
987 return true;
988}
989
990static bool InBlock(const Value *V, const BasicBlock *BB) {
991 if (const Instruction *I = dyn_cast<Instruction>(V))
992 return I->getParent() == BB;
993 return true;
994}
995
Dan Gohman8c1a6ca2008-10-17 18:18:45 +0000996/// getFCmpCondCode - Return the ISD condition code corresponding to
997/// the given LLVM IR floating-point condition code. This includes
998/// consideration of global floating-point math flags.
999///
1000static ISD::CondCode getFCmpCondCode(FCmpInst::Predicate Pred) {
1001 ISD::CondCode FPC, FOC;
1002 switch (Pred) {
1003 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
1004 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
1005 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
1006 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
1007 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
1008 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
1009 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
1010 case FCmpInst::FCMP_ORD: FOC = FPC = ISD::SETO; break;
1011 case FCmpInst::FCMP_UNO: FOC = FPC = ISD::SETUO; break;
1012 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
1013 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
1014 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
1015 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
1016 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
1017 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
1018 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
1019 default:
1020 assert(0 && "Invalid FCmp predicate opcode!");
1021 FOC = FPC = ISD::SETFALSE;
1022 break;
1023 }
1024 if (FiniteOnlyFPMath())
1025 return FOC;
1026 else
1027 return FPC;
1028}
1029
1030/// getICmpCondCode - Return the ISD condition code corresponding to
1031/// the given LLVM IR integer condition code.
1032///
1033static ISD::CondCode getICmpCondCode(ICmpInst::Predicate Pred) {
1034 switch (Pred) {
1035 case ICmpInst::ICMP_EQ: return ISD::SETEQ;
1036 case ICmpInst::ICMP_NE: return ISD::SETNE;
1037 case ICmpInst::ICMP_SLE: return ISD::SETLE;
1038 case ICmpInst::ICMP_ULE: return ISD::SETULE;
1039 case ICmpInst::ICMP_SGE: return ISD::SETGE;
1040 case ICmpInst::ICMP_UGE: return ISD::SETUGE;
1041 case ICmpInst::ICMP_SLT: return ISD::SETLT;
1042 case ICmpInst::ICMP_ULT: return ISD::SETULT;
1043 case ICmpInst::ICMP_SGT: return ISD::SETGT;
1044 case ICmpInst::ICMP_UGT: return ISD::SETUGT;
1045 default:
1046 assert(0 && "Invalid ICmp predicate opcode!");
1047 return ISD::SETNE;
1048 }
1049}
1050
Dan Gohmanc2277342008-10-17 21:16:08 +00001051/// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
1052/// This function emits a branch and is used at the leaves of an OR or an
1053/// AND operator tree.
1054///
1055void
1056SelectionDAGLowering::EmitBranchForMergedCondition(Value *Cond,
1057 MachineBasicBlock *TBB,
1058 MachineBasicBlock *FBB,
1059 MachineBasicBlock *CurBB) {
1060 const BasicBlock *BB = CurBB->getBasicBlock();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001061
Dan Gohmanc2277342008-10-17 21:16:08 +00001062 // If the leaf of the tree is a comparison, merge the condition into
1063 // the caseblock.
1064 if (CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
1065 // The operands of the cmp have to be in this block. We don't know
1066 // how to export them from some other block. If this is the first block
1067 // of the sequence, no exporting is needed.
1068 if (CurBB == CurMBB ||
1069 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
1070 isExportableFromCurrentBlock(BOp->getOperand(1), BB))) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001071 ISD::CondCode Condition;
1072 if (ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
Dan Gohman8c1a6ca2008-10-17 18:18:45 +00001073 Condition = getICmpCondCode(IC->getPredicate());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001074 } else if (FCmpInst *FC = dyn_cast<FCmpInst>(Cond)) {
Dan Gohman8c1a6ca2008-10-17 18:18:45 +00001075 Condition = getFCmpCondCode(FC->getPredicate());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001076 } else {
1077 Condition = ISD::SETEQ; // silence warning.
1078 assert(0 && "Unknown compare instruction");
1079 }
Dan Gohmanc2277342008-10-17 21:16:08 +00001080
1081 CaseBlock CB(Condition, BOp->getOperand(0),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001082 BOp->getOperand(1), NULL, TBB, FBB, CurBB);
1083 SwitchCases.push_back(CB);
1084 return;
1085 }
Dan Gohmanc2277342008-10-17 21:16:08 +00001086 }
1087
1088 // Create a CaseBlock record representing this branch.
1089 CaseBlock CB(ISD::SETEQ, Cond, ConstantInt::getTrue(),
1090 NULL, TBB, FBB, CurBB);
1091 SwitchCases.push_back(CB);
1092}
1093
1094/// FindMergedConditions - If Cond is an expression like
1095void SelectionDAGLowering::FindMergedConditions(Value *Cond,
1096 MachineBasicBlock *TBB,
1097 MachineBasicBlock *FBB,
1098 MachineBasicBlock *CurBB,
1099 unsigned Opc) {
1100 // If this node is not part of the or/and tree, emit it as a branch.
1101 Instruction *BOp = dyn_cast<Instruction>(Cond);
1102 if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
1103 (unsigned)BOp->getOpcode() != Opc || !BOp->hasOneUse() ||
1104 BOp->getParent() != CurBB->getBasicBlock() ||
1105 !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
1106 !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
1107 EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001108 return;
1109 }
1110
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001111 // Create TmpBB after CurBB.
1112 MachineFunction::iterator BBI = CurBB;
1113 MachineFunction &MF = DAG.getMachineFunction();
1114 MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
1115 CurBB->getParent()->insert(++BBI, TmpBB);
1116
1117 if (Opc == Instruction::Or) {
1118 // Codegen X | Y as:
1119 // jmp_if_X TBB
1120 // jmp TmpBB
1121 // TmpBB:
1122 // jmp_if_Y TBB
1123 // jmp FBB
1124 //
1125
1126 // Emit the LHS condition.
1127 FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, Opc);
1128
1129 // Emit the RHS condition into TmpBB.
1130 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
1131 } else {
1132 assert(Opc == Instruction::And && "Unknown merge op!");
1133 // Codegen X & Y as:
1134 // jmp_if_X TmpBB
1135 // jmp FBB
1136 // TmpBB:
1137 // jmp_if_Y TBB
1138 // jmp FBB
1139 //
1140 // This requires creation of TmpBB after CurBB.
1141
1142 // Emit the LHS condition.
1143 FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, Opc);
1144
1145 // Emit the RHS condition into TmpBB.
1146 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
1147 }
1148}
1149
1150/// If the set of cases should be emitted as a series of branches, return true.
1151/// If we should emit this as a bunch of and/or'd together conditions, return
1152/// false.
1153bool
1154SelectionDAGLowering::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases){
1155 if (Cases.size() != 2) return true;
1156
1157 // If this is two comparisons of the same values or'd or and'd together, they
1158 // will get folded into a single comparison, so don't emit two blocks.
1159 if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
1160 Cases[0].CmpRHS == Cases[1].CmpRHS) ||
1161 (Cases[0].CmpRHS == Cases[1].CmpLHS &&
1162 Cases[0].CmpLHS == Cases[1].CmpRHS)) {
1163 return false;
1164 }
1165
1166 return true;
1167}
1168
1169void SelectionDAGLowering::visitBr(BranchInst &I) {
1170 // Update machine-CFG edges.
1171 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
1172
1173 // Figure out which block is immediately after the current one.
1174 MachineBasicBlock *NextBlock = 0;
1175 MachineFunction::iterator BBI = CurMBB;
1176 if (++BBI != CurMBB->getParent()->end())
1177 NextBlock = BBI;
1178
1179 if (I.isUnconditional()) {
1180 // Update machine-CFG edges.
1181 CurMBB->addSuccessor(Succ0MBB);
1182
1183 // If this is not a fall-through branch, emit the branch.
1184 if (Succ0MBB != NextBlock)
1185 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getControlRoot(),
1186 DAG.getBasicBlock(Succ0MBB)));
1187 return;
1188 }
1189
1190 // If this condition is one of the special cases we handle, do special stuff
1191 // now.
1192 Value *CondVal = I.getCondition();
1193 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
1194
1195 // If this is a series of conditions that are or'd or and'd together, emit
1196 // this as a sequence of branches instead of setcc's with and/or operations.
1197 // For example, instead of something like:
1198 // cmp A, B
1199 // C = seteq
1200 // cmp D, E
1201 // F = setle
1202 // or C, F
1203 // jnz foo
1204 // Emit:
1205 // cmp A, B
1206 // je foo
1207 // cmp D, E
1208 // jle foo
1209 //
1210 if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
1211 if (BOp->hasOneUse() &&
1212 (BOp->getOpcode() == Instruction::And ||
1213 BOp->getOpcode() == Instruction::Or)) {
1214 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, CurMBB, BOp->getOpcode());
1215 // If the compares in later blocks need to use values not currently
1216 // exported from this block, export them now. This block should always
1217 // be the first entry.
1218 assert(SwitchCases[0].ThisBB == CurMBB && "Unexpected lowering!");
1219
1220 // Allow some cases to be rejected.
1221 if (ShouldEmitAsBranches(SwitchCases)) {
1222 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
1223 ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
1224 ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
1225 }
1226
1227 // Emit the branch for this block.
1228 visitSwitchCase(SwitchCases[0]);
1229 SwitchCases.erase(SwitchCases.begin());
1230 return;
1231 }
1232
1233 // Okay, we decided not to do this, remove any inserted MBB's and clear
1234 // SwitchCases.
1235 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
1236 CurMBB->getParent()->erase(SwitchCases[i].ThisBB);
1237
1238 SwitchCases.clear();
1239 }
1240 }
1241
1242 // Create a CaseBlock record representing this branch.
1243 CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(),
1244 NULL, Succ0MBB, Succ1MBB, CurMBB);
1245 // Use visitSwitchCase to actually insert the fast branch sequence for this
1246 // cond branch.
1247 visitSwitchCase(CB);
1248}
1249
1250/// visitSwitchCase - Emits the necessary code to represent a single node in
1251/// the binary search tree resulting from lowering a switch instruction.
1252void SelectionDAGLowering::visitSwitchCase(CaseBlock &CB) {
1253 SDValue Cond;
1254 SDValue CondLHS = getValue(CB.CmpLHS);
1255
1256 // Build the setcc now.
1257 if (CB.CmpMHS == NULL) {
1258 // Fold "(X == true)" to X and "(X == false)" to !X to
1259 // handle common cases produced by branch lowering.
1260 if (CB.CmpRHS == ConstantInt::getTrue() && CB.CC == ISD::SETEQ)
1261 Cond = CondLHS;
1262 else if (CB.CmpRHS == ConstantInt::getFalse() && CB.CC == ISD::SETEQ) {
1263 SDValue True = DAG.getConstant(1, CondLHS.getValueType());
1264 Cond = DAG.getNode(ISD::XOR, CondLHS.getValueType(), CondLHS, True);
1265 } else
1266 Cond = DAG.getSetCC(MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
1267 } else {
1268 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
1269
1270 uint64_t Low = cast<ConstantInt>(CB.CmpLHS)->getSExtValue();
1271 uint64_t High = cast<ConstantInt>(CB.CmpRHS)->getSExtValue();
1272
1273 SDValue CmpOp = getValue(CB.CmpMHS);
1274 MVT VT = CmpOp.getValueType();
1275
1276 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
1277 Cond = DAG.getSetCC(MVT::i1, CmpOp, DAG.getConstant(High, VT), ISD::SETLE);
1278 } else {
1279 SDValue SUB = DAG.getNode(ISD::SUB, VT, CmpOp, DAG.getConstant(Low, VT));
1280 Cond = DAG.getSetCC(MVT::i1, SUB,
1281 DAG.getConstant(High-Low, VT), ISD::SETULE);
1282 }
1283 }
1284
1285 // Update successor info
1286 CurMBB->addSuccessor(CB.TrueBB);
1287 CurMBB->addSuccessor(CB.FalseBB);
1288
1289 // Set NextBlock to be the MBB immediately after the current one, if any.
1290 // This is used to avoid emitting unnecessary branches to the next block.
1291 MachineBasicBlock *NextBlock = 0;
1292 MachineFunction::iterator BBI = CurMBB;
1293 if (++BBI != CurMBB->getParent()->end())
1294 NextBlock = BBI;
1295
1296 // If the lhs block is the next block, invert the condition so that we can
1297 // fall through to the lhs instead of the rhs block.
1298 if (CB.TrueBB == NextBlock) {
1299 std::swap(CB.TrueBB, CB.FalseBB);
1300 SDValue True = DAG.getConstant(1, Cond.getValueType());
1301 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
1302 }
1303 SDValue BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, getControlRoot(), Cond,
1304 DAG.getBasicBlock(CB.TrueBB));
1305
1306 // If the branch was constant folded, fix up the CFG.
1307 if (BrCond.getOpcode() == ISD::BR) {
1308 CurMBB->removeSuccessor(CB.FalseBB);
1309 DAG.setRoot(BrCond);
1310 } else {
1311 // Otherwise, go ahead and insert the false branch.
1312 if (BrCond == getControlRoot())
1313 CurMBB->removeSuccessor(CB.TrueBB);
1314
1315 if (CB.FalseBB == NextBlock)
1316 DAG.setRoot(BrCond);
1317 else
1318 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond,
1319 DAG.getBasicBlock(CB.FalseBB)));
1320 }
1321}
1322
1323/// visitJumpTable - Emit JumpTable node in the current MBB
1324void SelectionDAGLowering::visitJumpTable(JumpTable &JT) {
1325 // Emit the code for the jump table
1326 assert(JT.Reg != -1U && "Should lower JT Header first!");
1327 MVT PTy = TLI.getPointerTy();
1328 SDValue Index = DAG.getCopyFromReg(getControlRoot(), JT.Reg, PTy);
1329 SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
1330 DAG.setRoot(DAG.getNode(ISD::BR_JT, MVT::Other, Index.getValue(1),
1331 Table, Index));
1332 return;
1333}
1334
1335/// visitJumpTableHeader - This function emits necessary code to produce index
1336/// in the JumpTable from switch case.
1337void SelectionDAGLowering::visitJumpTableHeader(JumpTable &JT,
1338 JumpTableHeader &JTH) {
1339 // Subtract the lowest switch case value from the value being switched on
1340 // and conditional branch to default mbb if the result is greater than the
1341 // difference between smallest and largest cases.
1342 SDValue SwitchOp = getValue(JTH.SValue);
1343 MVT VT = SwitchOp.getValueType();
1344 SDValue SUB = DAG.getNode(ISD::SUB, VT, SwitchOp,
1345 DAG.getConstant(JTH.First, VT));
1346
1347 // The SDNode we just created, which holds the value being switched on
1348 // minus the the smallest case value, needs to be copied to a virtual
1349 // register so it can be used as an index into the jump table in a
1350 // subsequent basic block. This value may be smaller or larger than the
1351 // target's pointer type, and therefore require extension or truncating.
1352 if (VT.bitsGT(TLI.getPointerTy()))
1353 SwitchOp = DAG.getNode(ISD::TRUNCATE, TLI.getPointerTy(), SUB);
1354 else
1355 SwitchOp = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(), SUB);
1356
1357 unsigned JumpTableReg = FuncInfo.MakeReg(TLI.getPointerTy());
1358 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), JumpTableReg, SwitchOp);
1359 JT.Reg = JumpTableReg;
1360
1361 // Emit the range check for the jump table, and branch to the default
1362 // block for the switch statement if the value being switched on exceeds
1363 // the largest case in the switch.
1364 SDValue CMP = DAG.getSetCC(TLI.getSetCCResultType(SUB), SUB,
1365 DAG.getConstant(JTH.Last-JTH.First,VT),
1366 ISD::SETUGT);
1367
1368 // Set NextBlock to be the MBB immediately after the current one, if any.
1369 // This is used to avoid emitting unnecessary branches to the next block.
1370 MachineBasicBlock *NextBlock = 0;
1371 MachineFunction::iterator BBI = CurMBB;
1372 if (++BBI != CurMBB->getParent()->end())
1373 NextBlock = BBI;
1374
1375 SDValue BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, CopyTo, CMP,
1376 DAG.getBasicBlock(JT.Default));
1377
1378 if (JT.MBB == NextBlock)
1379 DAG.setRoot(BrCond);
1380 else
1381 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond,
1382 DAG.getBasicBlock(JT.MBB)));
1383
1384 return;
1385}
1386
1387/// visitBitTestHeader - This function emits necessary code to produce value
1388/// suitable for "bit tests"
1389void SelectionDAGLowering::visitBitTestHeader(BitTestBlock &B) {
1390 // Subtract the minimum value
1391 SDValue SwitchOp = getValue(B.SValue);
1392 MVT VT = SwitchOp.getValueType();
1393 SDValue SUB = DAG.getNode(ISD::SUB, VT, SwitchOp,
1394 DAG.getConstant(B.First, VT));
1395
1396 // Check range
1397 SDValue RangeCmp = DAG.getSetCC(TLI.getSetCCResultType(SUB), SUB,
1398 DAG.getConstant(B.Range, VT),
1399 ISD::SETUGT);
1400
1401 SDValue ShiftOp;
1402 if (VT.bitsGT(TLI.getShiftAmountTy()))
1403 ShiftOp = DAG.getNode(ISD::TRUNCATE, TLI.getShiftAmountTy(), SUB);
1404 else
1405 ShiftOp = DAG.getNode(ISD::ZERO_EXTEND, TLI.getShiftAmountTy(), SUB);
1406
1407 // Make desired shift
1408 SDValue SwitchVal = DAG.getNode(ISD::SHL, TLI.getPointerTy(),
1409 DAG.getConstant(1, TLI.getPointerTy()),
1410 ShiftOp);
1411
1412 unsigned SwitchReg = FuncInfo.MakeReg(TLI.getPointerTy());
1413 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), SwitchReg, SwitchVal);
1414 B.Reg = SwitchReg;
1415
1416 // Set NextBlock to be the MBB immediately after the current one, if any.
1417 // This is used to avoid emitting unnecessary branches to the next block.
1418 MachineBasicBlock *NextBlock = 0;
1419 MachineFunction::iterator BBI = CurMBB;
1420 if (++BBI != CurMBB->getParent()->end())
1421 NextBlock = BBI;
1422
1423 MachineBasicBlock* MBB = B.Cases[0].ThisBB;
1424
1425 CurMBB->addSuccessor(B.Default);
1426 CurMBB->addSuccessor(MBB);
1427
1428 SDValue BrRange = DAG.getNode(ISD::BRCOND, MVT::Other, CopyTo, RangeCmp,
1429 DAG.getBasicBlock(B.Default));
1430
1431 if (MBB == NextBlock)
1432 DAG.setRoot(BrRange);
1433 else
1434 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, CopyTo,
1435 DAG.getBasicBlock(MBB)));
1436
1437 return;
1438}
1439
1440/// visitBitTestCase - this function produces one "bit test"
1441void SelectionDAGLowering::visitBitTestCase(MachineBasicBlock* NextMBB,
1442 unsigned Reg,
1443 BitTestCase &B) {
1444 // Emit bit tests and jumps
1445 SDValue SwitchVal = DAG.getCopyFromReg(getControlRoot(), Reg,
1446 TLI.getPointerTy());
1447
1448 SDValue AndOp = DAG.getNode(ISD::AND, TLI.getPointerTy(), SwitchVal,
1449 DAG.getConstant(B.Mask, TLI.getPointerTy()));
1450 SDValue AndCmp = DAG.getSetCC(TLI.getSetCCResultType(AndOp), AndOp,
1451 DAG.getConstant(0, TLI.getPointerTy()),
1452 ISD::SETNE);
1453
1454 CurMBB->addSuccessor(B.TargetBB);
1455 CurMBB->addSuccessor(NextMBB);
1456
1457 SDValue BrAnd = DAG.getNode(ISD::BRCOND, MVT::Other, getControlRoot(),
1458 AndCmp, DAG.getBasicBlock(B.TargetBB));
1459
1460 // Set NextBlock to be the MBB immediately after the current one, if any.
1461 // This is used to avoid emitting unnecessary branches to the next block.
1462 MachineBasicBlock *NextBlock = 0;
1463 MachineFunction::iterator BBI = CurMBB;
1464 if (++BBI != CurMBB->getParent()->end())
1465 NextBlock = BBI;
1466
1467 if (NextMBB == NextBlock)
1468 DAG.setRoot(BrAnd);
1469 else
1470 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrAnd,
1471 DAG.getBasicBlock(NextMBB)));
1472
1473 return;
1474}
1475
1476void SelectionDAGLowering::visitInvoke(InvokeInst &I) {
1477 // Retrieve successors.
1478 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
1479 MachineBasicBlock *LandingPad = FuncInfo.MBBMap[I.getSuccessor(1)];
1480
1481 if (isa<InlineAsm>(I.getCalledValue()))
1482 visitInlineAsm(&I);
1483 else
1484 LowerCallTo(&I, getValue(I.getOperand(0)), false, LandingPad);
1485
1486 // If the value of the invoke is used outside of its defining block, make it
1487 // available as a virtual register.
1488 if (!I.use_empty()) {
1489 DenseMap<const Value*, unsigned>::iterator VMI = FuncInfo.ValueMap.find(&I);
1490 if (VMI != FuncInfo.ValueMap.end())
1491 CopyValueToVirtualRegister(&I, VMI->second);
1492 }
1493
1494 // Update successor info
1495 CurMBB->addSuccessor(Return);
1496 CurMBB->addSuccessor(LandingPad);
1497
1498 // Drop into normal successor.
1499 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getControlRoot(),
1500 DAG.getBasicBlock(Return)));
1501}
1502
1503void SelectionDAGLowering::visitUnwind(UnwindInst &I) {
1504}
1505
1506/// handleSmallSwitchCaseRange - Emit a series of specific tests (suitable for
1507/// small case ranges).
1508bool SelectionDAGLowering::handleSmallSwitchRange(CaseRec& CR,
1509 CaseRecVector& WorkList,
1510 Value* SV,
1511 MachineBasicBlock* Default) {
1512 Case& BackCase = *(CR.Range.second-1);
1513
1514 // Size is the number of Cases represented by this range.
1515 unsigned Size = CR.Range.second - CR.Range.first;
1516 if (Size > 3)
1517 return false;
1518
1519 // Get the MachineFunction which holds the current MBB. This is used when
1520 // inserting any additional MBBs necessary to represent the switch.
1521 MachineFunction *CurMF = CurMBB->getParent();
1522
1523 // Figure out which block is immediately after the current one.
1524 MachineBasicBlock *NextBlock = 0;
1525 MachineFunction::iterator BBI = CR.CaseBB;
1526
1527 if (++BBI != CurMBB->getParent()->end())
1528 NextBlock = BBI;
1529
1530 // TODO: If any two of the cases has the same destination, and if one value
1531 // is the same as the other, but has one bit unset that the other has set,
1532 // use bit manipulation to do two compares at once. For example:
1533 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
1534
1535 // Rearrange the case blocks so that the last one falls through if possible.
1536 if (NextBlock && Default != NextBlock && BackCase.BB != NextBlock) {
1537 // The last case block won't fall through into 'NextBlock' if we emit the
1538 // branches in this order. See if rearranging a case value would help.
1539 for (CaseItr I = CR.Range.first, E = CR.Range.second-1; I != E; ++I) {
1540 if (I->BB == NextBlock) {
1541 std::swap(*I, BackCase);
1542 break;
1543 }
1544 }
1545 }
1546
1547 // Create a CaseBlock record representing a conditional branch to
1548 // the Case's target mbb if the value being switched on SV is equal
1549 // to C.
1550 MachineBasicBlock *CurBlock = CR.CaseBB;
1551 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I) {
1552 MachineBasicBlock *FallThrough;
1553 if (I != E-1) {
1554 FallThrough = CurMF->CreateMachineBasicBlock(CurBlock->getBasicBlock());
1555 CurMF->insert(BBI, FallThrough);
1556 } else {
1557 // If the last case doesn't match, go to the default block.
1558 FallThrough = Default;
1559 }
1560
1561 Value *RHS, *LHS, *MHS;
1562 ISD::CondCode CC;
1563 if (I->High == I->Low) {
1564 // This is just small small case range :) containing exactly 1 case
1565 CC = ISD::SETEQ;
1566 LHS = SV; RHS = I->High; MHS = NULL;
1567 } else {
1568 CC = ISD::SETLE;
1569 LHS = I->Low; MHS = SV; RHS = I->High;
1570 }
1571 CaseBlock CB(CC, LHS, RHS, MHS, I->BB, FallThrough, CurBlock);
1572
1573 // If emitting the first comparison, just call visitSwitchCase to emit the
1574 // code into the current block. Otherwise, push the CaseBlock onto the
1575 // vector to be later processed by SDISel, and insert the node's MBB
1576 // before the next MBB.
1577 if (CurBlock == CurMBB)
1578 visitSwitchCase(CB);
1579 else
1580 SwitchCases.push_back(CB);
1581
1582 CurBlock = FallThrough;
1583 }
1584
1585 return true;
1586}
1587
1588static inline bool areJTsAllowed(const TargetLowering &TLI) {
1589 return !DisableJumpTables &&
1590 (TLI.isOperationLegal(ISD::BR_JT, MVT::Other) ||
1591 TLI.isOperationLegal(ISD::BRIND, MVT::Other));
1592}
1593
1594/// handleJTSwitchCase - Emit jumptable for current switch case range
1595bool SelectionDAGLowering::handleJTSwitchCase(CaseRec& CR,
1596 CaseRecVector& WorkList,
1597 Value* SV,
1598 MachineBasicBlock* Default) {
1599 Case& FrontCase = *CR.Range.first;
1600 Case& BackCase = *(CR.Range.second-1);
1601
1602 int64_t First = cast<ConstantInt>(FrontCase.Low)->getSExtValue();
1603 int64_t Last = cast<ConstantInt>(BackCase.High)->getSExtValue();
1604
1605 uint64_t TSize = 0;
1606 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1607 I!=E; ++I)
1608 TSize += I->size();
1609
1610 if (!areJTsAllowed(TLI) || TSize <= 3)
1611 return false;
1612
1613 double Density = (double)TSize / (double)((Last - First) + 1ULL);
1614 if (Density < 0.4)
1615 return false;
1616
1617 DOUT << "Lowering jump table\n"
1618 << "First entry: " << First << ". Last entry: " << Last << "\n"
1619 << "Size: " << TSize << ". Density: " << Density << "\n\n";
1620
1621 // Get the MachineFunction which holds the current MBB. This is used when
1622 // inserting any additional MBBs necessary to represent the switch.
1623 MachineFunction *CurMF = CurMBB->getParent();
1624
1625 // Figure out which block is immediately after the current one.
1626 MachineBasicBlock *NextBlock = 0;
1627 MachineFunction::iterator BBI = CR.CaseBB;
1628
1629 if (++BBI != CurMBB->getParent()->end())
1630 NextBlock = BBI;
1631
1632 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1633
1634 // Create a new basic block to hold the code for loading the address
1635 // of the jump table, and jumping to it. Update successor information;
1636 // we will either branch to the default case for the switch, or the jump
1637 // table.
1638 MachineBasicBlock *JumpTableBB = CurMF->CreateMachineBasicBlock(LLVMBB);
1639 CurMF->insert(BBI, JumpTableBB);
1640 CR.CaseBB->addSuccessor(Default);
1641 CR.CaseBB->addSuccessor(JumpTableBB);
1642
1643 // Build a vector of destination BBs, corresponding to each target
1644 // of the jump table. If the value of the jump table slot corresponds to
1645 // a case statement, push the case's BB onto the vector, otherwise, push
1646 // the default BB.
1647 std::vector<MachineBasicBlock*> DestBBs;
1648 int64_t TEI = First;
1649 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++TEI) {
1650 int64_t Low = cast<ConstantInt>(I->Low)->getSExtValue();
1651 int64_t High = cast<ConstantInt>(I->High)->getSExtValue();
1652
1653 if ((Low <= TEI) && (TEI <= High)) {
1654 DestBBs.push_back(I->BB);
1655 if (TEI==High)
1656 ++I;
1657 } else {
1658 DestBBs.push_back(Default);
1659 }
1660 }
1661
1662 // Update successor info. Add one edge to each unique successor.
1663 BitVector SuccsHandled(CR.CaseBB->getParent()->getNumBlockIDs());
1664 for (std::vector<MachineBasicBlock*>::iterator I = DestBBs.begin(),
1665 E = DestBBs.end(); I != E; ++I) {
1666 if (!SuccsHandled[(*I)->getNumber()]) {
1667 SuccsHandled[(*I)->getNumber()] = true;
1668 JumpTableBB->addSuccessor(*I);
1669 }
1670 }
1671
1672 // Create a jump table index for this jump table, or return an existing
1673 // one.
1674 unsigned JTI = CurMF->getJumpTableInfo()->getJumpTableIndex(DestBBs);
1675
1676 // Set the jump table information so that we can codegen it as a second
1677 // MachineBasicBlock
1678 JumpTable JT(-1U, JTI, JumpTableBB, Default);
1679 JumpTableHeader JTH(First, Last, SV, CR.CaseBB, (CR.CaseBB == CurMBB));
1680 if (CR.CaseBB == CurMBB)
1681 visitJumpTableHeader(JT, JTH);
1682
1683 JTCases.push_back(JumpTableBlock(JTH, JT));
1684
1685 return true;
1686}
1687
1688/// handleBTSplitSwitchCase - emit comparison and split binary search tree into
1689/// 2 subtrees.
1690bool SelectionDAGLowering::handleBTSplitSwitchCase(CaseRec& CR,
1691 CaseRecVector& WorkList,
1692 Value* SV,
1693 MachineBasicBlock* Default) {
1694 // Get the MachineFunction which holds the current MBB. This is used when
1695 // inserting any additional MBBs necessary to represent the switch.
1696 MachineFunction *CurMF = CurMBB->getParent();
1697
1698 // Figure out which block is immediately after the current one.
1699 MachineBasicBlock *NextBlock = 0;
1700 MachineFunction::iterator BBI = CR.CaseBB;
1701
1702 if (++BBI != CurMBB->getParent()->end())
1703 NextBlock = BBI;
1704
1705 Case& FrontCase = *CR.Range.first;
1706 Case& BackCase = *(CR.Range.second-1);
1707 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1708
1709 // Size is the number of Cases represented by this range.
1710 unsigned Size = CR.Range.second - CR.Range.first;
1711
1712 int64_t First = cast<ConstantInt>(FrontCase.Low)->getSExtValue();
1713 int64_t Last = cast<ConstantInt>(BackCase.High)->getSExtValue();
1714 double FMetric = 0;
1715 CaseItr Pivot = CR.Range.first + Size/2;
1716
1717 // Select optimal pivot, maximizing sum density of LHS and RHS. This will
1718 // (heuristically) allow us to emit JumpTable's later.
1719 uint64_t TSize = 0;
1720 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1721 I!=E; ++I)
1722 TSize += I->size();
1723
1724 uint64_t LSize = FrontCase.size();
1725 uint64_t RSize = TSize-LSize;
1726 DOUT << "Selecting best pivot: \n"
1727 << "First: " << First << ", Last: " << Last <<"\n"
1728 << "LSize: " << LSize << ", RSize: " << RSize << "\n";
1729 for (CaseItr I = CR.Range.first, J=I+1, E = CR.Range.second;
1730 J!=E; ++I, ++J) {
1731 int64_t LEnd = cast<ConstantInt>(I->High)->getSExtValue();
1732 int64_t RBegin = cast<ConstantInt>(J->Low)->getSExtValue();
1733 assert((RBegin-LEnd>=1) && "Invalid case distance");
1734 double LDensity = (double)LSize / (double)((LEnd - First) + 1ULL);
1735 double RDensity = (double)RSize / (double)((Last - RBegin) + 1ULL);
1736 double Metric = Log2_64(RBegin-LEnd)*(LDensity+RDensity);
1737 // Should always split in some non-trivial place
1738 DOUT <<"=>Step\n"
1739 << "LEnd: " << LEnd << ", RBegin: " << RBegin << "\n"
1740 << "LDensity: " << LDensity << ", RDensity: " << RDensity << "\n"
1741 << "Metric: " << Metric << "\n";
1742 if (FMetric < Metric) {
1743 Pivot = J;
1744 FMetric = Metric;
1745 DOUT << "Current metric set to: " << FMetric << "\n";
1746 }
1747
1748 LSize += J->size();
1749 RSize -= J->size();
1750 }
1751 if (areJTsAllowed(TLI)) {
1752 // If our case is dense we *really* should handle it earlier!
1753 assert((FMetric > 0) && "Should handle dense range earlier!");
1754 } else {
1755 Pivot = CR.Range.first + Size/2;
1756 }
1757
1758 CaseRange LHSR(CR.Range.first, Pivot);
1759 CaseRange RHSR(Pivot, CR.Range.second);
1760 Constant *C = Pivot->Low;
1761 MachineBasicBlock *FalseBB = 0, *TrueBB = 0;
1762
1763 // We know that we branch to the LHS if the Value being switched on is
1764 // less than the Pivot value, C. We use this to optimize our binary
1765 // tree a bit, by recognizing that if SV is greater than or equal to the
1766 // LHS's Case Value, and that Case Value is exactly one less than the
1767 // Pivot's Value, then we can branch directly to the LHS's Target,
1768 // rather than creating a leaf node for it.
1769 if ((LHSR.second - LHSR.first) == 1 &&
1770 LHSR.first->High == CR.GE &&
1771 cast<ConstantInt>(C)->getSExtValue() ==
1772 (cast<ConstantInt>(CR.GE)->getSExtValue() + 1LL)) {
1773 TrueBB = LHSR.first->BB;
1774 } else {
1775 TrueBB = CurMF->CreateMachineBasicBlock(LLVMBB);
1776 CurMF->insert(BBI, TrueBB);
1777 WorkList.push_back(CaseRec(TrueBB, C, CR.GE, LHSR));
1778 }
1779
1780 // Similar to the optimization above, if the Value being switched on is
1781 // known to be less than the Constant CR.LT, and the current Case Value
1782 // is CR.LT - 1, then we can branch directly to the target block for
1783 // the current Case Value, rather than emitting a RHS leaf node for it.
1784 if ((RHSR.second - RHSR.first) == 1 && CR.LT &&
1785 cast<ConstantInt>(RHSR.first->Low)->getSExtValue() ==
1786 (cast<ConstantInt>(CR.LT)->getSExtValue() - 1LL)) {
1787 FalseBB = RHSR.first->BB;
1788 } else {
1789 FalseBB = CurMF->CreateMachineBasicBlock(LLVMBB);
1790 CurMF->insert(BBI, FalseBB);
1791 WorkList.push_back(CaseRec(FalseBB,CR.LT,C,RHSR));
1792 }
1793
1794 // Create a CaseBlock record representing a conditional branch to
1795 // the LHS node if the value being switched on SV is less than C.
1796 // Otherwise, branch to LHS.
1797 CaseBlock CB(ISD::SETLT, SV, C, NULL, TrueBB, FalseBB, CR.CaseBB);
1798
1799 if (CR.CaseBB == CurMBB)
1800 visitSwitchCase(CB);
1801 else
1802 SwitchCases.push_back(CB);
1803
1804 return true;
1805}
1806
1807/// handleBitTestsSwitchCase - if current case range has few destination and
1808/// range span less, than machine word bitwidth, encode case range into series
1809/// of masks and emit bit tests with these masks.
1810bool SelectionDAGLowering::handleBitTestsSwitchCase(CaseRec& CR,
1811 CaseRecVector& WorkList,
1812 Value* SV,
1813 MachineBasicBlock* Default){
1814 unsigned IntPtrBits = TLI.getPointerTy().getSizeInBits();
1815
1816 Case& FrontCase = *CR.Range.first;
1817 Case& BackCase = *(CR.Range.second-1);
1818
1819 // Get the MachineFunction which holds the current MBB. This is used when
1820 // inserting any additional MBBs necessary to represent the switch.
1821 MachineFunction *CurMF = CurMBB->getParent();
1822
1823 unsigned numCmps = 0;
1824 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1825 I!=E; ++I) {
1826 // Single case counts one, case range - two.
1827 if (I->Low == I->High)
1828 numCmps +=1;
1829 else
1830 numCmps +=2;
1831 }
1832
1833 // Count unique destinations
1834 SmallSet<MachineBasicBlock*, 4> Dests;
1835 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
1836 Dests.insert(I->BB);
1837 if (Dests.size() > 3)
1838 // Don't bother the code below, if there are too much unique destinations
1839 return false;
1840 }
1841 DOUT << "Total number of unique destinations: " << Dests.size() << "\n"
1842 << "Total number of comparisons: " << numCmps << "\n";
1843
1844 // Compute span of values.
1845 Constant* minValue = FrontCase.Low;
1846 Constant* maxValue = BackCase.High;
1847 uint64_t range = cast<ConstantInt>(maxValue)->getSExtValue() -
1848 cast<ConstantInt>(minValue)->getSExtValue();
1849 DOUT << "Compare range: " << range << "\n"
1850 << "Low bound: " << cast<ConstantInt>(minValue)->getSExtValue() << "\n"
1851 << "High bound: " << cast<ConstantInt>(maxValue)->getSExtValue() << "\n";
1852
1853 if (range>=IntPtrBits ||
1854 (!(Dests.size() == 1 && numCmps >= 3) &&
1855 !(Dests.size() == 2 && numCmps >= 5) &&
1856 !(Dests.size() >= 3 && numCmps >= 6)))
1857 return false;
1858
1859 DOUT << "Emitting bit tests\n";
1860 int64_t lowBound = 0;
1861
1862 // Optimize the case where all the case values fit in a
1863 // word without having to subtract minValue. In this case,
1864 // we can optimize away the subtraction.
1865 if (cast<ConstantInt>(minValue)->getSExtValue() >= 0 &&
1866 cast<ConstantInt>(maxValue)->getSExtValue() < IntPtrBits) {
1867 range = cast<ConstantInt>(maxValue)->getSExtValue();
1868 } else {
1869 lowBound = cast<ConstantInt>(minValue)->getSExtValue();
1870 }
1871
1872 CaseBitsVector CasesBits;
1873 unsigned i, count = 0;
1874
1875 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
1876 MachineBasicBlock* Dest = I->BB;
1877 for (i = 0; i < count; ++i)
1878 if (Dest == CasesBits[i].BB)
1879 break;
1880
1881 if (i == count) {
1882 assert((count < 3) && "Too much destinations to test!");
1883 CasesBits.push_back(CaseBits(0, Dest, 0));
1884 count++;
1885 }
1886
1887 uint64_t lo = cast<ConstantInt>(I->Low)->getSExtValue() - lowBound;
1888 uint64_t hi = cast<ConstantInt>(I->High)->getSExtValue() - lowBound;
1889
1890 for (uint64_t j = lo; j <= hi; j++) {
1891 CasesBits[i].Mask |= 1ULL << j;
1892 CasesBits[i].Bits++;
1893 }
1894
1895 }
1896 std::sort(CasesBits.begin(), CasesBits.end(), CaseBitsCmp());
1897
1898 BitTestInfo BTC;
1899
1900 // Figure out which block is immediately after the current one.
1901 MachineFunction::iterator BBI = CR.CaseBB;
1902 ++BBI;
1903
1904 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1905
1906 DOUT << "Cases:\n";
1907 for (unsigned i = 0, e = CasesBits.size(); i!=e; ++i) {
1908 DOUT << "Mask: " << CasesBits[i].Mask << ", Bits: " << CasesBits[i].Bits
1909 << ", BB: " << CasesBits[i].BB << "\n";
1910
1911 MachineBasicBlock *CaseBB = CurMF->CreateMachineBasicBlock(LLVMBB);
1912 CurMF->insert(BBI, CaseBB);
1913 BTC.push_back(BitTestCase(CasesBits[i].Mask,
1914 CaseBB,
1915 CasesBits[i].BB));
1916 }
1917
1918 BitTestBlock BTB(lowBound, range, SV,
1919 -1U, (CR.CaseBB == CurMBB),
1920 CR.CaseBB, Default, BTC);
1921
1922 if (CR.CaseBB == CurMBB)
1923 visitBitTestHeader(BTB);
1924
1925 BitTestCases.push_back(BTB);
1926
1927 return true;
1928}
1929
1930
1931/// Clusterify - Transform simple list of Cases into list of CaseRange's
1932unsigned SelectionDAGLowering::Clusterify(CaseVector& Cases,
1933 const SwitchInst& SI) {
1934 unsigned numCmps = 0;
1935
1936 // Start with "simple" cases
1937 for (unsigned i = 1; i < SI.getNumSuccessors(); ++i) {
1938 MachineBasicBlock *SMBB = FuncInfo.MBBMap[SI.getSuccessor(i)];
1939 Cases.push_back(Case(SI.getSuccessorValue(i),
1940 SI.getSuccessorValue(i),
1941 SMBB));
1942 }
1943 std::sort(Cases.begin(), Cases.end(), CaseCmp());
1944
1945 // Merge case into clusters
1946 if (Cases.size()>=2)
1947 // Must recompute end() each iteration because it may be
1948 // invalidated by erase if we hold on to it
1949 for (CaseItr I=Cases.begin(), J=++(Cases.begin()); J!=Cases.end(); ) {
1950 int64_t nextValue = cast<ConstantInt>(J->Low)->getSExtValue();
1951 int64_t currentValue = cast<ConstantInt>(I->High)->getSExtValue();
1952 MachineBasicBlock* nextBB = J->BB;
1953 MachineBasicBlock* currentBB = I->BB;
1954
1955 // If the two neighboring cases go to the same destination, merge them
1956 // into a single case.
1957 if ((nextValue-currentValue==1) && (currentBB == nextBB)) {
1958 I->High = J->High;
1959 J = Cases.erase(J);
1960 } else {
1961 I = J++;
1962 }
1963 }
1964
1965 for (CaseItr I=Cases.begin(), E=Cases.end(); I!=E; ++I, ++numCmps) {
1966 if (I->Low != I->High)
1967 // A range counts double, since it requires two compares.
1968 ++numCmps;
1969 }
1970
1971 return numCmps;
1972}
1973
1974void SelectionDAGLowering::visitSwitch(SwitchInst &SI) {
1975 // Figure out which block is immediately after the current one.
1976 MachineBasicBlock *NextBlock = 0;
1977 MachineFunction::iterator BBI = CurMBB;
1978
1979 MachineBasicBlock *Default = FuncInfo.MBBMap[SI.getDefaultDest()];
1980
1981 // If there is only the default destination, branch to it if it is not the
1982 // next basic block. Otherwise, just fall through.
1983 if (SI.getNumOperands() == 2) {
1984 // Update machine-CFG edges.
1985
1986 // If this is not a fall-through branch, emit the branch.
1987 CurMBB->addSuccessor(Default);
1988 if (Default != NextBlock)
1989 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getControlRoot(),
1990 DAG.getBasicBlock(Default)));
1991
1992 return;
1993 }
1994
1995 // If there are any non-default case statements, create a vector of Cases
1996 // representing each one, and sort the vector so that we can efficiently
1997 // create a binary search tree from them.
1998 CaseVector Cases;
1999 unsigned numCmps = Clusterify(Cases, SI);
2000 DOUT << "Clusterify finished. Total clusters: " << Cases.size()
2001 << ". Total compares: " << numCmps << "\n";
2002
2003 // Get the Value to be switched on and default basic blocks, which will be
2004 // inserted into CaseBlock records, representing basic blocks in the binary
2005 // search tree.
2006 Value *SV = SI.getOperand(0);
2007
2008 // Push the initial CaseRec onto the worklist
2009 CaseRecVector WorkList;
2010 WorkList.push_back(CaseRec(CurMBB,0,0,CaseRange(Cases.begin(),Cases.end())));
2011
2012 while (!WorkList.empty()) {
2013 // Grab a record representing a case range to process off the worklist
2014 CaseRec CR = WorkList.back();
2015 WorkList.pop_back();
2016
2017 if (handleBitTestsSwitchCase(CR, WorkList, SV, Default))
2018 continue;
2019
2020 // If the range has few cases (two or less) emit a series of specific
2021 // tests.
2022 if (handleSmallSwitchRange(CR, WorkList, SV, Default))
2023 continue;
2024
2025 // If the switch has more than 5 blocks, and at least 40% dense, and the
2026 // target supports indirect branches, then emit a jump table rather than
2027 // lowering the switch to a binary tree of conditional branches.
2028 if (handleJTSwitchCase(CR, WorkList, SV, Default))
2029 continue;
2030
2031 // Emit binary tree. We need to pick a pivot, and push left and right ranges
2032 // onto the worklist. Leafs are handled via handleSmallSwitchRange() call.
2033 handleBTSplitSwitchCase(CR, WorkList, SV, Default);
2034 }
2035}
2036
2037
2038void SelectionDAGLowering::visitSub(User &I) {
2039 // -0.0 - X --> fneg
2040 const Type *Ty = I.getType();
2041 if (isa<VectorType>(Ty)) {
2042 if (ConstantVector *CV = dyn_cast<ConstantVector>(I.getOperand(0))) {
2043 const VectorType *DestTy = cast<VectorType>(I.getType());
2044 const Type *ElTy = DestTy->getElementType();
2045 if (ElTy->isFloatingPoint()) {
2046 unsigned VL = DestTy->getNumElements();
2047 std::vector<Constant*> NZ(VL, ConstantFP::getNegativeZero(ElTy));
2048 Constant *CNZ = ConstantVector::get(&NZ[0], NZ.size());
2049 if (CV == CNZ) {
2050 SDValue Op2 = getValue(I.getOperand(1));
2051 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
2052 return;
2053 }
2054 }
2055 }
2056 }
2057 if (Ty->isFloatingPoint()) {
2058 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
2059 if (CFP->isExactlyValue(ConstantFP::getNegativeZero(Ty)->getValueAPF())) {
2060 SDValue Op2 = getValue(I.getOperand(1));
2061 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
2062 return;
2063 }
2064 }
2065
2066 visitBinary(I, Ty->isFPOrFPVector() ? ISD::FSUB : ISD::SUB);
2067}
2068
2069void SelectionDAGLowering::visitBinary(User &I, unsigned OpCode) {
2070 SDValue Op1 = getValue(I.getOperand(0));
2071 SDValue Op2 = getValue(I.getOperand(1));
2072
2073 setValue(&I, DAG.getNode(OpCode, Op1.getValueType(), Op1, Op2));
2074}
2075
2076void SelectionDAGLowering::visitShift(User &I, unsigned Opcode) {
2077 SDValue Op1 = getValue(I.getOperand(0));
2078 SDValue Op2 = getValue(I.getOperand(1));
2079 if (!isa<VectorType>(I.getType())) {
2080 if (TLI.getShiftAmountTy().bitsLT(Op2.getValueType()))
2081 Op2 = DAG.getNode(ISD::TRUNCATE, TLI.getShiftAmountTy(), Op2);
2082 else if (TLI.getShiftAmountTy().bitsGT(Op2.getValueType()))
2083 Op2 = DAG.getNode(ISD::ANY_EXTEND, TLI.getShiftAmountTy(), Op2);
2084 }
2085
2086 setValue(&I, DAG.getNode(Opcode, Op1.getValueType(), Op1, Op2));
2087}
2088
2089void SelectionDAGLowering::visitICmp(User &I) {
2090 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
2091 if (ICmpInst *IC = dyn_cast<ICmpInst>(&I))
2092 predicate = IC->getPredicate();
2093 else if (ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
2094 predicate = ICmpInst::Predicate(IC->getPredicate());
2095 SDValue Op1 = getValue(I.getOperand(0));
2096 SDValue Op2 = getValue(I.getOperand(1));
Dan Gohman8c1a6ca2008-10-17 18:18:45 +00002097 ISD::CondCode Opcode = getICmpCondCode(predicate);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002098 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Opcode));
2099}
2100
2101void SelectionDAGLowering::visitFCmp(User &I) {
2102 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
2103 if (FCmpInst *FC = dyn_cast<FCmpInst>(&I))
2104 predicate = FC->getPredicate();
2105 else if (ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
2106 predicate = FCmpInst::Predicate(FC->getPredicate());
2107 SDValue Op1 = getValue(I.getOperand(0));
2108 SDValue Op2 = getValue(I.getOperand(1));
Dan Gohman8c1a6ca2008-10-17 18:18:45 +00002109 ISD::CondCode Condition = getFCmpCondCode(predicate);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002110 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Condition));
2111}
2112
2113void SelectionDAGLowering::visitVICmp(User &I) {
2114 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
2115 if (VICmpInst *IC = dyn_cast<VICmpInst>(&I))
2116 predicate = IC->getPredicate();
2117 else if (ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
2118 predicate = ICmpInst::Predicate(IC->getPredicate());
2119 SDValue Op1 = getValue(I.getOperand(0));
2120 SDValue Op2 = getValue(I.getOperand(1));
Dan Gohman8c1a6ca2008-10-17 18:18:45 +00002121 ISD::CondCode Opcode = getICmpCondCode(predicate);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002122 setValue(&I, DAG.getVSetCC(Op1.getValueType(), Op1, Op2, Opcode));
2123}
2124
2125void SelectionDAGLowering::visitVFCmp(User &I) {
2126 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
2127 if (VFCmpInst *FC = dyn_cast<VFCmpInst>(&I))
2128 predicate = FC->getPredicate();
2129 else if (ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
2130 predicate = FCmpInst::Predicate(FC->getPredicate());
2131 SDValue Op1 = getValue(I.getOperand(0));
2132 SDValue Op2 = getValue(I.getOperand(1));
Dan Gohman8c1a6ca2008-10-17 18:18:45 +00002133 ISD::CondCode Condition = getFCmpCondCode(predicate);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002134 MVT DestVT = TLI.getValueType(I.getType());
2135
2136 setValue(&I, DAG.getVSetCC(DestVT, Op1, Op2, Condition));
2137}
2138
2139void SelectionDAGLowering::visitSelect(User &I) {
2140 SDValue Cond = getValue(I.getOperand(0));
2141 SDValue TrueVal = getValue(I.getOperand(1));
2142 SDValue FalseVal = getValue(I.getOperand(2));
2143 setValue(&I, DAG.getNode(ISD::SELECT, TrueVal.getValueType(), Cond,
2144 TrueVal, FalseVal));
2145}
2146
2147
2148void SelectionDAGLowering::visitTrunc(User &I) {
2149 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
2150 SDValue N = getValue(I.getOperand(0));
2151 MVT DestVT = TLI.getValueType(I.getType());
2152 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
2153}
2154
2155void SelectionDAGLowering::visitZExt(User &I) {
2156 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2157 // ZExt also can't be a cast to bool for same reason. So, nothing much to do
2158 SDValue N = getValue(I.getOperand(0));
2159 MVT DestVT = TLI.getValueType(I.getType());
2160 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
2161}
2162
2163void SelectionDAGLowering::visitSExt(User &I) {
2164 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2165 // SExt also can't be a cast to bool for same reason. So, nothing much to do
2166 SDValue N = getValue(I.getOperand(0));
2167 MVT DestVT = TLI.getValueType(I.getType());
2168 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, DestVT, N));
2169}
2170
2171void SelectionDAGLowering::visitFPTrunc(User &I) {
2172 // FPTrunc is never a no-op cast, no need to check
2173 SDValue N = getValue(I.getOperand(0));
2174 MVT DestVT = TLI.getValueType(I.getType());
2175 setValue(&I, DAG.getNode(ISD::FP_ROUND, DestVT, N, DAG.getIntPtrConstant(0)));
2176}
2177
2178void SelectionDAGLowering::visitFPExt(User &I){
2179 // FPTrunc is never a no-op cast, no need to check
2180 SDValue N = getValue(I.getOperand(0));
2181 MVT DestVT = TLI.getValueType(I.getType());
2182 setValue(&I, DAG.getNode(ISD::FP_EXTEND, DestVT, N));
2183}
2184
2185void SelectionDAGLowering::visitFPToUI(User &I) {
2186 // FPToUI is never a no-op cast, no need to check
2187 SDValue N = getValue(I.getOperand(0));
2188 MVT DestVT = TLI.getValueType(I.getType());
2189 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, DestVT, N));
2190}
2191
2192void SelectionDAGLowering::visitFPToSI(User &I) {
2193 // FPToSI is never a no-op cast, no need to check
2194 SDValue N = getValue(I.getOperand(0));
2195 MVT DestVT = TLI.getValueType(I.getType());
2196 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, DestVT, N));
2197}
2198
2199void SelectionDAGLowering::visitUIToFP(User &I) {
2200 // UIToFP is never a no-op cast, no need to check
2201 SDValue N = getValue(I.getOperand(0));
2202 MVT DestVT = TLI.getValueType(I.getType());
2203 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, DestVT, N));
2204}
2205
2206void SelectionDAGLowering::visitSIToFP(User &I){
Bill Wendling181b6272008-10-19 20:34:04 +00002207 // SIToFP is never a no-op cast, no need to check
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002208 SDValue N = getValue(I.getOperand(0));
2209 MVT DestVT = TLI.getValueType(I.getType());
2210 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, DestVT, N));
2211}
2212
2213void SelectionDAGLowering::visitPtrToInt(User &I) {
2214 // What to do depends on the size of the integer and the size of the pointer.
2215 // We can either truncate, zero extend, or no-op, accordingly.
2216 SDValue N = getValue(I.getOperand(0));
2217 MVT SrcVT = N.getValueType();
2218 MVT DestVT = TLI.getValueType(I.getType());
2219 SDValue Result;
2220 if (DestVT.bitsLT(SrcVT))
2221 Result = DAG.getNode(ISD::TRUNCATE, DestVT, N);
2222 else
2223 // Note: ZERO_EXTEND can handle cases where the sizes are equal too
2224 Result = DAG.getNode(ISD::ZERO_EXTEND, DestVT, N);
2225 setValue(&I, Result);
2226}
2227
2228void SelectionDAGLowering::visitIntToPtr(User &I) {
2229 // What to do depends on the size of the integer and the size of the pointer.
2230 // We can either truncate, zero extend, or no-op, accordingly.
2231 SDValue N = getValue(I.getOperand(0));
2232 MVT SrcVT = N.getValueType();
2233 MVT DestVT = TLI.getValueType(I.getType());
2234 if (DestVT.bitsLT(SrcVT))
2235 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
2236 else
2237 // Note: ZERO_EXTEND can handle cases where the sizes are equal too
2238 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
2239}
2240
2241void SelectionDAGLowering::visitBitCast(User &I) {
2242 SDValue N = getValue(I.getOperand(0));
2243 MVT DestVT = TLI.getValueType(I.getType());
2244
2245 // BitCast assures us that source and destination are the same size so this
2246 // is either a BIT_CONVERT or a no-op.
2247 if (DestVT != N.getValueType())
2248 setValue(&I, DAG.getNode(ISD::BIT_CONVERT, DestVT, N)); // convert types
2249 else
2250 setValue(&I, N); // noop cast.
2251}
2252
2253void SelectionDAGLowering::visitInsertElement(User &I) {
2254 SDValue InVec = getValue(I.getOperand(0));
2255 SDValue InVal = getValue(I.getOperand(1));
2256 SDValue InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
2257 getValue(I.getOperand(2)));
2258
2259 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT,
2260 TLI.getValueType(I.getType()),
2261 InVec, InVal, InIdx));
2262}
2263
2264void SelectionDAGLowering::visitExtractElement(User &I) {
2265 SDValue InVec = getValue(I.getOperand(0));
2266 SDValue InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
2267 getValue(I.getOperand(1)));
2268 setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
2269 TLI.getValueType(I.getType()), InVec, InIdx));
2270}
2271
2272void SelectionDAGLowering::visitShuffleVector(User &I) {
2273 SDValue V1 = getValue(I.getOperand(0));
2274 SDValue V2 = getValue(I.getOperand(1));
2275 SDValue Mask = getValue(I.getOperand(2));
2276
2277 setValue(&I, DAG.getNode(ISD::VECTOR_SHUFFLE,
2278 TLI.getValueType(I.getType()),
2279 V1, V2, Mask));
2280}
2281
2282void SelectionDAGLowering::visitInsertValue(InsertValueInst &I) {
2283 const Value *Op0 = I.getOperand(0);
2284 const Value *Op1 = I.getOperand(1);
2285 const Type *AggTy = I.getType();
2286 const Type *ValTy = Op1->getType();
2287 bool IntoUndef = isa<UndefValue>(Op0);
2288 bool FromUndef = isa<UndefValue>(Op1);
2289
2290 unsigned LinearIndex = ComputeLinearIndex(TLI, AggTy,
2291 I.idx_begin(), I.idx_end());
2292
2293 SmallVector<MVT, 4> AggValueVTs;
2294 ComputeValueVTs(TLI, AggTy, AggValueVTs);
2295 SmallVector<MVT, 4> ValValueVTs;
2296 ComputeValueVTs(TLI, ValTy, ValValueVTs);
2297
2298 unsigned NumAggValues = AggValueVTs.size();
2299 unsigned NumValValues = ValValueVTs.size();
2300 SmallVector<SDValue, 4> Values(NumAggValues);
2301
2302 SDValue Agg = getValue(Op0);
2303 SDValue Val = getValue(Op1);
2304 unsigned i = 0;
2305 // Copy the beginning value(s) from the original aggregate.
2306 for (; i != LinearIndex; ++i)
2307 Values[i] = IntoUndef ? DAG.getNode(ISD::UNDEF, AggValueVTs[i]) :
2308 SDValue(Agg.getNode(), Agg.getResNo() + i);
2309 // Copy values from the inserted value(s).
2310 for (; i != LinearIndex + NumValValues; ++i)
2311 Values[i] = FromUndef ? DAG.getNode(ISD::UNDEF, AggValueVTs[i]) :
2312 SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
2313 // Copy remaining value(s) from the original aggregate.
2314 for (; i != NumAggValues; ++i)
2315 Values[i] = IntoUndef ? DAG.getNode(ISD::UNDEF, AggValueVTs[i]) :
2316 SDValue(Agg.getNode(), Agg.getResNo() + i);
2317
2318 setValue(&I, DAG.getMergeValues(DAG.getVTList(&AggValueVTs[0], NumAggValues),
2319 &Values[0], NumAggValues));
2320}
2321
2322void SelectionDAGLowering::visitExtractValue(ExtractValueInst &I) {
2323 const Value *Op0 = I.getOperand(0);
2324 const Type *AggTy = Op0->getType();
2325 const Type *ValTy = I.getType();
2326 bool OutOfUndef = isa<UndefValue>(Op0);
2327
2328 unsigned LinearIndex = ComputeLinearIndex(TLI, AggTy,
2329 I.idx_begin(), I.idx_end());
2330
2331 SmallVector<MVT, 4> ValValueVTs;
2332 ComputeValueVTs(TLI, ValTy, ValValueVTs);
2333
2334 unsigned NumValValues = ValValueVTs.size();
2335 SmallVector<SDValue, 4> Values(NumValValues);
2336
2337 SDValue Agg = getValue(Op0);
2338 // Copy out the selected value(s).
2339 for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
2340 Values[i - LinearIndex] =
2341 OutOfUndef ? DAG.getNode(ISD::UNDEF, Agg.getNode()->getValueType(Agg.getResNo() + i)) :
2342 SDValue(Agg.getNode(), Agg.getResNo() + i);
2343
2344 setValue(&I, DAG.getMergeValues(DAG.getVTList(&ValValueVTs[0], NumValValues),
2345 &Values[0], NumValValues));
2346}
2347
2348
2349void SelectionDAGLowering::visitGetElementPtr(User &I) {
2350 SDValue N = getValue(I.getOperand(0));
2351 const Type *Ty = I.getOperand(0)->getType();
2352
2353 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
2354 OI != E; ++OI) {
2355 Value *Idx = *OI;
2356 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
2357 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
2358 if (Field) {
2359 // N = N + Offset
2360 uint64_t Offset = TD->getStructLayout(StTy)->getElementOffset(Field);
2361 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
2362 DAG.getIntPtrConstant(Offset));
2363 }
2364 Ty = StTy->getElementType(Field);
2365 } else {
2366 Ty = cast<SequentialType>(Ty)->getElementType();
2367
2368 // If this is a constant subscript, handle it quickly.
2369 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
2370 if (CI->getZExtValue() == 0) continue;
2371 uint64_t Offs =
2372 TD->getABITypeSize(Ty)*cast<ConstantInt>(CI)->getSExtValue();
2373 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
2374 DAG.getIntPtrConstant(Offs));
2375 continue;
2376 }
2377
2378 // N = N + Idx * ElementSize;
2379 uint64_t ElementSize = TD->getABITypeSize(Ty);
2380 SDValue IdxN = getValue(Idx);
2381
2382 // If the index is smaller or larger than intptr_t, truncate or extend
2383 // it.
2384 if (IdxN.getValueType().bitsLT(N.getValueType()))
2385 IdxN = DAG.getNode(ISD::SIGN_EXTEND, N.getValueType(), IdxN);
2386 else if (IdxN.getValueType().bitsGT(N.getValueType()))
2387 IdxN = DAG.getNode(ISD::TRUNCATE, N.getValueType(), IdxN);
2388
2389 // If this is a multiply by a power of two, turn it into a shl
2390 // immediately. This is a very common case.
2391 if (ElementSize != 1) {
2392 if (isPowerOf2_64(ElementSize)) {
2393 unsigned Amt = Log2_64(ElementSize);
2394 IdxN = DAG.getNode(ISD::SHL, N.getValueType(), IdxN,
2395 DAG.getConstant(Amt, TLI.getShiftAmountTy()));
2396 } else {
2397 SDValue Scale = DAG.getIntPtrConstant(ElementSize);
2398 IdxN = DAG.getNode(ISD::MUL, N.getValueType(), IdxN, Scale);
2399 }
2400 }
2401
2402 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
2403 }
2404 }
2405 setValue(&I, N);
2406}
2407
2408void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
2409 // If this is a fixed sized alloca in the entry block of the function,
2410 // allocate it statically on the stack.
2411 if (FuncInfo.StaticAllocaMap.count(&I))
2412 return; // getValue will auto-populate this.
2413
2414 const Type *Ty = I.getAllocatedType();
2415 uint64_t TySize = TLI.getTargetData()->getABITypeSize(Ty);
2416 unsigned Align =
2417 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
2418 I.getAlignment());
2419
2420 SDValue AllocSize = getValue(I.getArraySize());
2421 MVT IntPtr = TLI.getPointerTy();
2422 if (IntPtr.bitsLT(AllocSize.getValueType()))
2423 AllocSize = DAG.getNode(ISD::TRUNCATE, IntPtr, AllocSize);
2424 else if (IntPtr.bitsGT(AllocSize.getValueType()))
2425 AllocSize = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, AllocSize);
2426
2427 AllocSize = DAG.getNode(ISD::MUL, IntPtr, AllocSize,
2428 DAG.getIntPtrConstant(TySize));
2429
2430 // Handle alignment. If the requested alignment is less than or equal to
2431 // the stack alignment, ignore it. If the size is greater than or equal to
2432 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
2433 unsigned StackAlign =
2434 TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
2435 if (Align <= StackAlign)
2436 Align = 0;
2437
2438 // Round the size of the allocation up to the stack alignment size
2439 // by add SA-1 to the size.
2440 AllocSize = DAG.getNode(ISD::ADD, AllocSize.getValueType(), AllocSize,
2441 DAG.getIntPtrConstant(StackAlign-1));
2442 // Mask out the low bits for alignment purposes.
2443 AllocSize = DAG.getNode(ISD::AND, AllocSize.getValueType(), AllocSize,
2444 DAG.getIntPtrConstant(~(uint64_t)(StackAlign-1)));
2445
2446 SDValue Ops[] = { getRoot(), AllocSize, DAG.getIntPtrConstant(Align) };
2447 const MVT *VTs = DAG.getNodeValueTypes(AllocSize.getValueType(),
2448 MVT::Other);
2449 SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, VTs, 2, Ops, 3);
2450 setValue(&I, DSA);
2451 DAG.setRoot(DSA.getValue(1));
2452
2453 // Inform the Frame Information that we have just allocated a variable-sized
2454 // object.
2455 CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
2456}
2457
2458void SelectionDAGLowering::visitLoad(LoadInst &I) {
2459 const Value *SV = I.getOperand(0);
2460 SDValue Ptr = getValue(SV);
2461
2462 const Type *Ty = I.getType();
2463 bool isVolatile = I.isVolatile();
2464 unsigned Alignment = I.getAlignment();
2465
2466 SmallVector<MVT, 4> ValueVTs;
2467 SmallVector<uint64_t, 4> Offsets;
2468 ComputeValueVTs(TLI, Ty, ValueVTs, &Offsets);
2469 unsigned NumValues = ValueVTs.size();
2470 if (NumValues == 0)
2471 return;
2472
2473 SDValue Root;
2474 bool ConstantMemory = false;
2475 if (I.isVolatile())
2476 // Serialize volatile loads with other side effects.
2477 Root = getRoot();
2478 else if (AA->pointsToConstantMemory(SV)) {
2479 // Do not serialize (non-volatile) loads of constant memory with anything.
2480 Root = DAG.getEntryNode();
2481 ConstantMemory = true;
2482 } else {
2483 // Do not serialize non-volatile loads against each other.
2484 Root = DAG.getRoot();
2485 }
2486
2487 SmallVector<SDValue, 4> Values(NumValues);
2488 SmallVector<SDValue, 4> Chains(NumValues);
2489 MVT PtrVT = Ptr.getValueType();
2490 for (unsigned i = 0; i != NumValues; ++i) {
2491 SDValue L = DAG.getLoad(ValueVTs[i], Root,
2492 DAG.getNode(ISD::ADD, PtrVT, Ptr,
2493 DAG.getConstant(Offsets[i], PtrVT)),
2494 SV, Offsets[i],
2495 isVolatile, Alignment);
2496 Values[i] = L;
2497 Chains[i] = L.getValue(1);
2498 }
2499
2500 if (!ConstantMemory) {
2501 SDValue Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
2502 &Chains[0], NumValues);
2503 if (isVolatile)
2504 DAG.setRoot(Chain);
2505 else
2506 PendingLoads.push_back(Chain);
2507 }
2508
2509 setValue(&I, DAG.getMergeValues(DAG.getVTList(&ValueVTs[0], NumValues),
2510 &Values[0], NumValues));
2511}
2512
2513
2514void SelectionDAGLowering::visitStore(StoreInst &I) {
2515 Value *SrcV = I.getOperand(0);
2516 Value *PtrV = I.getOperand(1);
2517
2518 SmallVector<MVT, 4> ValueVTs;
2519 SmallVector<uint64_t, 4> Offsets;
2520 ComputeValueVTs(TLI, SrcV->getType(), ValueVTs, &Offsets);
2521 unsigned NumValues = ValueVTs.size();
2522 if (NumValues == 0)
2523 return;
2524
2525 // Get the lowered operands. Note that we do this after
2526 // checking if NumResults is zero, because with zero results
2527 // the operands won't have values in the map.
2528 SDValue Src = getValue(SrcV);
2529 SDValue Ptr = getValue(PtrV);
2530
2531 SDValue Root = getRoot();
2532 SmallVector<SDValue, 4> Chains(NumValues);
2533 MVT PtrVT = Ptr.getValueType();
2534 bool isVolatile = I.isVolatile();
2535 unsigned Alignment = I.getAlignment();
2536 for (unsigned i = 0; i != NumValues; ++i)
2537 Chains[i] = DAG.getStore(Root, SDValue(Src.getNode(), Src.getResNo() + i),
2538 DAG.getNode(ISD::ADD, PtrVT, Ptr,
2539 DAG.getConstant(Offsets[i], PtrVT)),
2540 PtrV, Offsets[i],
2541 isVolatile, Alignment);
2542
2543 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other, &Chains[0], NumValues));
2544}
2545
2546/// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
2547/// node.
2548void SelectionDAGLowering::visitTargetIntrinsic(CallInst &I,
2549 unsigned Intrinsic) {
2550 bool HasChain = !I.doesNotAccessMemory();
2551 bool OnlyLoad = HasChain && I.onlyReadsMemory();
2552
2553 // Build the operand list.
2554 SmallVector<SDValue, 8> Ops;
2555 if (HasChain) { // If this intrinsic has side-effects, chainify it.
2556 if (OnlyLoad) {
2557 // We don't need to serialize loads against other loads.
2558 Ops.push_back(DAG.getRoot());
2559 } else {
2560 Ops.push_back(getRoot());
2561 }
2562 }
2563
2564 // Add the intrinsic ID as an integer operand.
2565 Ops.push_back(DAG.getConstant(Intrinsic, TLI.getPointerTy()));
2566
2567 // Add all operands of the call to the operand list.
2568 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
2569 SDValue Op = getValue(I.getOperand(i));
2570 assert(TLI.isTypeLegal(Op.getValueType()) &&
2571 "Intrinsic uses a non-legal type?");
2572 Ops.push_back(Op);
2573 }
2574
2575 std::vector<MVT> VTs;
2576 if (I.getType() != Type::VoidTy) {
2577 MVT VT = TLI.getValueType(I.getType());
2578 if (VT.isVector()) {
2579 const VectorType *DestTy = cast<VectorType>(I.getType());
2580 MVT EltVT = TLI.getValueType(DestTy->getElementType());
2581
2582 VT = MVT::getVectorVT(EltVT, DestTy->getNumElements());
2583 assert(VT != MVT::Other && "Intrinsic uses a non-legal type?");
2584 }
2585
2586 assert(TLI.isTypeLegal(VT) && "Intrinsic uses a non-legal type?");
2587 VTs.push_back(VT);
2588 }
2589 if (HasChain)
2590 VTs.push_back(MVT::Other);
2591
2592 const MVT *VTList = DAG.getNodeValueTypes(VTs);
2593
2594 // Create the node.
2595 SDValue Result;
2596 if (!HasChain)
2597 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VTList, VTs.size(),
2598 &Ops[0], Ops.size());
2599 else if (I.getType() != Type::VoidTy)
2600 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, VTList, VTs.size(),
2601 &Ops[0], Ops.size());
2602 else
2603 Result = DAG.getNode(ISD::INTRINSIC_VOID, VTList, VTs.size(),
2604 &Ops[0], Ops.size());
2605
2606 if (HasChain) {
2607 SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
2608 if (OnlyLoad)
2609 PendingLoads.push_back(Chain);
2610 else
2611 DAG.setRoot(Chain);
2612 }
2613 if (I.getType() != Type::VoidTy) {
2614 if (const VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
2615 MVT VT = TLI.getValueType(PTy);
2616 Result = DAG.getNode(ISD::BIT_CONVERT, VT, Result);
2617 }
2618 setValue(&I, Result);
2619 }
2620}
2621
2622/// ExtractTypeInfo - Returns the type info, possibly bitcast, encoded in V.
2623static GlobalVariable *ExtractTypeInfo(Value *V) {
2624 V = V->stripPointerCasts();
2625 GlobalVariable *GV = dyn_cast<GlobalVariable>(V);
2626 assert ((GV || isa<ConstantPointerNull>(V)) &&
2627 "TypeInfo must be a global variable or NULL");
2628 return GV;
2629}
2630
2631namespace llvm {
2632
2633/// AddCatchInfo - Extract the personality and type infos from an eh.selector
2634/// call, and add them to the specified machine basic block.
2635void AddCatchInfo(CallInst &I, MachineModuleInfo *MMI,
2636 MachineBasicBlock *MBB) {
2637 // Inform the MachineModuleInfo of the personality for this landing pad.
2638 ConstantExpr *CE = cast<ConstantExpr>(I.getOperand(2));
2639 assert(CE->getOpcode() == Instruction::BitCast &&
2640 isa<Function>(CE->getOperand(0)) &&
2641 "Personality should be a function");
2642 MMI->addPersonality(MBB, cast<Function>(CE->getOperand(0)));
2643
2644 // Gather all the type infos for this landing pad and pass them along to
2645 // MachineModuleInfo.
2646 std::vector<GlobalVariable *> TyInfo;
2647 unsigned N = I.getNumOperands();
2648
2649 for (unsigned i = N - 1; i > 2; --i) {
2650 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(i))) {
2651 unsigned FilterLength = CI->getZExtValue();
2652 unsigned FirstCatch = i + FilterLength + !FilterLength;
2653 assert (FirstCatch <= N && "Invalid filter length");
2654
2655 if (FirstCatch < N) {
2656 TyInfo.reserve(N - FirstCatch);
2657 for (unsigned j = FirstCatch; j < N; ++j)
2658 TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
2659 MMI->addCatchTypeInfo(MBB, TyInfo);
2660 TyInfo.clear();
2661 }
2662
2663 if (!FilterLength) {
2664 // Cleanup.
2665 MMI->addCleanup(MBB);
2666 } else {
2667 // Filter.
2668 TyInfo.reserve(FilterLength - 1);
2669 for (unsigned j = i + 1; j < FirstCatch; ++j)
2670 TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
2671 MMI->addFilterTypeInfo(MBB, TyInfo);
2672 TyInfo.clear();
2673 }
2674
2675 N = i;
2676 }
2677 }
2678
2679 if (N > 3) {
2680 TyInfo.reserve(N - 3);
2681 for (unsigned j = 3; j < N; ++j)
2682 TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
2683 MMI->addCatchTypeInfo(MBB, TyInfo);
2684 }
2685}
2686
2687}
2688
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00002689/// GetSignificand - Get the significand and build it into a floating-point
2690/// number with exponent of 1:
2691///
2692/// Op = (Op & 0x007fffff) | 0x3f800000;
2693///
2694/// where Op is the hexidecimal representation of floating point value.
Bill Wendling39150252008-09-09 20:39:27 +00002695static SDValue
2696GetSignificand(SelectionDAG &DAG, SDValue Op) {
2697 SDValue t1 = DAG.getNode(ISD::AND, MVT::i32, Op,
2698 DAG.getConstant(0x007fffff, MVT::i32));
2699 SDValue t2 = DAG.getNode(ISD::OR, MVT::i32, t1,
2700 DAG.getConstant(0x3f800000, MVT::i32));
2701 return DAG.getNode(ISD::BIT_CONVERT, MVT::f32, t2);
2702}
2703
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00002704/// GetExponent - Get the exponent:
2705///
2706/// (float)((Op1 >> 23) - 127);
2707///
2708/// where Op is the hexidecimal representation of floating point value.
Bill Wendling39150252008-09-09 20:39:27 +00002709static SDValue
2710GetExponent(SelectionDAG &DAG, SDValue Op) {
Bill Wendlingfc2508e2008-09-10 06:26:10 +00002711 SDValue t1 = DAG.getNode(ISD::SRL, MVT::i32, Op,
Bill Wendling39150252008-09-09 20:39:27 +00002712 DAG.getConstant(23, MVT::i32));
Bill Wendlingfc2508e2008-09-10 06:26:10 +00002713 SDValue t2 = DAG.getNode(ISD::SUB, MVT::i32, t1,
Bill Wendling39150252008-09-09 20:39:27 +00002714 DAG.getConstant(127, MVT::i32));
Bill Wendlingfc2508e2008-09-10 06:26:10 +00002715 return DAG.getNode(ISD::UINT_TO_FP, MVT::f32, t2);
Bill Wendling39150252008-09-09 20:39:27 +00002716}
2717
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00002718/// getF32Constant - Get 32-bit floating point constant.
2719static SDValue
2720getF32Constant(SelectionDAG &DAG, unsigned Flt) {
2721 return DAG.getConstantFP(APFloat(APInt(32, Flt)), MVT::f32);
2722}
2723
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002724/// Inlined utility function to implement binary input atomic intrinsics for
2725/// visitIntrinsicCall: I is a call instruction
2726/// Op is the associated NodeType for I
2727const char *
2728SelectionDAGLowering::implVisitBinaryAtomic(CallInst& I, ISD::NodeType Op) {
2729 SDValue Root = getRoot();
2730 SDValue L = DAG.getAtomic(Op, Root,
2731 getValue(I.getOperand(1)),
2732 getValue(I.getOperand(2)),
2733 I.getOperand(1));
2734 setValue(&I, L);
2735 DAG.setRoot(L.getValue(1));
2736 return 0;
2737}
2738
Bill Wendlingb4ec2832008-09-09 22:13:54 +00002739/// visitExp - Lower an exp intrinsic. Handles the special sequences for
2740/// limited-precision mode.
Dale Johannesen59e577f2008-09-05 18:38:42 +00002741void
2742SelectionDAGLowering::visitExp(CallInst &I) {
2743 SDValue result;
Bill Wendlingb4ec2832008-09-09 22:13:54 +00002744
2745 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
2746 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
2747 SDValue Op = getValue(I.getOperand(1));
2748
2749 // Put the exponent in the right bit position for later addition to the
2750 // final result:
2751 //
2752 // #define LOG2OFe 1.4426950f
2753 // IntegerPartOfX = ((int32_t)(X * LOG2OFe));
2754 SDValue t0 = DAG.getNode(ISD::FMUL, MVT::f32, Op,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00002755 getF32Constant(DAG, 0x3fb8aa3b));
Bill Wendlingb4ec2832008-09-09 22:13:54 +00002756 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, MVT::i32, t0);
2757
2758 // FractionalPartOfX = (X * LOG2OFe) - (float)IntegerPartOfX;
2759 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, MVT::f32, IntegerPartOfX);
2760 SDValue X = DAG.getNode(ISD::FSUB, MVT::f32, t0, t1);
2761
2762 // IntegerPartOfX <<= 23;
2763 IntegerPartOfX = DAG.getNode(ISD::SHL, MVT::i32, IntegerPartOfX,
2764 DAG.getConstant(23, MVT::i32));
2765
2766 if (LimitFloatPrecision <= 6) {
2767 // For floating-point precision of 6:
2768 //
2769 // TwoToFractionalPartOfX =
2770 // 0.997535578f +
2771 // (0.735607626f + 0.252464424f * x) * x;
2772 //
2773 // error 0.0144103317, which is 6 bits
2774 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00002775 getF32Constant(DAG, 0x3e814304));
Bill Wendlingb4ec2832008-09-09 22:13:54 +00002776 SDValue t3 = DAG.getNode(ISD::FADD, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00002777 getF32Constant(DAG, 0x3f3c50c8));
Bill Wendlingb4ec2832008-09-09 22:13:54 +00002778 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
2779 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00002780 getF32Constant(DAG, 0x3f7f5e7e));
Bill Wendlingb4ec2832008-09-09 22:13:54 +00002781 SDValue TwoToFracPartOfX = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, t5);
2782
2783 // Add the exponent into the result in integer domain.
2784 SDValue t6 = DAG.getNode(ISD::ADD, MVT::i32,
2785 TwoToFracPartOfX, IntegerPartOfX);
2786
2787 result = DAG.getNode(ISD::BIT_CONVERT, MVT::f32, t6);
2788 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
2789 // For floating-point precision of 12:
2790 //
2791 // TwoToFractionalPartOfX =
2792 // 0.999892986f +
2793 // (0.696457318f +
2794 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
2795 //
2796 // 0.000107046256 error, which is 13 to 14 bits
2797 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00002798 getF32Constant(DAG, 0x3da235e3));
Bill Wendlingb4ec2832008-09-09 22:13:54 +00002799 SDValue t3 = DAG.getNode(ISD::FADD, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00002800 getF32Constant(DAG, 0x3e65b8f3));
Bill Wendlingb4ec2832008-09-09 22:13:54 +00002801 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
2802 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00002803 getF32Constant(DAG, 0x3f324b07));
Bill Wendlingb4ec2832008-09-09 22:13:54 +00002804 SDValue t6 = DAG.getNode(ISD::FMUL, MVT::f32, t5, X);
2805 SDValue t7 = DAG.getNode(ISD::FADD, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00002806 getF32Constant(DAG, 0x3f7ff8fd));
Bill Wendlingb4ec2832008-09-09 22:13:54 +00002807 SDValue TwoToFracPartOfX = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, t7);
2808
2809 // Add the exponent into the result in integer domain.
2810 SDValue t8 = DAG.getNode(ISD::ADD, MVT::i32,
2811 TwoToFracPartOfX, IntegerPartOfX);
2812
2813 result = DAG.getNode(ISD::BIT_CONVERT, MVT::f32, t8);
2814 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
2815 // For floating-point precision of 18:
2816 //
2817 // TwoToFractionalPartOfX =
2818 // 0.999999982f +
2819 // (0.693148872f +
2820 // (0.240227044f +
2821 // (0.554906021e-1f +
2822 // (0.961591928e-2f +
2823 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
2824 //
2825 // error 2.47208000*10^(-7), which is better than 18 bits
2826 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00002827 getF32Constant(DAG, 0x3924b03e));
Bill Wendlingb4ec2832008-09-09 22:13:54 +00002828 SDValue t3 = DAG.getNode(ISD::FADD, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00002829 getF32Constant(DAG, 0x3ab24b87));
Bill Wendlingb4ec2832008-09-09 22:13:54 +00002830 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
2831 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00002832 getF32Constant(DAG, 0x3c1d8c17));
Bill Wendlingb4ec2832008-09-09 22:13:54 +00002833 SDValue t6 = DAG.getNode(ISD::FMUL, MVT::f32, t5, X);
2834 SDValue t7 = DAG.getNode(ISD::FADD, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00002835 getF32Constant(DAG, 0x3d634a1d));
Bill Wendlingb4ec2832008-09-09 22:13:54 +00002836 SDValue t8 = DAG.getNode(ISD::FMUL, MVT::f32, t7, X);
2837 SDValue t9 = DAG.getNode(ISD::FADD, MVT::f32, t8,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00002838 getF32Constant(DAG, 0x3e75fe14));
Bill Wendlingb4ec2832008-09-09 22:13:54 +00002839 SDValue t10 = DAG.getNode(ISD::FMUL, MVT::f32, t9, X);
2840 SDValue t11 = DAG.getNode(ISD::FADD, MVT::f32, t10,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00002841 getF32Constant(DAG, 0x3f317234));
Bill Wendlingb4ec2832008-09-09 22:13:54 +00002842 SDValue t12 = DAG.getNode(ISD::FMUL, MVT::f32, t11, X);
2843 SDValue t13 = DAG.getNode(ISD::FADD, MVT::f32, t12,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00002844 getF32Constant(DAG, 0x3f800000));
Bill Wendlingb4ec2832008-09-09 22:13:54 +00002845 SDValue TwoToFracPartOfX = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, t13);
2846
2847 // Add the exponent into the result in integer domain.
2848 SDValue t14 = DAG.getNode(ISD::ADD, MVT::i32,
2849 TwoToFracPartOfX, IntegerPartOfX);
2850
2851 result = DAG.getNode(ISD::BIT_CONVERT, MVT::f32, t14);
2852 }
2853 } else {
2854 // No special expansion.
2855 result = DAG.getNode(ISD::FEXP,
2856 getValue(I.getOperand(1)).getValueType(),
2857 getValue(I.getOperand(1)));
2858 }
2859
Dale Johannesen59e577f2008-09-05 18:38:42 +00002860 setValue(&I, result);
2861}
2862
Bill Wendling39150252008-09-09 20:39:27 +00002863/// visitLog - Lower a log intrinsic. Handles the special sequences for
2864/// limited-precision mode.
Dale Johannesen59e577f2008-09-05 18:38:42 +00002865void
2866SelectionDAGLowering::visitLog(CallInst &I) {
2867 SDValue result;
Bill Wendling39150252008-09-09 20:39:27 +00002868
2869 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
2870 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
2871 SDValue Op = getValue(I.getOperand(1));
2872 SDValue Op1 = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, Op);
2873
2874 // Scale the exponent by log(2) [0.69314718f].
2875 SDValue Exp = GetExponent(DAG, Op1);
2876 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, MVT::f32, Exp,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00002877 getF32Constant(DAG, 0x3f317218));
Bill Wendling39150252008-09-09 20:39:27 +00002878
2879 // Get the significand and build it into a floating-point number with
2880 // exponent of 1.
2881 SDValue X = GetSignificand(DAG, Op1);
2882
2883 if (LimitFloatPrecision <= 6) {
2884 // For floating-point precision of 6:
2885 //
2886 // LogofMantissa =
2887 // -1.1609546f +
2888 // (1.4034025f - 0.23903021f * x) * x;
2889 //
2890 // error 0.0034276066, which is better than 8 bits
2891 SDValue t0 = DAG.getNode(ISD::FMUL, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00002892 getF32Constant(DAG, 0xbe74c456));
Bill Wendling39150252008-09-09 20:39:27 +00002893 SDValue t1 = DAG.getNode(ISD::FADD, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00002894 getF32Constant(DAG, 0x3fb3a2b1));
Bill Wendling39150252008-09-09 20:39:27 +00002895 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, t1, X);
2896 SDValue LogOfMantissa = DAG.getNode(ISD::FSUB, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00002897 getF32Constant(DAG, 0x3f949a29));
Bill Wendling39150252008-09-09 20:39:27 +00002898
2899 result = DAG.getNode(ISD::FADD, MVT::f32, LogOfExponent, LogOfMantissa);
2900 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
2901 // For floating-point precision of 12:
2902 //
2903 // LogOfMantissa =
2904 // -1.7417939f +
2905 // (2.8212026f +
2906 // (-1.4699568f +
2907 // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
2908 //
2909 // error 0.000061011436, which is 14 bits
2910 SDValue t0 = DAG.getNode(ISD::FMUL, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00002911 getF32Constant(DAG, 0xbd67b6d6));
Bill Wendling39150252008-09-09 20:39:27 +00002912 SDValue t1 = DAG.getNode(ISD::FADD, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00002913 getF32Constant(DAG, 0x3ee4f4b8));
Bill Wendling39150252008-09-09 20:39:27 +00002914 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, t1, X);
2915 SDValue t3 = DAG.getNode(ISD::FSUB, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00002916 getF32Constant(DAG, 0x3fbc278b));
Bill Wendling39150252008-09-09 20:39:27 +00002917 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
2918 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00002919 getF32Constant(DAG, 0x40348e95));
Bill Wendling39150252008-09-09 20:39:27 +00002920 SDValue t6 = DAG.getNode(ISD::FMUL, MVT::f32, t5, X);
2921 SDValue LogOfMantissa = DAG.getNode(ISD::FSUB, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00002922 getF32Constant(DAG, 0x3fdef31a));
Bill Wendling39150252008-09-09 20:39:27 +00002923
2924 result = DAG.getNode(ISD::FADD, MVT::f32, LogOfExponent, LogOfMantissa);
2925 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
2926 // For floating-point precision of 18:
2927 //
2928 // LogOfMantissa =
2929 // -2.1072184f +
2930 // (4.2372794f +
2931 // (-3.7029485f +
2932 // (2.2781945f +
2933 // (-0.87823314f +
2934 // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
2935 //
2936 // error 0.0000023660568, which is better than 18 bits
2937 SDValue t0 = DAG.getNode(ISD::FMUL, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00002938 getF32Constant(DAG, 0xbc91e5ac));
Bill Wendling39150252008-09-09 20:39:27 +00002939 SDValue t1 = DAG.getNode(ISD::FADD, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00002940 getF32Constant(DAG, 0x3e4350aa));
Bill Wendling39150252008-09-09 20:39:27 +00002941 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, t1, X);
2942 SDValue t3 = DAG.getNode(ISD::FSUB, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00002943 getF32Constant(DAG, 0x3f60d3e3));
Bill Wendling39150252008-09-09 20:39:27 +00002944 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
2945 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00002946 getF32Constant(DAG, 0x4011cdf0));
Bill Wendling39150252008-09-09 20:39:27 +00002947 SDValue t6 = DAG.getNode(ISD::FMUL, MVT::f32, t5, X);
2948 SDValue t7 = DAG.getNode(ISD::FSUB, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00002949 getF32Constant(DAG, 0x406cfd1c));
Bill Wendling39150252008-09-09 20:39:27 +00002950 SDValue t8 = DAG.getNode(ISD::FMUL, MVT::f32, t7, X);
2951 SDValue t9 = DAG.getNode(ISD::FADD, MVT::f32, t8,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00002952 getF32Constant(DAG, 0x408797cb));
Bill Wendling39150252008-09-09 20:39:27 +00002953 SDValue t10 = DAG.getNode(ISD::FMUL, MVT::f32, t9, X);
2954 SDValue LogOfMantissa = DAG.getNode(ISD::FSUB, MVT::f32, t10,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00002955 getF32Constant(DAG, 0x4006dcab));
Bill Wendling39150252008-09-09 20:39:27 +00002956
2957 result = DAG.getNode(ISD::FADD, MVT::f32, LogOfExponent, LogOfMantissa);
2958 }
2959 } else {
2960 // No special expansion.
2961 result = DAG.getNode(ISD::FLOG,
2962 getValue(I.getOperand(1)).getValueType(),
2963 getValue(I.getOperand(1)));
2964 }
2965
Dale Johannesen59e577f2008-09-05 18:38:42 +00002966 setValue(&I, result);
2967}
2968
Bill Wendling3eb59402008-09-09 00:28:24 +00002969/// visitLog2 - Lower a log2 intrinsic. Handles the special sequences for
2970/// limited-precision mode.
Dale Johannesen59e577f2008-09-05 18:38:42 +00002971void
2972SelectionDAGLowering::visitLog2(CallInst &I) {
2973 SDValue result;
Bill Wendling3eb59402008-09-09 00:28:24 +00002974
Dale Johannesen853244f2008-09-05 23:49:37 +00002975 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
Bill Wendling3eb59402008-09-09 00:28:24 +00002976 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
2977 SDValue Op = getValue(I.getOperand(1));
2978 SDValue Op1 = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, Op);
2979
Bill Wendling39150252008-09-09 20:39:27 +00002980 // Get the exponent.
2981 SDValue LogOfExponent = GetExponent(DAG, Op1);
Bill Wendling3eb59402008-09-09 00:28:24 +00002982
2983 // Get the significand and build it into a floating-point number with
Bill Wendling39150252008-09-09 20:39:27 +00002984 // exponent of 1.
2985 SDValue X = GetSignificand(DAG, Op1);
Bill Wendling3eb59402008-09-09 00:28:24 +00002986
2987 // Different possible minimax approximations of significand in
2988 // floating-point for various degrees of accuracy over [1,2].
2989 if (LimitFloatPrecision <= 6) {
2990 // For floating-point precision of 6:
2991 //
2992 // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
2993 //
2994 // error 0.0049451742, which is more than 7 bits
Bill Wendling39150252008-09-09 20:39:27 +00002995 SDValue t0 = DAG.getNode(ISD::FMUL, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00002996 getF32Constant(DAG, 0xbeb08fe0));
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, 0x40019463));
Bill Wendling39150252008-09-09 20:39:27 +00002999 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, t1, X);
3000 SDValue Log2ofMantissa = DAG.getNode(ISD::FSUB, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003001 getF32Constant(DAG, 0x3fd6633d));
Bill Wendling3eb59402008-09-09 00:28:24 +00003002
3003 result = DAG.getNode(ISD::FADD, MVT::f32, LogOfExponent, Log2ofMantissa);
3004 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3005 // For floating-point precision of 12:
3006 //
3007 // Log2ofMantissa =
3008 // -2.51285454f +
3009 // (4.07009056f +
3010 // (-2.12067489f +
3011 // (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
3012 //
3013 // error 0.0000876136000, which is better than 13 bits
Bill Wendling39150252008-09-09 20:39:27 +00003014 SDValue t0 = DAG.getNode(ISD::FMUL, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003015 getF32Constant(DAG, 0xbda7262e));
Bill Wendling39150252008-09-09 20:39:27 +00003016 SDValue t1 = DAG.getNode(ISD::FADD, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003017 getF32Constant(DAG, 0x3f25280b));
Bill Wendling39150252008-09-09 20:39:27 +00003018 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, t1, X);
3019 SDValue t3 = DAG.getNode(ISD::FSUB, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003020 getF32Constant(DAG, 0x4007b923));
Bill Wendling39150252008-09-09 20:39:27 +00003021 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3022 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003023 getF32Constant(DAG, 0x40823e2f));
Bill Wendling39150252008-09-09 20:39:27 +00003024 SDValue t6 = DAG.getNode(ISD::FMUL, MVT::f32, t5, X);
3025 SDValue Log2ofMantissa = DAG.getNode(ISD::FSUB, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003026 getF32Constant(DAG, 0x4020d29c));
Bill Wendling3eb59402008-09-09 00:28:24 +00003027
3028 result = DAG.getNode(ISD::FADD, MVT::f32, LogOfExponent, Log2ofMantissa);
3029 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3030 // For floating-point precision of 18:
3031 //
3032 // Log2ofMantissa =
3033 // -3.0400495f +
3034 // (6.1129976f +
3035 // (-5.3420409f +
3036 // (3.2865683f +
3037 // (-1.2669343f +
3038 // (0.27515199f -
3039 // 0.25691327e-1f * x) * x) * x) * x) * x) * x;
3040 //
3041 // error 0.0000018516, which is better than 18 bits
Bill Wendling39150252008-09-09 20:39:27 +00003042 SDValue t0 = DAG.getNode(ISD::FMUL, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003043 getF32Constant(DAG, 0xbcd2769e));
Bill Wendling39150252008-09-09 20:39:27 +00003044 SDValue t1 = DAG.getNode(ISD::FADD, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003045 getF32Constant(DAG, 0x3e8ce0b9));
Bill Wendling39150252008-09-09 20:39:27 +00003046 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, t1, X);
3047 SDValue t3 = DAG.getNode(ISD::FSUB, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003048 getF32Constant(DAG, 0x3fa22ae7));
Bill Wendling39150252008-09-09 20:39:27 +00003049 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3050 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003051 getF32Constant(DAG, 0x40525723));
Bill Wendling39150252008-09-09 20:39:27 +00003052 SDValue t6 = DAG.getNode(ISD::FMUL, MVT::f32, t5, X);
3053 SDValue t7 = DAG.getNode(ISD::FSUB, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003054 getF32Constant(DAG, 0x40aaf200));
Bill Wendling39150252008-09-09 20:39:27 +00003055 SDValue t8 = DAG.getNode(ISD::FMUL, MVT::f32, t7, X);
3056 SDValue t9 = DAG.getNode(ISD::FADD, MVT::f32, t8,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003057 getF32Constant(DAG, 0x40c39dad));
Bill Wendling3eb59402008-09-09 00:28:24 +00003058 SDValue t10 = DAG.getNode(ISD::FMUL, MVT::f32, t9, X);
Bill Wendling39150252008-09-09 20:39:27 +00003059 SDValue Log2ofMantissa = DAG.getNode(ISD::FSUB, MVT::f32, t10,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003060 getF32Constant(DAG, 0x4042902c));
Bill Wendling3eb59402008-09-09 00:28:24 +00003061
3062 result = DAG.getNode(ISD::FADD, MVT::f32, LogOfExponent, Log2ofMantissa);
3063 }
Dale Johannesen853244f2008-09-05 23:49:37 +00003064 } else {
Bill Wendling3eb59402008-09-09 00:28:24 +00003065 // No special expansion.
Dale Johannesen853244f2008-09-05 23:49:37 +00003066 result = DAG.getNode(ISD::FLOG2,
3067 getValue(I.getOperand(1)).getValueType(),
3068 getValue(I.getOperand(1)));
3069 }
Bill Wendling3eb59402008-09-09 00:28:24 +00003070
Dale Johannesen59e577f2008-09-05 18:38:42 +00003071 setValue(&I, result);
3072}
3073
Bill Wendling3eb59402008-09-09 00:28:24 +00003074/// visitLog10 - Lower a log10 intrinsic. Handles the special sequences for
3075/// limited-precision mode.
Dale Johannesen59e577f2008-09-05 18:38:42 +00003076void
3077SelectionDAGLowering::visitLog10(CallInst &I) {
3078 SDValue result;
Bill Wendling181b6272008-10-19 20:34:04 +00003079
Dale Johannesen852680a2008-09-05 21:27:19 +00003080 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
Bill Wendling3eb59402008-09-09 00:28:24 +00003081 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3082 SDValue Op = getValue(I.getOperand(1));
3083 SDValue Op1 = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, Op);
3084
Bill Wendling39150252008-09-09 20:39:27 +00003085 // Scale the exponent by log10(2) [0.30102999f].
3086 SDValue Exp = GetExponent(DAG, Op1);
3087 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, MVT::f32, Exp,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003088 getF32Constant(DAG, 0x3e9a209a));
Bill Wendling3eb59402008-09-09 00:28:24 +00003089
3090 // Get the significand and build it into a floating-point number with
Bill Wendling39150252008-09-09 20:39:27 +00003091 // exponent of 1.
3092 SDValue X = GetSignificand(DAG, Op1);
Bill Wendling3eb59402008-09-09 00:28:24 +00003093
3094 if (LimitFloatPrecision <= 6) {
Bill Wendlingbd297bc2008-09-09 18:42:23 +00003095 // For floating-point precision of 6:
3096 //
3097 // Log10ofMantissa =
3098 // -0.50419619f +
3099 // (0.60948995f - 0.10380950f * x) * x;
3100 //
3101 // error 0.0014886165, which is 6 bits
Bill Wendling39150252008-09-09 20:39:27 +00003102 SDValue t0 = DAG.getNode(ISD::FMUL, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003103 getF32Constant(DAG, 0xbdd49a13));
Bill Wendling39150252008-09-09 20:39:27 +00003104 SDValue t1 = DAG.getNode(ISD::FADD, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003105 getF32Constant(DAG, 0x3f1c0789));
Bill Wendling39150252008-09-09 20:39:27 +00003106 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, t1, X);
3107 SDValue Log10ofMantissa = DAG.getNode(ISD::FSUB, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003108 getF32Constant(DAG, 0x3f011300));
Bill Wendlingbd297bc2008-09-09 18:42:23 +00003109
3110 result = DAG.getNode(ISD::FADD, MVT::f32, LogOfExponent, Log10ofMantissa);
Bill Wendling3eb59402008-09-09 00:28:24 +00003111 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3112 // For floating-point precision of 12:
3113 //
3114 // Log10ofMantissa =
3115 // -0.64831180f +
3116 // (0.91751397f +
3117 // (-0.31664806f + 0.47637168e-1f * x) * x) * x;
3118 //
3119 // error 0.00019228036, which is better than 12 bits
Bill Wendling39150252008-09-09 20:39:27 +00003120 SDValue t0 = DAG.getNode(ISD::FMUL, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003121 getF32Constant(DAG, 0x3d431f31));
Bill Wendling39150252008-09-09 20:39:27 +00003122 SDValue t1 = DAG.getNode(ISD::FSUB, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003123 getF32Constant(DAG, 0x3ea21fb2));
Bill Wendling39150252008-09-09 20:39:27 +00003124 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, t1, X);
3125 SDValue t3 = DAG.getNode(ISD::FADD, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003126 getF32Constant(DAG, 0x3f6ae232));
Bill Wendling39150252008-09-09 20:39:27 +00003127 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3128 SDValue Log10ofMantissa = DAG.getNode(ISD::FSUB, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003129 getF32Constant(DAG, 0x3f25f7c3));
Bill Wendling3eb59402008-09-09 00:28:24 +00003130
3131 result = DAG.getNode(ISD::FADD, MVT::f32, LogOfExponent, Log10ofMantissa);
3132 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
Bill Wendlingbd297bc2008-09-09 18:42:23 +00003133 // For floating-point precision of 18:
3134 //
3135 // Log10ofMantissa =
3136 // -0.84299375f +
3137 // (1.5327582f +
3138 // (-1.0688956f +
3139 // (0.49102474f +
3140 // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
3141 //
3142 // error 0.0000037995730, which is better than 18 bits
Bill Wendling39150252008-09-09 20:39:27 +00003143 SDValue t0 = DAG.getNode(ISD::FMUL, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003144 getF32Constant(DAG, 0x3c5d51ce));
Bill Wendling39150252008-09-09 20:39:27 +00003145 SDValue t1 = DAG.getNode(ISD::FSUB, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003146 getF32Constant(DAG, 0x3e00685a));
Bill Wendling39150252008-09-09 20:39:27 +00003147 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, t1, X);
3148 SDValue t3 = DAG.getNode(ISD::FADD, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003149 getF32Constant(DAG, 0x3efb6798));
Bill Wendling39150252008-09-09 20:39:27 +00003150 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3151 SDValue t5 = DAG.getNode(ISD::FSUB, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003152 getF32Constant(DAG, 0x3f88d192));
Bill Wendling39150252008-09-09 20:39:27 +00003153 SDValue t6 = DAG.getNode(ISD::FMUL, MVT::f32, t5, X);
3154 SDValue t7 = DAG.getNode(ISD::FADD, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003155 getF32Constant(DAG, 0x3fc4316c));
Bill Wendlingbd297bc2008-09-09 18:42:23 +00003156 SDValue t8 = DAG.getNode(ISD::FMUL, MVT::f32, t7, X);
Bill Wendling39150252008-09-09 20:39:27 +00003157 SDValue Log10ofMantissa = DAG.getNode(ISD::FSUB, MVT::f32, t8,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003158 getF32Constant(DAG, 0x3f57ce70));
Bill Wendlingbd297bc2008-09-09 18:42:23 +00003159
3160 result = DAG.getNode(ISD::FADD, MVT::f32, LogOfExponent, Log10ofMantissa);
Bill Wendling3eb59402008-09-09 00:28:24 +00003161 }
Dale Johannesen852680a2008-09-05 21:27:19 +00003162 } else {
Bill Wendling3eb59402008-09-09 00:28:24 +00003163 // No special expansion.
Dale Johannesen852680a2008-09-05 21:27:19 +00003164 result = DAG.getNode(ISD::FLOG10,
3165 getValue(I.getOperand(1)).getValueType(),
3166 getValue(I.getOperand(1)));
3167 }
Bill Wendling3eb59402008-09-09 00:28:24 +00003168
Dale Johannesen59e577f2008-09-05 18:38:42 +00003169 setValue(&I, result);
3170}
3171
Bill Wendlinge10c8142008-09-09 22:39:21 +00003172/// visitExp2 - Lower an exp2 intrinsic. Handles the special sequences for
3173/// limited-precision mode.
Dale Johannesen601d3c02008-09-05 01:48:15 +00003174void
3175SelectionDAGLowering::visitExp2(CallInst &I) {
3176 SDValue result;
Bill Wendlinge10c8142008-09-09 22:39:21 +00003177
Dale Johannesen601d3c02008-09-05 01:48:15 +00003178 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
Bill Wendlinge10c8142008-09-09 22:39:21 +00003179 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3180 SDValue Op = getValue(I.getOperand(1));
3181
3182 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, MVT::i32, Op);
3183
3184 // FractionalPartOfX = x - (float)IntegerPartOfX;
3185 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, MVT::f32, IntegerPartOfX);
3186 SDValue X = DAG.getNode(ISD::FSUB, MVT::f32, Op, t1);
3187
3188 // IntegerPartOfX <<= 23;
3189 IntegerPartOfX = DAG.getNode(ISD::SHL, MVT::i32, IntegerPartOfX,
3190 DAG.getConstant(23, MVT::i32));
3191
3192 if (LimitFloatPrecision <= 6) {
3193 // For floating-point precision of 6:
3194 //
3195 // TwoToFractionalPartOfX =
3196 // 0.997535578f +
3197 // (0.735607626f + 0.252464424f * x) * x;
3198 //
3199 // error 0.0144103317, which is 6 bits
3200 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003201 getF32Constant(DAG, 0x3e814304));
Bill Wendlinge10c8142008-09-09 22:39:21 +00003202 SDValue t3 = DAG.getNode(ISD::FADD, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003203 getF32Constant(DAG, 0x3f3c50c8));
Bill Wendlinge10c8142008-09-09 22:39:21 +00003204 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3205 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003206 getF32Constant(DAG, 0x3f7f5e7e));
Bill Wendlinge10c8142008-09-09 22:39:21 +00003207 SDValue t6 = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, t5);
3208 SDValue TwoToFractionalPartOfX =
3209 DAG.getNode(ISD::ADD, MVT::i32, t6, IntegerPartOfX);
3210
3211 result = DAG.getNode(ISD::BIT_CONVERT, MVT::f32, TwoToFractionalPartOfX);
3212 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3213 // For floating-point precision of 12:
3214 //
3215 // TwoToFractionalPartOfX =
3216 // 0.999892986f +
3217 // (0.696457318f +
3218 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
3219 //
3220 // error 0.000107046256, which is 13 to 14 bits
3221 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003222 getF32Constant(DAG, 0x3da235e3));
Bill Wendlinge10c8142008-09-09 22:39:21 +00003223 SDValue t3 = DAG.getNode(ISD::FADD, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003224 getF32Constant(DAG, 0x3e65b8f3));
Bill Wendlinge10c8142008-09-09 22:39:21 +00003225 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3226 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003227 getF32Constant(DAG, 0x3f324b07));
Bill Wendlinge10c8142008-09-09 22:39:21 +00003228 SDValue t6 = DAG.getNode(ISD::FMUL, MVT::f32, t5, X);
3229 SDValue t7 = DAG.getNode(ISD::FADD, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003230 getF32Constant(DAG, 0x3f7ff8fd));
Bill Wendlinge10c8142008-09-09 22:39:21 +00003231 SDValue t8 = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, t7);
3232 SDValue TwoToFractionalPartOfX =
3233 DAG.getNode(ISD::ADD, MVT::i32, t8, IntegerPartOfX);
3234
3235 result = DAG.getNode(ISD::BIT_CONVERT, MVT::f32, TwoToFractionalPartOfX);
3236 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3237 // For floating-point precision of 18:
3238 //
3239 // TwoToFractionalPartOfX =
3240 // 0.999999982f +
3241 // (0.693148872f +
3242 // (0.240227044f +
3243 // (0.554906021e-1f +
3244 // (0.961591928e-2f +
3245 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
3246 // error 2.47208000*10^(-7), which is better than 18 bits
3247 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003248 getF32Constant(DAG, 0x3924b03e));
Bill Wendlinge10c8142008-09-09 22:39:21 +00003249 SDValue t3 = DAG.getNode(ISD::FADD, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003250 getF32Constant(DAG, 0x3ab24b87));
Bill Wendlinge10c8142008-09-09 22:39:21 +00003251 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3252 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003253 getF32Constant(DAG, 0x3c1d8c17));
Bill Wendlinge10c8142008-09-09 22:39:21 +00003254 SDValue t6 = DAG.getNode(ISD::FMUL, MVT::f32, t5, X);
3255 SDValue t7 = DAG.getNode(ISD::FADD, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003256 getF32Constant(DAG, 0x3d634a1d));
Bill Wendlinge10c8142008-09-09 22:39:21 +00003257 SDValue t8 = DAG.getNode(ISD::FMUL, MVT::f32, t7, X);
3258 SDValue t9 = DAG.getNode(ISD::FADD, MVT::f32, t8,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003259 getF32Constant(DAG, 0x3e75fe14));
Bill Wendlinge10c8142008-09-09 22:39:21 +00003260 SDValue t10 = DAG.getNode(ISD::FMUL, MVT::f32, t9, X);
3261 SDValue t11 = DAG.getNode(ISD::FADD, MVT::f32, t10,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003262 getF32Constant(DAG, 0x3f317234));
Bill Wendlinge10c8142008-09-09 22:39:21 +00003263 SDValue t12 = DAG.getNode(ISD::FMUL, MVT::f32, t11, X);
3264 SDValue t13 = DAG.getNode(ISD::FADD, MVT::f32, t12,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003265 getF32Constant(DAG, 0x3f800000));
Bill Wendlinge10c8142008-09-09 22:39:21 +00003266 SDValue t14 = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, t13);
3267 SDValue TwoToFractionalPartOfX =
3268 DAG.getNode(ISD::ADD, MVT::i32, t14, IntegerPartOfX);
3269
3270 result = DAG.getNode(ISD::BIT_CONVERT, MVT::f32, TwoToFractionalPartOfX);
3271 }
Dale Johannesen601d3c02008-09-05 01:48:15 +00003272 } else {
Bill Wendling3eb59402008-09-09 00:28:24 +00003273 // No special expansion.
Dale Johannesen601d3c02008-09-05 01:48:15 +00003274 result = DAG.getNode(ISD::FEXP2,
3275 getValue(I.getOperand(1)).getValueType(),
3276 getValue(I.getOperand(1)));
3277 }
Bill Wendlinge10c8142008-09-09 22:39:21 +00003278
Dale Johannesen601d3c02008-09-05 01:48:15 +00003279 setValue(&I, result);
3280}
3281
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003282/// visitPow - Lower a pow intrinsic. Handles the special sequences for
3283/// limited-precision mode with x == 10.0f.
3284void
3285SelectionDAGLowering::visitPow(CallInst &I) {
3286 SDValue result;
3287 Value *Val = I.getOperand(1);
3288 bool IsExp10 = false;
3289
3290 if (getValue(Val).getValueType() == MVT::f32 &&
Bill Wendling277fc242008-09-10 00:24:59 +00003291 getValue(I.getOperand(2)).getValueType() == MVT::f32 &&
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003292 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3293 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(Val))) {
3294 if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
3295 APFloat Ten(10.0f);
3296 IsExp10 = CFP->getValueAPF().bitwiseIsEqual(Ten);
3297 }
3298 }
3299 }
3300
3301 if (IsExp10 && LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3302 SDValue Op = getValue(I.getOperand(2));
3303
3304 // Put the exponent in the right bit position for later addition to the
3305 // final result:
3306 //
3307 // #define LOG2OF10 3.3219281f
3308 // IntegerPartOfX = (int32_t)(x * LOG2OF10);
3309 SDValue t0 = DAG.getNode(ISD::FMUL, MVT::f32, Op,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003310 getF32Constant(DAG, 0x40549a78));
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003311 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, MVT::i32, t0);
3312
3313 // FractionalPartOfX = x - (float)IntegerPartOfX;
3314 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, MVT::f32, IntegerPartOfX);
3315 SDValue X = DAG.getNode(ISD::FSUB, MVT::f32, t0, t1);
3316
3317 // IntegerPartOfX <<= 23;
3318 IntegerPartOfX = DAG.getNode(ISD::SHL, MVT::i32, IntegerPartOfX,
3319 DAG.getConstant(23, MVT::i32));
3320
3321 if (LimitFloatPrecision <= 6) {
3322 // For floating-point precision of 6:
3323 //
3324 // twoToFractionalPartOfX =
3325 // 0.997535578f +
3326 // (0.735607626f + 0.252464424f * x) * x;
3327 //
3328 // error 0.0144103317, which is 6 bits
3329 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003330 getF32Constant(DAG, 0x3e814304));
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003331 SDValue t3 = DAG.getNode(ISD::FADD, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003332 getF32Constant(DAG, 0x3f3c50c8));
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003333 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3334 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003335 getF32Constant(DAG, 0x3f7f5e7e));
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003336 SDValue t6 = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, t5);
3337 SDValue TwoToFractionalPartOfX =
3338 DAG.getNode(ISD::ADD, MVT::i32, t6, IntegerPartOfX);
3339
3340 result = DAG.getNode(ISD::BIT_CONVERT, MVT::f32, TwoToFractionalPartOfX);
3341 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3342 // For floating-point precision of 12:
3343 //
3344 // TwoToFractionalPartOfX =
3345 // 0.999892986f +
3346 // (0.696457318f +
3347 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
3348 //
3349 // error 0.000107046256, which is 13 to 14 bits
3350 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003351 getF32Constant(DAG, 0x3da235e3));
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003352 SDValue t3 = DAG.getNode(ISD::FADD, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003353 getF32Constant(DAG, 0x3e65b8f3));
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003354 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3355 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003356 getF32Constant(DAG, 0x3f324b07));
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003357 SDValue t6 = DAG.getNode(ISD::FMUL, MVT::f32, t5, X);
3358 SDValue t7 = DAG.getNode(ISD::FADD, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003359 getF32Constant(DAG, 0x3f7ff8fd));
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003360 SDValue t8 = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, t7);
3361 SDValue TwoToFractionalPartOfX =
3362 DAG.getNode(ISD::ADD, MVT::i32, t8, IntegerPartOfX);
3363
3364 result = DAG.getNode(ISD::BIT_CONVERT, MVT::f32, TwoToFractionalPartOfX);
3365 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3366 // For floating-point precision of 18:
3367 //
3368 // TwoToFractionalPartOfX =
3369 // 0.999999982f +
3370 // (0.693148872f +
3371 // (0.240227044f +
3372 // (0.554906021e-1f +
3373 // (0.961591928e-2f +
3374 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
3375 // error 2.47208000*10^(-7), which is better than 18 bits
3376 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003377 getF32Constant(DAG, 0x3924b03e));
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003378 SDValue t3 = DAG.getNode(ISD::FADD, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003379 getF32Constant(DAG, 0x3ab24b87));
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003380 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3381 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003382 getF32Constant(DAG, 0x3c1d8c17));
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003383 SDValue t6 = DAG.getNode(ISD::FMUL, MVT::f32, t5, X);
3384 SDValue t7 = DAG.getNode(ISD::FADD, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003385 getF32Constant(DAG, 0x3d634a1d));
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003386 SDValue t8 = DAG.getNode(ISD::FMUL, MVT::f32, t7, X);
3387 SDValue t9 = DAG.getNode(ISD::FADD, MVT::f32, t8,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003388 getF32Constant(DAG, 0x3e75fe14));
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003389 SDValue t10 = DAG.getNode(ISD::FMUL, MVT::f32, t9, X);
3390 SDValue t11 = DAG.getNode(ISD::FADD, MVT::f32, t10,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003391 getF32Constant(DAG, 0x3f317234));
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003392 SDValue t12 = DAG.getNode(ISD::FMUL, MVT::f32, t11, X);
3393 SDValue t13 = DAG.getNode(ISD::FADD, MVT::f32, t12,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003394 getF32Constant(DAG, 0x3f800000));
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003395 SDValue t14 = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, t13);
3396 SDValue TwoToFractionalPartOfX =
3397 DAG.getNode(ISD::ADD, MVT::i32, t14, IntegerPartOfX);
3398
3399 result = DAG.getNode(ISD::BIT_CONVERT, MVT::f32, TwoToFractionalPartOfX);
3400 }
3401 } else {
3402 // No special expansion.
3403 result = DAG.getNode(ISD::FPOW,
3404 getValue(I.getOperand(1)).getValueType(),
3405 getValue(I.getOperand(1)),
3406 getValue(I.getOperand(2)));
3407 }
3408
3409 setValue(&I, result);
3410}
3411
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003412/// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
3413/// we want to emit this as a call to a named external function, return the name
3414/// otherwise lower it and return null.
3415const char *
3416SelectionDAGLowering::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
3417 switch (Intrinsic) {
3418 default:
3419 // By default, turn this into a target intrinsic node.
3420 visitTargetIntrinsic(I, Intrinsic);
3421 return 0;
3422 case Intrinsic::vastart: visitVAStart(I); return 0;
3423 case Intrinsic::vaend: visitVAEnd(I); return 0;
3424 case Intrinsic::vacopy: visitVACopy(I); return 0;
3425 case Intrinsic::returnaddress:
3426 setValue(&I, DAG.getNode(ISD::RETURNADDR, TLI.getPointerTy(),
3427 getValue(I.getOperand(1))));
3428 return 0;
Bill Wendlingd5d81912008-09-26 22:10:44 +00003429 case Intrinsic::frameaddress:
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003430 setValue(&I, DAG.getNode(ISD::FRAMEADDR, TLI.getPointerTy(),
3431 getValue(I.getOperand(1))));
3432 return 0;
3433 case Intrinsic::setjmp:
3434 return "_setjmp"+!TLI.usesUnderscoreSetJmp();
3435 break;
3436 case Intrinsic::longjmp:
3437 return "_longjmp"+!TLI.usesUnderscoreLongJmp();
3438 break;
3439 case Intrinsic::memcpy_i32:
3440 case Intrinsic::memcpy_i64: {
3441 SDValue Op1 = getValue(I.getOperand(1));
3442 SDValue Op2 = getValue(I.getOperand(2));
3443 SDValue Op3 = getValue(I.getOperand(3));
3444 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
3445 DAG.setRoot(DAG.getMemcpy(getRoot(), Op1, Op2, Op3, Align, false,
3446 I.getOperand(1), 0, I.getOperand(2), 0));
3447 return 0;
3448 }
3449 case Intrinsic::memset_i32:
3450 case Intrinsic::memset_i64: {
3451 SDValue Op1 = getValue(I.getOperand(1));
3452 SDValue Op2 = getValue(I.getOperand(2));
3453 SDValue Op3 = getValue(I.getOperand(3));
3454 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
3455 DAG.setRoot(DAG.getMemset(getRoot(), Op1, Op2, Op3, Align,
3456 I.getOperand(1), 0));
3457 return 0;
3458 }
3459 case Intrinsic::memmove_i32:
3460 case Intrinsic::memmove_i64: {
3461 SDValue Op1 = getValue(I.getOperand(1));
3462 SDValue Op2 = getValue(I.getOperand(2));
3463 SDValue Op3 = getValue(I.getOperand(3));
3464 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
3465
3466 // If the source and destination are known to not be aliases, we can
3467 // lower memmove as memcpy.
3468 uint64_t Size = -1ULL;
3469 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op3))
Dan Gohmanf5aeb1a2008-09-12 16:56:44 +00003470 Size = C->getZExtValue();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003471 if (AA->alias(I.getOperand(1), Size, I.getOperand(2), Size) ==
3472 AliasAnalysis::NoAlias) {
3473 DAG.setRoot(DAG.getMemcpy(getRoot(), Op1, Op2, Op3, Align, false,
3474 I.getOperand(1), 0, I.getOperand(2), 0));
3475 return 0;
3476 }
3477
3478 DAG.setRoot(DAG.getMemmove(getRoot(), Op1, Op2, Op3, Align,
3479 I.getOperand(1), 0, I.getOperand(2), 0));
3480 return 0;
3481 }
3482 case Intrinsic::dbg_stoppoint: {
3483 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3484 DbgStopPointInst &SPI = cast<DbgStopPointInst>(I);
3485 if (MMI && SPI.getContext() && MMI->Verify(SPI.getContext())) {
3486 DebugInfoDesc *DD = MMI->getDescFor(SPI.getContext());
3487 assert(DD && "Not a debug information descriptor");
3488 DAG.setRoot(DAG.getDbgStopPoint(getRoot(),
3489 SPI.getLine(),
3490 SPI.getColumn(),
3491 cast<CompileUnitDesc>(DD)));
3492 }
3493
3494 return 0;
3495 }
3496 case Intrinsic::dbg_region_start: {
3497 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3498 DbgRegionStartInst &RSI = cast<DbgRegionStartInst>(I);
3499 if (MMI && RSI.getContext() && MMI->Verify(RSI.getContext())) {
3500 unsigned LabelID = MMI->RecordRegionStart(RSI.getContext());
3501 DAG.setRoot(DAG.getLabel(ISD::DBG_LABEL, getRoot(), LabelID));
3502 }
3503
3504 return 0;
3505 }
3506 case Intrinsic::dbg_region_end: {
3507 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3508 DbgRegionEndInst &REI = cast<DbgRegionEndInst>(I);
3509 if (MMI && REI.getContext() && MMI->Verify(REI.getContext())) {
3510 unsigned LabelID = MMI->RecordRegionEnd(REI.getContext());
3511 DAG.setRoot(DAG.getLabel(ISD::DBG_LABEL, getRoot(), LabelID));
3512 }
3513
3514 return 0;
3515 }
3516 case Intrinsic::dbg_func_start: {
3517 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3518 if (!MMI) return 0;
3519 DbgFuncStartInst &FSI = cast<DbgFuncStartInst>(I);
3520 Value *SP = FSI.getSubprogram();
3521 if (SP && MMI->Verify(SP)) {
3522 // llvm.dbg.func.start implicitly defines a dbg_stoppoint which is
3523 // what (most?) gdb expects.
3524 DebugInfoDesc *DD = MMI->getDescFor(SP);
3525 assert(DD && "Not a debug information descriptor");
3526 SubprogramDesc *Subprogram = cast<SubprogramDesc>(DD);
3527 const CompileUnitDesc *CompileUnit = Subprogram->getFile();
3528 unsigned SrcFile = MMI->RecordSource(CompileUnit);
3529 // Record the source line but does create a label. It will be emitted
3530 // at asm emission time.
3531 MMI->RecordSourceLine(Subprogram->getLine(), 0, SrcFile);
3532 }
3533
3534 return 0;
3535 }
3536 case Intrinsic::dbg_declare: {
3537 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3538 DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
3539 Value *Variable = DI.getVariable();
3540 if (MMI && Variable && MMI->Verify(Variable))
3541 DAG.setRoot(DAG.getNode(ISD::DECLARE, MVT::Other, getRoot(),
3542 getValue(DI.getAddress()), getValue(Variable)));
3543 return 0;
3544 }
3545
3546 case Intrinsic::eh_exception: {
3547 if (!CurMBB->isLandingPad()) {
3548 // FIXME: Mark exception register as live in. Hack for PR1508.
3549 unsigned Reg = TLI.getExceptionAddressRegister();
3550 if (Reg) CurMBB->addLiveIn(Reg);
3551 }
3552 // Insert the EXCEPTIONADDR instruction.
3553 SDVTList VTs = DAG.getVTList(TLI.getPointerTy(), MVT::Other);
3554 SDValue Ops[1];
3555 Ops[0] = DAG.getRoot();
3556 SDValue Op = DAG.getNode(ISD::EXCEPTIONADDR, VTs, Ops, 1);
3557 setValue(&I, Op);
3558 DAG.setRoot(Op.getValue(1));
3559 return 0;
3560 }
3561
3562 case Intrinsic::eh_selector_i32:
3563 case Intrinsic::eh_selector_i64: {
3564 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3565 MVT VT = (Intrinsic == Intrinsic::eh_selector_i32 ?
3566 MVT::i32 : MVT::i64);
3567
3568 if (MMI) {
3569 if (CurMBB->isLandingPad())
3570 AddCatchInfo(I, MMI, CurMBB);
3571 else {
3572#ifndef NDEBUG
3573 FuncInfo.CatchInfoLost.insert(&I);
3574#endif
3575 // FIXME: Mark exception selector register as live in. Hack for PR1508.
3576 unsigned Reg = TLI.getExceptionSelectorRegister();
3577 if (Reg) CurMBB->addLiveIn(Reg);
3578 }
3579
3580 // Insert the EHSELECTION instruction.
3581 SDVTList VTs = DAG.getVTList(VT, MVT::Other);
3582 SDValue Ops[2];
3583 Ops[0] = getValue(I.getOperand(1));
3584 Ops[1] = getRoot();
3585 SDValue Op = DAG.getNode(ISD::EHSELECTION, VTs, Ops, 2);
3586 setValue(&I, Op);
3587 DAG.setRoot(Op.getValue(1));
3588 } else {
3589 setValue(&I, DAG.getConstant(0, VT));
3590 }
3591
3592 return 0;
3593 }
3594
3595 case Intrinsic::eh_typeid_for_i32:
3596 case Intrinsic::eh_typeid_for_i64: {
3597 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3598 MVT VT = (Intrinsic == Intrinsic::eh_typeid_for_i32 ?
3599 MVT::i32 : MVT::i64);
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00003600
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003601 if (MMI) {
3602 // Find the type id for the given typeinfo.
3603 GlobalVariable *GV = ExtractTypeInfo(I.getOperand(1));
3604
3605 unsigned TypeID = MMI->getTypeIDFor(GV);
3606 setValue(&I, DAG.getConstant(TypeID, VT));
3607 } else {
3608 // Return something different to eh_selector.
3609 setValue(&I, DAG.getConstant(1, VT));
3610 }
3611
3612 return 0;
3613 }
3614
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00003615 case Intrinsic::eh_return_i32:
3616 case Intrinsic::eh_return_i64:
3617 if (MachineModuleInfo *MMI = DAG.getMachineModuleInfo()) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003618 MMI->setCallsEHReturn(true);
3619 DAG.setRoot(DAG.getNode(ISD::EH_RETURN,
3620 MVT::Other,
3621 getControlRoot(),
3622 getValue(I.getOperand(1)),
3623 getValue(I.getOperand(2))));
3624 } else {
3625 setValue(&I, DAG.getConstant(0, TLI.getPointerTy()));
3626 }
3627
3628 return 0;
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00003629 case Intrinsic::eh_unwind_init:
3630 if (MachineModuleInfo *MMI = DAG.getMachineModuleInfo()) {
3631 MMI->setCallsUnwindInit(true);
3632 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003633
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00003634 return 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003635
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00003636 case Intrinsic::eh_dwarf_cfa: {
3637 MVT VT = getValue(I.getOperand(1)).getValueType();
3638 SDValue CfaArg;
3639 if (VT.bitsGT(TLI.getPointerTy()))
3640 CfaArg = DAG.getNode(ISD::TRUNCATE,
3641 TLI.getPointerTy(), getValue(I.getOperand(1)));
3642 else
3643 CfaArg = DAG.getNode(ISD::SIGN_EXTEND,
3644 TLI.getPointerTy(), getValue(I.getOperand(1)));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003645
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00003646 SDValue Offset = DAG.getNode(ISD::ADD,
3647 TLI.getPointerTy(),
3648 DAG.getNode(ISD::FRAME_TO_ARGS_OFFSET,
3649 TLI.getPointerTy()),
3650 CfaArg);
3651 setValue(&I, DAG.getNode(ISD::ADD,
3652 TLI.getPointerTy(),
3653 DAG.getNode(ISD::FRAMEADDR,
3654 TLI.getPointerTy(),
3655 DAG.getConstant(0,
3656 TLI.getPointerTy())),
3657 Offset));
3658 return 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003659 }
3660
3661 case Intrinsic::sqrt:
3662 setValue(&I, DAG.getNode(ISD::FSQRT,
3663 getValue(I.getOperand(1)).getValueType(),
3664 getValue(I.getOperand(1))));
3665 return 0;
3666 case Intrinsic::powi:
3667 setValue(&I, DAG.getNode(ISD::FPOWI,
3668 getValue(I.getOperand(1)).getValueType(),
3669 getValue(I.getOperand(1)),
3670 getValue(I.getOperand(2))));
3671 return 0;
3672 case Intrinsic::sin:
3673 setValue(&I, DAG.getNode(ISD::FSIN,
3674 getValue(I.getOperand(1)).getValueType(),
3675 getValue(I.getOperand(1))));
3676 return 0;
3677 case Intrinsic::cos:
3678 setValue(&I, DAG.getNode(ISD::FCOS,
3679 getValue(I.getOperand(1)).getValueType(),
3680 getValue(I.getOperand(1))));
3681 return 0;
Dale Johannesen7794f2a2008-09-04 00:47:13 +00003682 case Intrinsic::log:
Dale Johannesen59e577f2008-09-05 18:38:42 +00003683 visitLog(I);
Dale Johannesen7794f2a2008-09-04 00:47:13 +00003684 return 0;
3685 case Intrinsic::log2:
Dale Johannesen59e577f2008-09-05 18:38:42 +00003686 visitLog2(I);
Dale Johannesen7794f2a2008-09-04 00:47:13 +00003687 return 0;
3688 case Intrinsic::log10:
Dale Johannesen59e577f2008-09-05 18:38:42 +00003689 visitLog10(I);
Dale Johannesen7794f2a2008-09-04 00:47:13 +00003690 return 0;
3691 case Intrinsic::exp:
Dale Johannesen59e577f2008-09-05 18:38:42 +00003692 visitExp(I);
Dale Johannesen7794f2a2008-09-04 00:47:13 +00003693 return 0;
3694 case Intrinsic::exp2:
Dale Johannesen601d3c02008-09-05 01:48:15 +00003695 visitExp2(I);
Dale Johannesen7794f2a2008-09-04 00:47:13 +00003696 return 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003697 case Intrinsic::pow:
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003698 visitPow(I);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003699 return 0;
3700 case Intrinsic::pcmarker: {
3701 SDValue Tmp = getValue(I.getOperand(1));
3702 DAG.setRoot(DAG.getNode(ISD::PCMARKER, MVT::Other, getRoot(), Tmp));
3703 return 0;
3704 }
3705 case Intrinsic::readcyclecounter: {
3706 SDValue Op = getRoot();
3707 SDValue Tmp = DAG.getNode(ISD::READCYCLECOUNTER,
3708 DAG.getNodeValueTypes(MVT::i64, MVT::Other), 2,
3709 &Op, 1);
3710 setValue(&I, Tmp);
3711 DAG.setRoot(Tmp.getValue(1));
3712 return 0;
3713 }
3714 case Intrinsic::part_select: {
3715 // Currently not implemented: just abort
3716 assert(0 && "part_select intrinsic not implemented");
3717 abort();
3718 }
3719 case Intrinsic::part_set: {
3720 // Currently not implemented: just abort
3721 assert(0 && "part_set intrinsic not implemented");
3722 abort();
3723 }
3724 case Intrinsic::bswap:
3725 setValue(&I, DAG.getNode(ISD::BSWAP,
3726 getValue(I.getOperand(1)).getValueType(),
3727 getValue(I.getOperand(1))));
3728 return 0;
3729 case Intrinsic::cttz: {
3730 SDValue Arg = getValue(I.getOperand(1));
3731 MVT Ty = Arg.getValueType();
3732 SDValue result = DAG.getNode(ISD::CTTZ, Ty, Arg);
3733 setValue(&I, result);
3734 return 0;
3735 }
3736 case Intrinsic::ctlz: {
3737 SDValue Arg = getValue(I.getOperand(1));
3738 MVT Ty = Arg.getValueType();
3739 SDValue result = DAG.getNode(ISD::CTLZ, Ty, Arg);
3740 setValue(&I, result);
3741 return 0;
3742 }
3743 case Intrinsic::ctpop: {
3744 SDValue Arg = getValue(I.getOperand(1));
3745 MVT Ty = Arg.getValueType();
3746 SDValue result = DAG.getNode(ISD::CTPOP, Ty, Arg);
3747 setValue(&I, result);
3748 return 0;
3749 }
3750 case Intrinsic::stacksave: {
3751 SDValue Op = getRoot();
3752 SDValue Tmp = DAG.getNode(ISD::STACKSAVE,
3753 DAG.getNodeValueTypes(TLI.getPointerTy(), MVT::Other), 2, &Op, 1);
3754 setValue(&I, Tmp);
3755 DAG.setRoot(Tmp.getValue(1));
3756 return 0;
3757 }
3758 case Intrinsic::stackrestore: {
3759 SDValue Tmp = getValue(I.getOperand(1));
3760 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, MVT::Other, getRoot(), Tmp));
3761 return 0;
3762 }
3763 case Intrinsic::var_annotation:
3764 // Discard annotate attributes
3765 return 0;
3766
3767 case Intrinsic::init_trampoline: {
3768 const Function *F = cast<Function>(I.getOperand(2)->stripPointerCasts());
3769
3770 SDValue Ops[6];
3771 Ops[0] = getRoot();
3772 Ops[1] = getValue(I.getOperand(1));
3773 Ops[2] = getValue(I.getOperand(2));
3774 Ops[3] = getValue(I.getOperand(3));
3775 Ops[4] = DAG.getSrcValue(I.getOperand(1));
3776 Ops[5] = DAG.getSrcValue(F);
3777
3778 SDValue Tmp = DAG.getNode(ISD::TRAMPOLINE,
3779 DAG.getNodeValueTypes(TLI.getPointerTy(),
3780 MVT::Other), 2,
3781 Ops, 6);
3782
3783 setValue(&I, Tmp);
3784 DAG.setRoot(Tmp.getValue(1));
3785 return 0;
3786 }
3787
3788 case Intrinsic::gcroot:
3789 if (GFI) {
3790 Value *Alloca = I.getOperand(1);
3791 Constant *TypeMap = cast<Constant>(I.getOperand(2));
3792
3793 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
3794 GFI->addStackRoot(FI->getIndex(), TypeMap);
3795 }
3796 return 0;
3797
3798 case Intrinsic::gcread:
3799 case Intrinsic::gcwrite:
3800 assert(0 && "GC failed to lower gcread/gcwrite intrinsics!");
3801 return 0;
3802
3803 case Intrinsic::flt_rounds: {
3804 setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, MVT::i32));
3805 return 0;
3806 }
3807
3808 case Intrinsic::trap: {
3809 DAG.setRoot(DAG.getNode(ISD::TRAP, MVT::Other, getRoot()));
3810 return 0;
3811 }
3812 case Intrinsic::prefetch: {
3813 SDValue Ops[4];
3814 Ops[0] = getRoot();
3815 Ops[1] = getValue(I.getOperand(1));
3816 Ops[2] = getValue(I.getOperand(2));
3817 Ops[3] = getValue(I.getOperand(3));
3818 DAG.setRoot(DAG.getNode(ISD::PREFETCH, MVT::Other, &Ops[0], 4));
3819 return 0;
3820 }
3821
3822 case Intrinsic::memory_barrier: {
3823 SDValue Ops[6];
3824 Ops[0] = getRoot();
3825 for (int x = 1; x < 6; ++x)
3826 Ops[x] = getValue(I.getOperand(x));
3827
3828 DAG.setRoot(DAG.getNode(ISD::MEMBARRIER, MVT::Other, &Ops[0], 6));
3829 return 0;
3830 }
3831 case Intrinsic::atomic_cmp_swap: {
3832 SDValue Root = getRoot();
3833 SDValue L;
3834 switch (getValue(I.getOperand(2)).getValueType().getSimpleVT()) {
3835 case MVT::i8:
3836 L = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP_8, Root,
3837 getValue(I.getOperand(1)),
3838 getValue(I.getOperand(2)),
3839 getValue(I.getOperand(3)),
3840 I.getOperand(1));
3841 break;
3842 case MVT::i16:
3843 L = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP_16, Root,
3844 getValue(I.getOperand(1)),
3845 getValue(I.getOperand(2)),
3846 getValue(I.getOperand(3)),
3847 I.getOperand(1));
3848 break;
3849 case MVT::i32:
3850 L = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP_32, Root,
3851 getValue(I.getOperand(1)),
3852 getValue(I.getOperand(2)),
3853 getValue(I.getOperand(3)),
3854 I.getOperand(1));
3855 break;
3856 case MVT::i64:
3857 L = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP_64, Root,
3858 getValue(I.getOperand(1)),
3859 getValue(I.getOperand(2)),
3860 getValue(I.getOperand(3)),
3861 I.getOperand(1));
3862 break;
3863 default:
3864 assert(0 && "Invalid atomic type");
3865 abort();
3866 }
3867 setValue(&I, L);
3868 DAG.setRoot(L.getValue(1));
3869 return 0;
3870 }
3871 case Intrinsic::atomic_load_add:
3872 switch (getValue(I.getOperand(2)).getValueType().getSimpleVT()) {
3873 case MVT::i8:
3874 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_ADD_8);
3875 case MVT::i16:
3876 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_ADD_16);
3877 case MVT::i32:
3878 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_ADD_32);
3879 case MVT::i64:
3880 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_ADD_64);
3881 default:
3882 assert(0 && "Invalid atomic type");
3883 abort();
3884 }
3885 case Intrinsic::atomic_load_sub:
3886 switch (getValue(I.getOperand(2)).getValueType().getSimpleVT()) {
3887 case MVT::i8:
3888 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_SUB_8);
3889 case MVT::i16:
3890 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_SUB_16);
3891 case MVT::i32:
3892 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_SUB_32);
3893 case MVT::i64:
3894 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_SUB_64);
3895 default:
3896 assert(0 && "Invalid atomic type");
3897 abort();
3898 }
3899 case Intrinsic::atomic_load_or:
3900 switch (getValue(I.getOperand(2)).getValueType().getSimpleVT()) {
3901 case MVT::i8:
3902 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_OR_8);
3903 case MVT::i16:
3904 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_OR_16);
3905 case MVT::i32:
3906 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_OR_32);
3907 case MVT::i64:
3908 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_OR_64);
3909 default:
3910 assert(0 && "Invalid atomic type");
3911 abort();
3912 }
3913 case Intrinsic::atomic_load_xor:
3914 switch (getValue(I.getOperand(2)).getValueType().getSimpleVT()) {
3915 case MVT::i8:
3916 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_XOR_8);
3917 case MVT::i16:
3918 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_XOR_16);
3919 case MVT::i32:
3920 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_XOR_32);
3921 case MVT::i64:
3922 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_XOR_64);
3923 default:
3924 assert(0 && "Invalid atomic type");
3925 abort();
3926 }
3927 case Intrinsic::atomic_load_and:
3928 switch (getValue(I.getOperand(2)).getValueType().getSimpleVT()) {
3929 case MVT::i8:
3930 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_AND_8);
3931 case MVT::i16:
3932 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_AND_16);
3933 case MVT::i32:
3934 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_AND_32);
3935 case MVT::i64:
3936 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_AND_64);
3937 default:
3938 assert(0 && "Invalid atomic type");
3939 abort();
3940 }
3941 case Intrinsic::atomic_load_nand:
3942 switch (getValue(I.getOperand(2)).getValueType().getSimpleVT()) {
3943 case MVT::i8:
3944 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_NAND_8);
3945 case MVT::i16:
3946 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_NAND_16);
3947 case MVT::i32:
3948 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_NAND_32);
3949 case MVT::i64:
3950 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_NAND_64);
3951 default:
3952 assert(0 && "Invalid atomic type");
3953 abort();
3954 }
3955 case Intrinsic::atomic_load_max:
3956 switch (getValue(I.getOperand(2)).getValueType().getSimpleVT()) {
3957 case MVT::i8:
3958 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MAX_8);
3959 case MVT::i16:
3960 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MAX_16);
3961 case MVT::i32:
3962 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MAX_32);
3963 case MVT::i64:
3964 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MAX_64);
3965 default:
3966 assert(0 && "Invalid atomic type");
3967 abort();
3968 }
3969 case Intrinsic::atomic_load_min:
3970 switch (getValue(I.getOperand(2)).getValueType().getSimpleVT()) {
3971 case MVT::i8:
3972 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MIN_8);
3973 case MVT::i16:
3974 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MIN_16);
3975 case MVT::i32:
3976 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MIN_32);
3977 case MVT::i64:
3978 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MIN_64);
3979 default:
3980 assert(0 && "Invalid atomic type");
3981 abort();
3982 }
3983 case Intrinsic::atomic_load_umin:
3984 switch (getValue(I.getOperand(2)).getValueType().getSimpleVT()) {
3985 case MVT::i8:
3986 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMIN_8);
3987 case MVT::i16:
3988 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMIN_16);
3989 case MVT::i32:
3990 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMIN_32);
3991 case MVT::i64:
3992 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMIN_64);
3993 default:
3994 assert(0 && "Invalid atomic type");
3995 abort();
3996 }
3997 case Intrinsic::atomic_load_umax:
3998 switch (getValue(I.getOperand(2)).getValueType().getSimpleVT()) {
3999 case MVT::i8:
4000 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMAX_8);
4001 case MVT::i16:
4002 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMAX_16);
4003 case MVT::i32:
4004 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMAX_32);
4005 case MVT::i64:
4006 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMAX_64);
4007 default:
4008 assert(0 && "Invalid atomic type");
4009 abort();
4010 }
4011 case Intrinsic::atomic_swap:
4012 switch (getValue(I.getOperand(2)).getValueType().getSimpleVT()) {
4013 case MVT::i8:
4014 return implVisitBinaryAtomic(I, ISD::ATOMIC_SWAP_8);
4015 case MVT::i16:
4016 return implVisitBinaryAtomic(I, ISD::ATOMIC_SWAP_16);
4017 case MVT::i32:
4018 return implVisitBinaryAtomic(I, ISD::ATOMIC_SWAP_32);
4019 case MVT::i64:
4020 return implVisitBinaryAtomic(I, ISD::ATOMIC_SWAP_64);
4021 default:
4022 assert(0 && "Invalid atomic type");
4023 abort();
4024 }
4025 }
4026}
4027
4028
4029void SelectionDAGLowering::LowerCallTo(CallSite CS, SDValue Callee,
4030 bool IsTailCall,
4031 MachineBasicBlock *LandingPad) {
4032 const PointerType *PT = cast<PointerType>(CS.getCalledValue()->getType());
4033 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
4034 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
4035 unsigned BeginLabel = 0, EndLabel = 0;
4036
4037 TargetLowering::ArgListTy Args;
4038 TargetLowering::ArgListEntry Entry;
4039 Args.reserve(CS.arg_size());
4040 for (CallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
4041 i != e; ++i) {
4042 SDValue ArgNode = getValue(*i);
4043 Entry.Node = ArgNode; Entry.Ty = (*i)->getType();
4044
4045 unsigned attrInd = i - CS.arg_begin() + 1;
Devang Patel05988662008-09-25 21:00:45 +00004046 Entry.isSExt = CS.paramHasAttr(attrInd, Attribute::SExt);
4047 Entry.isZExt = CS.paramHasAttr(attrInd, Attribute::ZExt);
4048 Entry.isInReg = CS.paramHasAttr(attrInd, Attribute::InReg);
4049 Entry.isSRet = CS.paramHasAttr(attrInd, Attribute::StructRet);
4050 Entry.isNest = CS.paramHasAttr(attrInd, Attribute::Nest);
4051 Entry.isByVal = CS.paramHasAttr(attrInd, Attribute::ByVal);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004052 Entry.Alignment = CS.getParamAlignment(attrInd);
4053 Args.push_back(Entry);
4054 }
4055
4056 if (LandingPad && MMI) {
4057 // Insert a label before the invoke call to mark the try range. This can be
4058 // used to detect deletion of the invoke via the MachineModuleInfo.
4059 BeginLabel = MMI->NextLabelID();
4060 // Both PendingLoads and PendingExports must be flushed here;
4061 // this call might not return.
4062 (void)getRoot();
4063 DAG.setRoot(DAG.getLabel(ISD::EH_LABEL, getControlRoot(), BeginLabel));
4064 }
4065
4066 std::pair<SDValue,SDValue> Result =
4067 TLI.LowerCallTo(getRoot(), CS.getType(),
Devang Patel05988662008-09-25 21:00:45 +00004068 CS.paramHasAttr(0, Attribute::SExt),
Dale Johannesen86098bd2008-09-26 19:31:26 +00004069 CS.paramHasAttr(0, Attribute::ZExt), FTy->isVarArg(),
4070 CS.paramHasAttr(0, Attribute::InReg),
4071 CS.getCallingConv(),
Dan Gohman1937e2f2008-09-16 01:42:28 +00004072 IsTailCall && PerformTailCallOpt,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004073 Callee, Args, DAG);
4074 if (CS.getType() != Type::VoidTy)
4075 setValue(CS.getInstruction(), Result.first);
4076 DAG.setRoot(Result.second);
4077
4078 if (LandingPad && MMI) {
4079 // Insert a label at the end of the invoke call to mark the try range. This
4080 // can be used to detect deletion of the invoke via the MachineModuleInfo.
4081 EndLabel = MMI->NextLabelID();
4082 DAG.setRoot(DAG.getLabel(ISD::EH_LABEL, getRoot(), EndLabel));
4083
4084 // Inform MachineModuleInfo of range.
4085 MMI->addInvoke(LandingPad, BeginLabel, EndLabel);
4086 }
4087}
4088
4089
4090void SelectionDAGLowering::visitCall(CallInst &I) {
4091 const char *RenameFn = 0;
4092 if (Function *F = I.getCalledFunction()) {
4093 if (F->isDeclaration()) {
4094 if (unsigned IID = F->getIntrinsicID()) {
4095 RenameFn = visitIntrinsicCall(I, IID);
4096 if (!RenameFn)
4097 return;
4098 }
4099 }
4100
4101 // Check for well-known libc/libm calls. If the function is internal, it
4102 // can't be a library call.
4103 unsigned NameLen = F->getNameLen();
4104 if (!F->hasInternalLinkage() && NameLen) {
4105 const char *NameStr = F->getNameStart();
4106 if (NameStr[0] == 'c' &&
4107 ((NameLen == 8 && !strcmp(NameStr, "copysign")) ||
4108 (NameLen == 9 && !strcmp(NameStr, "copysignf")))) {
4109 if (I.getNumOperands() == 3 && // Basic sanity checks.
4110 I.getOperand(1)->getType()->isFloatingPoint() &&
4111 I.getType() == I.getOperand(1)->getType() &&
4112 I.getType() == I.getOperand(2)->getType()) {
4113 SDValue LHS = getValue(I.getOperand(1));
4114 SDValue RHS = getValue(I.getOperand(2));
4115 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, LHS.getValueType(),
4116 LHS, RHS));
4117 return;
4118 }
4119 } else if (NameStr[0] == 'f' &&
4120 ((NameLen == 4 && !strcmp(NameStr, "fabs")) ||
4121 (NameLen == 5 && !strcmp(NameStr, "fabsf")) ||
4122 (NameLen == 5 && !strcmp(NameStr, "fabsl")))) {
4123 if (I.getNumOperands() == 2 && // Basic sanity checks.
4124 I.getOperand(1)->getType()->isFloatingPoint() &&
4125 I.getType() == I.getOperand(1)->getType()) {
4126 SDValue Tmp = getValue(I.getOperand(1));
4127 setValue(&I, DAG.getNode(ISD::FABS, Tmp.getValueType(), Tmp));
4128 return;
4129 }
4130 } else if (NameStr[0] == 's' &&
4131 ((NameLen == 3 && !strcmp(NameStr, "sin")) ||
4132 (NameLen == 4 && !strcmp(NameStr, "sinf")) ||
4133 (NameLen == 4 && !strcmp(NameStr, "sinl")))) {
4134 if (I.getNumOperands() == 2 && // Basic sanity checks.
4135 I.getOperand(1)->getType()->isFloatingPoint() &&
4136 I.getType() == I.getOperand(1)->getType()) {
4137 SDValue Tmp = getValue(I.getOperand(1));
4138 setValue(&I, DAG.getNode(ISD::FSIN, Tmp.getValueType(), Tmp));
4139 return;
4140 }
4141 } else if (NameStr[0] == 'c' &&
4142 ((NameLen == 3 && !strcmp(NameStr, "cos")) ||
4143 (NameLen == 4 && !strcmp(NameStr, "cosf")) ||
4144 (NameLen == 4 && !strcmp(NameStr, "cosl")))) {
4145 if (I.getNumOperands() == 2 && // Basic sanity checks.
4146 I.getOperand(1)->getType()->isFloatingPoint() &&
4147 I.getType() == I.getOperand(1)->getType()) {
4148 SDValue Tmp = getValue(I.getOperand(1));
4149 setValue(&I, DAG.getNode(ISD::FCOS, Tmp.getValueType(), Tmp));
4150 return;
4151 }
4152 }
4153 }
4154 } else if (isa<InlineAsm>(I.getOperand(0))) {
4155 visitInlineAsm(&I);
4156 return;
4157 }
4158
4159 SDValue Callee;
4160 if (!RenameFn)
4161 Callee = getValue(I.getOperand(0));
4162 else
Bill Wendling056292f2008-09-16 21:48:12 +00004163 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004164
4165 LowerCallTo(&I, Callee, I.isTailCall());
4166}
4167
4168
4169/// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
4170/// this value and returns the result as a ValueVT value. This uses
4171/// Chain/Flag as the input and updates them for the output Chain/Flag.
4172/// If the Flag pointer is NULL, no flag is used.
4173SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
4174 SDValue &Chain,
4175 SDValue *Flag) const {
4176 // Assemble the legal parts into the final values.
4177 SmallVector<SDValue, 4> Values(ValueVTs.size());
4178 SmallVector<SDValue, 8> Parts;
4179 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
4180 // Copy the legal parts from the registers.
4181 MVT ValueVT = ValueVTs[Value];
4182 unsigned NumRegs = TLI->getNumRegisters(ValueVT);
4183 MVT RegisterVT = RegVTs[Value];
4184
4185 Parts.resize(NumRegs);
4186 for (unsigned i = 0; i != NumRegs; ++i) {
4187 SDValue P;
4188 if (Flag == 0)
4189 P = DAG.getCopyFromReg(Chain, Regs[Part+i], RegisterVT);
4190 else {
4191 P = DAG.getCopyFromReg(Chain, Regs[Part+i], RegisterVT, *Flag);
4192 *Flag = P.getValue(2);
4193 }
4194 Chain = P.getValue(1);
4195
4196 // If the source register was virtual and if we know something about it,
4197 // add an assert node.
4198 if (TargetRegisterInfo::isVirtualRegister(Regs[Part+i]) &&
4199 RegisterVT.isInteger() && !RegisterVT.isVector()) {
4200 unsigned SlotNo = Regs[Part+i]-TargetRegisterInfo::FirstVirtualRegister;
4201 FunctionLoweringInfo &FLI = DAG.getFunctionLoweringInfo();
4202 if (FLI.LiveOutRegInfo.size() > SlotNo) {
4203 FunctionLoweringInfo::LiveOutInfo &LOI = FLI.LiveOutRegInfo[SlotNo];
4204
4205 unsigned RegSize = RegisterVT.getSizeInBits();
4206 unsigned NumSignBits = LOI.NumSignBits;
4207 unsigned NumZeroBits = LOI.KnownZero.countLeadingOnes();
4208
4209 // FIXME: We capture more information than the dag can represent. For
4210 // now, just use the tightest assertzext/assertsext possible.
4211 bool isSExt = true;
4212 MVT FromVT(MVT::Other);
4213 if (NumSignBits == RegSize)
4214 isSExt = true, FromVT = MVT::i1; // ASSERT SEXT 1
4215 else if (NumZeroBits >= RegSize-1)
4216 isSExt = false, FromVT = MVT::i1; // ASSERT ZEXT 1
4217 else if (NumSignBits > RegSize-8)
4218 isSExt = true, FromVT = MVT::i8; // ASSERT SEXT 8
4219 else if (NumZeroBits >= RegSize-9)
4220 isSExt = false, FromVT = MVT::i8; // ASSERT ZEXT 8
4221 else if (NumSignBits > RegSize-16)
Bill Wendling181b6272008-10-19 20:34:04 +00004222 isSExt = true, FromVT = MVT::i16; // ASSERT SEXT 16
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004223 else if (NumZeroBits >= RegSize-17)
Bill Wendling181b6272008-10-19 20:34:04 +00004224 isSExt = false, FromVT = MVT::i16; // ASSERT ZEXT 16
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004225 else if (NumSignBits > RegSize-32)
Bill Wendling181b6272008-10-19 20:34:04 +00004226 isSExt = true, FromVT = MVT::i32; // ASSERT SEXT 32
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004227 else if (NumZeroBits >= RegSize-33)
Bill Wendling181b6272008-10-19 20:34:04 +00004228 isSExt = false, FromVT = MVT::i32; // ASSERT ZEXT 32
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004229
4230 if (FromVT != MVT::Other) {
4231 P = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext,
4232 RegisterVT, P, DAG.getValueType(FromVT));
4233
4234 }
4235 }
4236 }
4237
4238 Parts[i] = P;
4239 }
4240
4241 Values[Value] = getCopyFromParts(DAG, Parts.begin(), NumRegs, RegisterVT,
4242 ValueVT);
4243 Part += NumRegs;
4244 Parts.clear();
4245 }
4246
4247 return DAG.getMergeValues(DAG.getVTList(&ValueVTs[0], ValueVTs.size()),
4248 &Values[0], ValueVTs.size());
4249}
4250
4251/// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
4252/// specified value into the registers specified by this object. This uses
4253/// Chain/Flag as the input and updates them for the output Chain/Flag.
4254/// If the Flag pointer is NULL, no flag is used.
4255void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG,
4256 SDValue &Chain, SDValue *Flag) const {
4257 // Get the list of the values's legal parts.
4258 unsigned NumRegs = Regs.size();
4259 SmallVector<SDValue, 8> Parts(NumRegs);
4260 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
4261 MVT ValueVT = ValueVTs[Value];
4262 unsigned NumParts = TLI->getNumRegisters(ValueVT);
4263 MVT RegisterVT = RegVTs[Value];
4264
4265 getCopyToParts(DAG, Val.getValue(Val.getResNo() + Value),
4266 &Parts[Part], NumParts, RegisterVT);
4267 Part += NumParts;
4268 }
4269
4270 // Copy the parts into the registers.
4271 SmallVector<SDValue, 8> Chains(NumRegs);
4272 for (unsigned i = 0; i != NumRegs; ++i) {
4273 SDValue Part;
4274 if (Flag == 0)
4275 Part = DAG.getCopyToReg(Chain, Regs[i], Parts[i]);
4276 else {
4277 Part = DAG.getCopyToReg(Chain, Regs[i], Parts[i], *Flag);
4278 *Flag = Part.getValue(1);
4279 }
4280 Chains[i] = Part.getValue(0);
4281 }
4282
4283 if (NumRegs == 1 || Flag)
4284 // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is
4285 // flagged to it. That is the CopyToReg nodes and the user are considered
4286 // a single scheduling unit. If we create a TokenFactor and return it as
4287 // chain, then the TokenFactor is both a predecessor (operand) of the
4288 // user as well as a successor (the TF operands are flagged to the user).
4289 // c1, f1 = CopyToReg
4290 // c2, f2 = CopyToReg
4291 // c3 = TokenFactor c1, c2
4292 // ...
4293 // = op c3, ..., f2
4294 Chain = Chains[NumRegs-1];
4295 else
4296 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other, &Chains[0], NumRegs);
4297}
4298
4299/// AddInlineAsmOperands - Add this value to the specified inlineasm node
4300/// operand list. This adds the code marker and includes the number of
4301/// values added into it.
4302void RegsForValue::AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
4303 std::vector<SDValue> &Ops) const {
4304 MVT IntPtrTy = DAG.getTargetLoweringInfo().getPointerTy();
4305 Ops.push_back(DAG.getTargetConstant(Code | (Regs.size() << 3), IntPtrTy));
4306 for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
4307 unsigned NumRegs = TLI->getNumRegisters(ValueVTs[Value]);
4308 MVT RegisterVT = RegVTs[Value];
Chris Lattner58f15c42008-10-17 16:21:11 +00004309 for (unsigned i = 0; i != NumRegs; ++i) {
4310 assert(Reg < Regs.size() && "Mismatch in # registers expected");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004311 Ops.push_back(DAG.getRegister(Regs[Reg++], RegisterVT));
Chris Lattner58f15c42008-10-17 16:21:11 +00004312 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004313 }
4314}
4315
4316/// isAllocatableRegister - If the specified register is safe to allocate,
4317/// i.e. it isn't a stack pointer or some other special register, return the
4318/// register class for the register. Otherwise, return null.
4319static const TargetRegisterClass *
4320isAllocatableRegister(unsigned Reg, MachineFunction &MF,
4321 const TargetLowering &TLI,
4322 const TargetRegisterInfo *TRI) {
4323 MVT FoundVT = MVT::Other;
4324 const TargetRegisterClass *FoundRC = 0;
4325 for (TargetRegisterInfo::regclass_iterator RCI = TRI->regclass_begin(),
4326 E = TRI->regclass_end(); RCI != E; ++RCI) {
4327 MVT ThisVT = MVT::Other;
4328
4329 const TargetRegisterClass *RC = *RCI;
4330 // If none of the the value types for this register class are valid, we
4331 // can't use it. For example, 64-bit reg classes on 32-bit targets.
4332 for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
4333 I != E; ++I) {
4334 if (TLI.isTypeLegal(*I)) {
4335 // If we have already found this register in a different register class,
4336 // choose the one with the largest VT specified. For example, on
4337 // PowerPC, we favor f64 register classes over f32.
4338 if (FoundVT == MVT::Other || FoundVT.bitsLT(*I)) {
4339 ThisVT = *I;
4340 break;
4341 }
4342 }
4343 }
4344
4345 if (ThisVT == MVT::Other) continue;
4346
4347 // NOTE: This isn't ideal. In particular, this might allocate the
4348 // frame pointer in functions that need it (due to them not being taken
4349 // out of allocation, because a variable sized allocation hasn't been seen
4350 // yet). This is a slight code pessimization, but should still work.
4351 for (TargetRegisterClass::iterator I = RC->allocation_order_begin(MF),
4352 E = RC->allocation_order_end(MF); I != E; ++I)
4353 if (*I == Reg) {
4354 // We found a matching register class. Keep looking at others in case
4355 // we find one with larger registers that this physreg is also in.
4356 FoundRC = RC;
4357 FoundVT = ThisVT;
4358 break;
4359 }
4360 }
4361 return FoundRC;
4362}
4363
4364
4365namespace llvm {
4366/// AsmOperandInfo - This contains information for each constraint that we are
4367/// lowering.
Daniel Dunbarc0c3b9a2008-09-10 04:16:29 +00004368struct VISIBILITY_HIDDEN SDISelAsmOperandInfo :
4369 public TargetLowering::AsmOperandInfo {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004370 /// CallOperand - If this is the result output operand or a clobber
4371 /// this is null, otherwise it is the incoming operand to the CallInst.
4372 /// This gets modified as the asm is processed.
4373 SDValue CallOperand;
4374
4375 /// AssignedRegs - If this is a register or register class operand, this
4376 /// contains the set of register corresponding to the operand.
4377 RegsForValue AssignedRegs;
4378
4379 explicit SDISelAsmOperandInfo(const InlineAsm::ConstraintInfo &info)
4380 : TargetLowering::AsmOperandInfo(info), CallOperand(0,0) {
4381 }
4382
4383 /// MarkAllocatedRegs - Once AssignedRegs is set, mark the assigned registers
4384 /// busy in OutputRegs/InputRegs.
4385 void MarkAllocatedRegs(bool isOutReg, bool isInReg,
4386 std::set<unsigned> &OutputRegs,
4387 std::set<unsigned> &InputRegs,
4388 const TargetRegisterInfo &TRI) const {
4389 if (isOutReg) {
4390 for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i)
4391 MarkRegAndAliases(AssignedRegs.Regs[i], OutputRegs, TRI);
4392 }
4393 if (isInReg) {
4394 for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i)
4395 MarkRegAndAliases(AssignedRegs.Regs[i], InputRegs, TRI);
4396 }
4397 }
Chris Lattner81249c92008-10-17 17:05:25 +00004398
4399 /// getCallOperandValMVT - Return the MVT of the Value* that this operand
4400 /// corresponds to. If there is no Value* for this operand, it returns
4401 /// MVT::Other.
4402 MVT getCallOperandValMVT(const TargetLowering &TLI,
4403 const TargetData *TD) const {
4404 if (CallOperandVal == 0) return MVT::Other;
4405
4406 if (isa<BasicBlock>(CallOperandVal))
4407 return TLI.getPointerTy();
4408
4409 const llvm::Type *OpTy = CallOperandVal->getType();
4410
4411 // If this is an indirect operand, the operand is a pointer to the
4412 // accessed type.
4413 if (isIndirect)
4414 OpTy = cast<PointerType>(OpTy)->getElementType();
4415
4416 // If OpTy is not a single value, it may be a struct/union that we
4417 // can tile with integers.
4418 if (!OpTy->isSingleValueType() && OpTy->isSized()) {
4419 unsigned BitSize = TD->getTypeSizeInBits(OpTy);
4420 switch (BitSize) {
4421 default: break;
4422 case 1:
4423 case 8:
4424 case 16:
4425 case 32:
4426 case 64:
Chris Lattnercfc14c12008-10-17 19:59:51 +00004427 case 128:
Chris Lattner81249c92008-10-17 17:05:25 +00004428 OpTy = IntegerType::get(BitSize);
4429 break;
4430 }
4431 }
4432
4433 return TLI.getValueType(OpTy, true);
4434 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004435
4436private:
4437 /// MarkRegAndAliases - Mark the specified register and all aliases in the
4438 /// specified set.
4439 static void MarkRegAndAliases(unsigned Reg, std::set<unsigned> &Regs,
4440 const TargetRegisterInfo &TRI) {
4441 assert(TargetRegisterInfo::isPhysicalRegister(Reg) && "Isn't a physreg");
4442 Regs.insert(Reg);
4443 if (const unsigned *Aliases = TRI.getAliasSet(Reg))
4444 for (; *Aliases; ++Aliases)
4445 Regs.insert(*Aliases);
4446 }
4447};
4448} // end llvm namespace.
4449
4450
4451/// GetRegistersForValue - Assign registers (virtual or physical) for the
4452/// specified operand. We prefer to assign virtual registers, to allow the
4453/// register allocator handle the assignment process. However, if the asm uses
4454/// features that we can't model on machineinstrs, we have SDISel do the
4455/// allocation. This produces generally horrible, but correct, code.
4456///
4457/// OpInfo describes the operand.
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004458/// Input and OutputRegs are the set of already allocated physical registers.
4459///
4460void SelectionDAGLowering::
Dale Johannesen8e3455b2008-09-24 23:13:09 +00004461GetRegistersForValue(SDISelAsmOperandInfo &OpInfo,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004462 std::set<unsigned> &OutputRegs,
4463 std::set<unsigned> &InputRegs) {
4464 // Compute whether this value requires an input register, an output register,
4465 // or both.
4466 bool isOutReg = false;
4467 bool isInReg = false;
4468 switch (OpInfo.Type) {
4469 case InlineAsm::isOutput:
4470 isOutReg = true;
4471
Dale Johannesen8e3455b2008-09-24 23:13:09 +00004472 // If there is an input constraint that matches this, we need to reserve
4473 // the input register so no other inputs allocate to it.
Chris Lattner6bdcda32008-10-17 16:47:46 +00004474 isInReg = OpInfo.hasMatchingInput();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004475 break;
4476 case InlineAsm::isInput:
4477 isInReg = true;
4478 isOutReg = false;
4479 break;
4480 case InlineAsm::isClobber:
4481 isOutReg = true;
4482 isInReg = true;
4483 break;
4484 }
4485
4486
4487 MachineFunction &MF = DAG.getMachineFunction();
4488 SmallVector<unsigned, 4> Regs;
4489
4490 // If this is a constraint for a single physreg, or a constraint for a
4491 // register class, find it.
4492 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
4493 TLI.getRegForInlineAsmConstraint(OpInfo.ConstraintCode,
4494 OpInfo.ConstraintVT);
4495
4496 unsigned NumRegs = 1;
Chris Lattner01426e12008-10-21 00:45:36 +00004497 if (OpInfo.ConstraintVT != MVT::Other) {
4498 // If this is a FP input in an integer register (or visa versa) insert a bit
4499 // cast of the input value. More generally, handle any case where the input
4500 // value disagrees with the register class we plan to stick this in.
4501 if (OpInfo.Type == InlineAsm::isInput &&
4502 PhysReg.second && !PhysReg.second->hasType(OpInfo.ConstraintVT)) {
4503 // Try to convert to the first MVT that the reg class contains. If the
4504 // types are identical size, use a bitcast to convert (e.g. two differing
4505 // vector types).
4506 MVT RegVT = *PhysReg.second->vt_begin();
4507 if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) {
4508 OpInfo.CallOperand = DAG.getNode(ISD::BIT_CONVERT, RegVT,
4509 OpInfo.CallOperand);
4510 OpInfo.ConstraintVT = RegVT;
4511 } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
4512 // If the input is a FP value and we want it in FP registers, do a
4513 // bitcast to the corresponding integer type. This turns an f64 value
4514 // into i64, which can be passed with two i32 values on a 32-bit
4515 // machine.
4516 RegVT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits());
4517 OpInfo.CallOperand = DAG.getNode(ISD::BIT_CONVERT, RegVT,
4518 OpInfo.CallOperand);
4519 OpInfo.ConstraintVT = RegVT;
4520 }
4521 }
4522
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004523 NumRegs = TLI.getNumRegisters(OpInfo.ConstraintVT);
Chris Lattner01426e12008-10-21 00:45:36 +00004524 }
4525
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004526 MVT RegVT;
4527 MVT ValueVT = OpInfo.ConstraintVT;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004528
4529 // If this is a constraint for a specific physical register, like {r17},
4530 // assign it now.
4531 if (PhysReg.first) {
4532 if (OpInfo.ConstraintVT == MVT::Other)
4533 ValueVT = *PhysReg.second->vt_begin();
4534
4535 // Get the actual register value type. This is important, because the user
4536 // may have asked for (e.g.) the AX register in i32 type. We need to
4537 // remember that AX is actually i16 to get the right extension.
4538 RegVT = *PhysReg.second->vt_begin();
4539
4540 // This is a explicit reference to a physical register.
4541 Regs.push_back(PhysReg.first);
4542
4543 // If this is an expanded reference, add the rest of the regs to Regs.
4544 if (NumRegs != 1) {
4545 TargetRegisterClass::iterator I = PhysReg.second->begin();
4546 for (; *I != PhysReg.first; ++I)
4547 assert(I != PhysReg.second->end() && "Didn't find reg!");
4548
4549 // Already added the first reg.
4550 --NumRegs; ++I;
4551 for (; NumRegs; --NumRegs, ++I) {
4552 assert(I != PhysReg.second->end() && "Ran out of registers to allocate!");
4553 Regs.push_back(*I);
4554 }
4555 }
4556 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, RegVT, ValueVT);
4557 const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
4558 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TRI);
4559 return;
4560 }
4561
4562 // Otherwise, if this was a reference to an LLVM register class, create vregs
4563 // for this reference.
4564 std::vector<unsigned> RegClassRegs;
4565 const TargetRegisterClass *RC = PhysReg.second;
4566 if (RC) {
Dale Johannesen8e3455b2008-09-24 23:13:09 +00004567 // If this is a tied register, our regalloc doesn't know how to maintain
Chris Lattner58f15c42008-10-17 16:21:11 +00004568 // the constraint, so we have to pick a register to pin the input/output to.
4569 // If it isn't a matched constraint, go ahead and create vreg and let the
4570 // regalloc do its thing.
Chris Lattner6bdcda32008-10-17 16:47:46 +00004571 if (!OpInfo.hasMatchingInput()) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004572 RegVT = *PhysReg.second->vt_begin();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004573 if (OpInfo.ConstraintVT == MVT::Other)
4574 ValueVT = RegVT;
4575
4576 // Create the appropriate number of virtual registers.
4577 MachineRegisterInfo &RegInfo = MF.getRegInfo();
4578 for (; NumRegs; --NumRegs)
4579 Regs.push_back(RegInfo.createVirtualRegister(PhysReg.second));
4580
4581 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, RegVT, ValueVT);
4582 return;
4583 }
4584
4585 // Otherwise, we can't allocate it. Let the code below figure out how to
4586 // maintain these constraints.
4587 RegClassRegs.assign(PhysReg.second->begin(), PhysReg.second->end());
4588
4589 } else {
4590 // This is a reference to a register class that doesn't directly correspond
4591 // to an LLVM register class. Allocate NumRegs consecutive, available,
4592 // registers from the class.
4593 RegClassRegs = TLI.getRegClassForInlineAsmConstraint(OpInfo.ConstraintCode,
4594 OpInfo.ConstraintVT);
4595 }
4596
4597 const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
4598 unsigned NumAllocated = 0;
4599 for (unsigned i = 0, e = RegClassRegs.size(); i != e; ++i) {
4600 unsigned Reg = RegClassRegs[i];
4601 // See if this register is available.
4602 if ((isOutReg && OutputRegs.count(Reg)) || // Already used.
4603 (isInReg && InputRegs.count(Reg))) { // Already used.
4604 // Make sure we find consecutive registers.
4605 NumAllocated = 0;
4606 continue;
4607 }
4608
4609 // Check to see if this register is allocatable (i.e. don't give out the
4610 // stack pointer).
4611 if (RC == 0) {
4612 RC = isAllocatableRegister(Reg, MF, TLI, TRI);
4613 if (!RC) { // Couldn't allocate this register.
4614 // Reset NumAllocated to make sure we return consecutive registers.
4615 NumAllocated = 0;
4616 continue;
4617 }
4618 }
4619
4620 // Okay, this register is good, we can use it.
4621 ++NumAllocated;
4622
4623 // If we allocated enough consecutive registers, succeed.
4624 if (NumAllocated == NumRegs) {
4625 unsigned RegStart = (i-NumAllocated)+1;
4626 unsigned RegEnd = i+1;
4627 // Mark all of the allocated registers used.
4628 for (unsigned i = RegStart; i != RegEnd; ++i)
4629 Regs.push_back(RegClassRegs[i]);
4630
4631 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, *RC->vt_begin(),
4632 OpInfo.ConstraintVT);
4633 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TRI);
4634 return;
4635 }
4636 }
4637
4638 // Otherwise, we couldn't allocate enough registers for this.
4639}
4640
Evan Chengda43bcf2008-09-24 00:05:32 +00004641/// hasInlineAsmMemConstraint - Return true if the inline asm instruction being
4642/// processed uses a memory 'm' constraint.
4643static bool
4644hasInlineAsmMemConstraint(std::vector<InlineAsm::ConstraintInfo> &CInfos,
4645 TargetLowering &TLI) {
4646 for (unsigned i = 0, e = CInfos.size(); i != e; ++i) {
4647 InlineAsm::ConstraintInfo &CI = CInfos[i];
4648 for (unsigned j = 0, ee = CI.Codes.size(); j != ee; ++j) {
4649 TargetLowering::ConstraintType CType = TLI.getConstraintType(CI.Codes[j]);
4650 if (CType == TargetLowering::C_Memory)
4651 return true;
4652 }
4653 }
4654
4655 return false;
4656}
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004657
4658/// visitInlineAsm - Handle a call to an InlineAsm object.
4659///
4660void SelectionDAGLowering::visitInlineAsm(CallSite CS) {
4661 InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
4662
4663 /// ConstraintOperands - Information about all of the constraints.
4664 std::vector<SDISelAsmOperandInfo> ConstraintOperands;
4665
4666 SDValue Chain = getRoot();
4667 SDValue Flag;
4668
4669 std::set<unsigned> OutputRegs, InputRegs;
4670
4671 // Do a prepass over the constraints, canonicalizing them, and building up the
4672 // ConstraintOperands list.
4673 std::vector<InlineAsm::ConstraintInfo>
4674 ConstraintInfos = IA->ParseConstraints();
4675
Evan Chengda43bcf2008-09-24 00:05:32 +00004676 bool hasMemory = hasInlineAsmMemConstraint(ConstraintInfos, TLI);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004677
4678 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst.
4679 unsigned ResNo = 0; // ResNo - The result number of the next output.
4680 for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) {
4681 ConstraintOperands.push_back(SDISelAsmOperandInfo(ConstraintInfos[i]));
4682 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
4683
4684 MVT OpVT = MVT::Other;
4685
4686 // Compute the value type for each operand.
4687 switch (OpInfo.Type) {
4688 case InlineAsm::isOutput:
4689 // Indirect outputs just consume an argument.
4690 if (OpInfo.isIndirect) {
4691 OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
4692 break;
4693 }
Chris Lattner2a0b96c2008-10-18 18:49:30 +00004694
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004695 // The return value of the call is this value. As such, there is no
4696 // corresponding argument.
4697 assert(CS.getType() != Type::VoidTy && "Bad inline asm!");
4698 if (const StructType *STy = dyn_cast<StructType>(CS.getType())) {
4699 OpVT = TLI.getValueType(STy->getElementType(ResNo));
4700 } else {
4701 assert(ResNo == 0 && "Asm only has one result!");
4702 OpVT = TLI.getValueType(CS.getType());
4703 }
4704 ++ResNo;
4705 break;
4706 case InlineAsm::isInput:
4707 OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
4708 break;
4709 case InlineAsm::isClobber:
4710 // Nothing to do.
4711 break;
4712 }
4713
4714 // If this is an input or an indirect output, process the call argument.
4715 // BasicBlocks are labels, currently appearing only in asm's.
4716 if (OpInfo.CallOperandVal) {
Chris Lattner81249c92008-10-17 17:05:25 +00004717 if (BasicBlock *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004718 OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
Chris Lattner81249c92008-10-17 17:05:25 +00004719 } else {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004720 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004721 }
Chris Lattner81249c92008-10-17 17:05:25 +00004722
4723 OpVT = OpInfo.getCallOperandValMVT(TLI, TD);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004724 }
4725
4726 OpInfo.ConstraintVT = OpVT;
Chris Lattner2a0b96c2008-10-18 18:49:30 +00004727 }
4728
4729 // Second pass over the constraints: compute which constraint option to use
4730 // and assign registers to constraints that want a specific physreg.
4731 for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) {
4732 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
4733
4734 // If this is an output operand with a matching input operand, look up the
4735 // matching input. It might have a different type (e.g. the output might be
4736 // i32 and the input i64) and we need to pick the larger width to ensure we
4737 // reserve the right number of registers.
4738 if (OpInfo.hasMatchingInput()) {
4739 SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
4740 if (OpInfo.ConstraintVT != Input.ConstraintVT) {
4741 assert(OpInfo.ConstraintVT.isInteger() &&
4742 Input.ConstraintVT.isInteger() &&
4743 "Asm constraints must be the same or different sized integers");
4744 if (OpInfo.ConstraintVT.getSizeInBits() <
4745 Input.ConstraintVT.getSizeInBits())
4746 OpInfo.ConstraintVT = Input.ConstraintVT;
4747 else
4748 Input.ConstraintVT = OpInfo.ConstraintVT;
4749 }
4750 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004751
4752 // Compute the constraint code and ConstraintType to use.
Evan Chengda43bcf2008-09-24 00:05:32 +00004753 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, hasMemory, &DAG);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004754
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004755 // If this is a memory input, and if the operand is not indirect, do what we
4756 // need to to provide an address for the memory input.
4757 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
4758 !OpInfo.isIndirect) {
4759 assert(OpInfo.Type == InlineAsm::isInput &&
4760 "Can only indirectify direct input operands!");
4761
4762 // Memory operands really want the address of the value. If we don't have
4763 // an indirect input, put it in the constpool if we can, otherwise spill
4764 // it to a stack slot.
4765
4766 // If the operand is a float, integer, or vector constant, spill to a
4767 // constant pool entry to get its address.
4768 Value *OpVal = OpInfo.CallOperandVal;
4769 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
4770 isa<ConstantVector>(OpVal)) {
4771 OpInfo.CallOperand = DAG.getConstantPool(cast<Constant>(OpVal),
4772 TLI.getPointerTy());
4773 } else {
4774 // Otherwise, create a stack slot and emit a store to it before the
4775 // asm.
4776 const Type *Ty = OpVal->getType();
4777 uint64_t TySize = TLI.getTargetData()->getABITypeSize(Ty);
4778 unsigned Align = TLI.getTargetData()->getPrefTypeAlignment(Ty);
4779 MachineFunction &MF = DAG.getMachineFunction();
4780 int SSFI = MF.getFrameInfo()->CreateStackObject(TySize, Align);
4781 SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getPointerTy());
4782 Chain = DAG.getStore(Chain, OpInfo.CallOperand, StackSlot, NULL, 0);
4783 OpInfo.CallOperand = StackSlot;
4784 }
4785
4786 // There is no longer a Value* corresponding to this operand.
4787 OpInfo.CallOperandVal = 0;
4788 // It is now an indirect operand.
4789 OpInfo.isIndirect = true;
4790 }
4791
4792 // If this constraint is for a specific register, allocate it before
4793 // anything else.
4794 if (OpInfo.ConstraintType == TargetLowering::C_Register)
Dale Johannesen8e3455b2008-09-24 23:13:09 +00004795 GetRegistersForValue(OpInfo, OutputRegs, InputRegs);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004796 }
4797 ConstraintInfos.clear();
4798
4799
4800 // Second pass - Loop over all of the operands, assigning virtual or physregs
Chris Lattner58f15c42008-10-17 16:21:11 +00004801 // to register class operands.
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004802 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
4803 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
4804
4805 // C_Register operands have already been allocated, Other/Memory don't need
4806 // to be.
4807 if (OpInfo.ConstraintType == TargetLowering::C_RegisterClass)
Dale Johannesen8e3455b2008-09-24 23:13:09 +00004808 GetRegistersForValue(OpInfo, OutputRegs, InputRegs);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004809 }
4810
4811 // AsmNodeOperands - The operands for the ISD::INLINEASM node.
4812 std::vector<SDValue> AsmNodeOperands;
4813 AsmNodeOperands.push_back(SDValue()); // reserve space for input chain
4814 AsmNodeOperands.push_back(
Bill Wendling056292f2008-09-16 21:48:12 +00004815 DAG.getTargetExternalSymbol(IA->getAsmString().c_str(), MVT::Other));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004816
4817
4818 // Loop over all of the inputs, copying the operand values into the
4819 // appropriate registers and processing the output regs.
4820 RegsForValue RetValRegs;
4821
4822 // IndirectStoresToEmit - The set of stores to emit after the inline asm node.
4823 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
4824
4825 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
4826 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
4827
4828 switch (OpInfo.Type) {
4829 case InlineAsm::isOutput: {
4830 if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass &&
4831 OpInfo.ConstraintType != TargetLowering::C_Register) {
4832 // Memory output, or 'other' output (e.g. 'X' constraint).
4833 assert(OpInfo.isIndirect && "Memory output must be indirect operand");
4834
4835 // Add information to the INLINEASM node to know about this output.
Dale Johannesen86b49f82008-09-24 01:07:17 +00004836 unsigned ResOpType = 4/*MEM*/ | (1<<3);
4837 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004838 TLI.getPointerTy()));
4839 AsmNodeOperands.push_back(OpInfo.CallOperand);
4840 break;
4841 }
4842
4843 // Otherwise, this is a register or register class output.
4844
4845 // Copy the output from the appropriate register. Find a register that
4846 // we can use.
4847 if (OpInfo.AssignedRegs.Regs.empty()) {
4848 cerr << "Couldn't allocate output reg for constraint '"
4849 << OpInfo.ConstraintCode << "'!\n";
4850 exit(1);
4851 }
4852
4853 // If this is an indirect operand, store through the pointer after the
4854 // asm.
4855 if (OpInfo.isIndirect) {
4856 IndirectStoresToEmit.push_back(std::make_pair(OpInfo.AssignedRegs,
4857 OpInfo.CallOperandVal));
4858 } else {
4859 // This is the result value of the call.
4860 assert(CS.getType() != Type::VoidTy && "Bad inline asm!");
4861 // Concatenate this output onto the outputs list.
4862 RetValRegs.append(OpInfo.AssignedRegs);
4863 }
4864
4865 // Add information to the INLINEASM node to know that this register is
4866 // set.
Dale Johannesen913d3df2008-09-12 17:49:03 +00004867 OpInfo.AssignedRegs.AddInlineAsmOperands(OpInfo.isEarlyClobber ?
4868 6 /* EARLYCLOBBER REGDEF */ :
4869 2 /* REGDEF */ ,
4870 DAG, AsmNodeOperands);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004871 break;
4872 }
4873 case InlineAsm::isInput: {
4874 SDValue InOperandVal = OpInfo.CallOperand;
4875
Chris Lattner6bdcda32008-10-17 16:47:46 +00004876 if (OpInfo.isMatchingInputConstraint()) { // Matching constraint?
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004877 // If this is required to match an output register we have already set,
4878 // just use its register.
Chris Lattner58f15c42008-10-17 16:21:11 +00004879 unsigned OperandNo = OpInfo.getMatchedOperand();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004880
4881 // Scan until we find the definition we already emitted of this operand.
4882 // When we find it, create a RegsForValue operand.
4883 unsigned CurOp = 2; // The first operand.
4884 for (; OperandNo; --OperandNo) {
4885 // Advance to the next operand.
4886 unsigned NumOps =
Dan Gohmanf5aeb1a2008-09-12 16:56:44 +00004887 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004888 assert(((NumOps & 7) == 2 /*REGDEF*/ ||
Dale Johannesen913d3df2008-09-12 17:49:03 +00004889 (NumOps & 7) == 6 /*EARLYCLOBBER REGDEF*/ ||
Dale Johannesen86b49f82008-09-24 01:07:17 +00004890 (NumOps & 7) == 4 /*MEM*/) &&
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004891 "Skipped past definitions?");
4892 CurOp += (NumOps>>3)+1;
4893 }
4894
4895 unsigned NumOps =
Dan Gohmanf5aeb1a2008-09-12 16:56:44 +00004896 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
Dale Johannesen913d3df2008-09-12 17:49:03 +00004897 if ((NumOps & 7) == 2 /*REGDEF*/
4898 || (NumOps & 7) == 6 /* EARLYCLOBBER REGDEF */) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004899 // Add NumOps>>3 registers to MatchedRegs.
4900 RegsForValue MatchedRegs;
4901 MatchedRegs.TLI = &TLI;
4902 MatchedRegs.ValueVTs.push_back(InOperandVal.getValueType());
4903 MatchedRegs.RegVTs.push_back(AsmNodeOperands[CurOp+1].getValueType());
4904 for (unsigned i = 0, e = NumOps>>3; i != e; ++i) {
4905 unsigned Reg =
4906 cast<RegisterSDNode>(AsmNodeOperands[++CurOp])->getReg();
4907 MatchedRegs.Regs.push_back(Reg);
4908 }
4909
4910 // Use the produced MatchedRegs object to
4911 MatchedRegs.getCopyToRegs(InOperandVal, DAG, Chain, &Flag);
Dale Johannesen86b49f82008-09-24 01:07:17 +00004912 MatchedRegs.AddInlineAsmOperands(1 /*REGUSE*/, DAG, AsmNodeOperands);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004913 break;
4914 } else {
Dale Johannesen86b49f82008-09-24 01:07:17 +00004915 assert(((NumOps & 7) == 4) && "Unknown matching constraint!");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004916 assert((NumOps >> 3) == 1 && "Unexpected number of operands");
4917 // Add information to the INLINEASM node to know about this input.
Dale Johannesen91aac102008-09-17 21:13:11 +00004918 AsmNodeOperands.push_back(DAG.getTargetConstant(NumOps,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004919 TLI.getPointerTy()));
4920 AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
4921 break;
4922 }
4923 }
4924
4925 if (OpInfo.ConstraintType == TargetLowering::C_Other) {
4926 assert(!OpInfo.isIndirect &&
4927 "Don't know how to handle indirect other inputs yet!");
4928
4929 std::vector<SDValue> Ops;
4930 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode[0],
Evan Chengda43bcf2008-09-24 00:05:32 +00004931 hasMemory, Ops, DAG);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004932 if (Ops.empty()) {
4933 cerr << "Invalid operand for inline asm constraint '"
4934 << OpInfo.ConstraintCode << "'!\n";
4935 exit(1);
4936 }
4937
4938 // Add information to the INLINEASM node to know about this input.
4939 unsigned ResOpType = 3 /*IMM*/ | (Ops.size() << 3);
4940 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
4941 TLI.getPointerTy()));
4942 AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end());
4943 break;
4944 } else if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
4945 assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
4946 assert(InOperandVal.getValueType() == TLI.getPointerTy() &&
4947 "Memory operands expect pointer values");
4948
4949 // Add information to the INLINEASM node to know about this input.
Dale Johannesen86b49f82008-09-24 01:07:17 +00004950 unsigned ResOpType = 4/*MEM*/ | (1<<3);
4951 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004952 TLI.getPointerTy()));
4953 AsmNodeOperands.push_back(InOperandVal);
4954 break;
4955 }
4956
4957 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
4958 OpInfo.ConstraintType == TargetLowering::C_Register) &&
4959 "Unknown constraint type!");
4960 assert(!OpInfo.isIndirect &&
4961 "Don't know how to handle indirect register inputs yet!");
4962
4963 // Copy the input into the appropriate registers.
Evan Chengaa765b82008-09-25 00:14:04 +00004964 if (OpInfo.AssignedRegs.Regs.empty()) {
4965 cerr << "Couldn't allocate output reg for constraint '"
4966 << OpInfo.ConstraintCode << "'!\n";
4967 exit(1);
4968 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004969
4970 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, Chain, &Flag);
4971
Dale Johannesen86b49f82008-09-24 01:07:17 +00004972 OpInfo.AssignedRegs.AddInlineAsmOperands(1/*REGUSE*/,
4973 DAG, AsmNodeOperands);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004974 break;
4975 }
4976 case InlineAsm::isClobber: {
4977 // Add the clobbered value to the operand list, so that the register
4978 // allocator is aware that the physreg got clobbered.
4979 if (!OpInfo.AssignedRegs.Regs.empty())
Dale Johannesen91aac102008-09-17 21:13:11 +00004980 OpInfo.AssignedRegs.AddInlineAsmOperands(6 /* EARLYCLOBBER REGDEF */,
4981 DAG, AsmNodeOperands);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004982 break;
4983 }
4984 }
4985 }
4986
4987 // Finish up input operands.
4988 AsmNodeOperands[0] = Chain;
4989 if (Flag.getNode()) AsmNodeOperands.push_back(Flag);
4990
4991 Chain = DAG.getNode(ISD::INLINEASM,
4992 DAG.getNodeValueTypes(MVT::Other, MVT::Flag), 2,
4993 &AsmNodeOperands[0], AsmNodeOperands.size());
4994 Flag = Chain.getValue(1);
4995
4996 // If this asm returns a register value, copy the result from that register
4997 // and set it as the value of the call.
4998 if (!RetValRegs.Regs.empty()) {
4999 SDValue Val = RetValRegs.getCopyFromRegs(DAG, Chain, &Flag);
Chris Lattner2a0b96c2008-10-18 18:49:30 +00005000
5001 // FIXME: Why don't we do this for inline asms with MRVs?
5002 if (CS.getType()->isSingleValueType() && CS.getType()->isSized()) {
5003 MVT ResultType = TLI.getValueType(CS.getType());
5004
5005 // If any of the results of the inline asm is a vector, it may have the
5006 // wrong width/num elts. This can happen for register classes that can
5007 // contain multiple different value types. The preg or vreg allocated may
5008 // not have the same VT as was expected. Convert it to the right type
5009 // with bit_convert.
5010 if (ResultType != Val.getValueType() && Val.getValueType().isVector()) {
5011 Val = DAG.getNode(ISD::BIT_CONVERT, ResultType, Val);
Dan Gohman95915732008-10-18 01:03:45 +00005012
Chris Lattner2a0b96c2008-10-18 18:49:30 +00005013 } else if (ResultType != Val.getValueType() &&
5014 ResultType.isInteger() && Val.getValueType().isInteger()) {
5015 // If a result value was tied to an input value, the computed result may
5016 // have a wider width than the expected result. Extract the relevant
5017 // portion.
5018 Val = DAG.getNode(ISD::TRUNCATE, ResultType, Val);
Dan Gohman95915732008-10-18 01:03:45 +00005019 }
Chris Lattner2a0b96c2008-10-18 18:49:30 +00005020
5021 assert(ResultType == Val.getValueType() && "Asm result value mismatch!");
Chris Lattner0c526442008-10-17 17:52:49 +00005022 }
Dan Gohman95915732008-10-18 01:03:45 +00005023
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005024 setValue(CS.getInstruction(), Val);
5025 }
5026
5027 std::vector<std::pair<SDValue, Value*> > StoresToEmit;
5028
5029 // Process indirect outputs, first output all of the flagged copies out of
5030 // physregs.
5031 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
5032 RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
5033 Value *Ptr = IndirectStoresToEmit[i].second;
5034 SDValue OutVal = OutRegs.getCopyFromRegs(DAG, Chain, &Flag);
5035 StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
5036 }
5037
5038 // Emit the non-flagged stores from the physregs.
5039 SmallVector<SDValue, 8> OutChains;
5040 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i)
5041 OutChains.push_back(DAG.getStore(Chain, StoresToEmit[i].first,
5042 getValue(StoresToEmit[i].second),
5043 StoresToEmit[i].second, 0));
5044 if (!OutChains.empty())
5045 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
5046 &OutChains[0], OutChains.size());
5047 DAG.setRoot(Chain);
5048}
5049
5050
5051void SelectionDAGLowering::visitMalloc(MallocInst &I) {
5052 SDValue Src = getValue(I.getOperand(0));
5053
5054 MVT IntPtr = TLI.getPointerTy();
5055
5056 if (IntPtr.bitsLT(Src.getValueType()))
5057 Src = DAG.getNode(ISD::TRUNCATE, IntPtr, Src);
5058 else if (IntPtr.bitsGT(Src.getValueType()))
5059 Src = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, Src);
5060
5061 // Scale the source by the type size.
5062 uint64_t ElementSize = TD->getABITypeSize(I.getType()->getElementType());
5063 Src = DAG.getNode(ISD::MUL, Src.getValueType(),
5064 Src, DAG.getIntPtrConstant(ElementSize));
5065
5066 TargetLowering::ArgListTy Args;
5067 TargetLowering::ArgListEntry Entry;
5068 Entry.Node = Src;
5069 Entry.Ty = TLI.getTargetData()->getIntPtrType();
5070 Args.push_back(Entry);
5071
5072 std::pair<SDValue,SDValue> Result =
Dale Johannesen86098bd2008-09-26 19:31:26 +00005073 TLI.LowerCallTo(getRoot(), I.getType(), false, false, false, false,
5074 CallingConv::C, PerformTailCallOpt,
5075 DAG.getExternalSymbol("malloc", IntPtr),
Dan Gohman1937e2f2008-09-16 01:42:28 +00005076 Args, DAG);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005077 setValue(&I, Result.first); // Pointers always fit in registers
5078 DAG.setRoot(Result.second);
5079}
5080
5081void SelectionDAGLowering::visitFree(FreeInst &I) {
5082 TargetLowering::ArgListTy Args;
5083 TargetLowering::ArgListEntry Entry;
5084 Entry.Node = getValue(I.getOperand(0));
5085 Entry.Ty = TLI.getTargetData()->getIntPtrType();
5086 Args.push_back(Entry);
5087 MVT IntPtr = TLI.getPointerTy();
5088 std::pair<SDValue,SDValue> Result =
Dale Johannesen86098bd2008-09-26 19:31:26 +00005089 TLI.LowerCallTo(getRoot(), Type::VoidTy, false, false, false, false,
Dan Gohman1937e2f2008-09-16 01:42:28 +00005090 CallingConv::C, PerformTailCallOpt,
Bill Wendling056292f2008-09-16 21:48:12 +00005091 DAG.getExternalSymbol("free", IntPtr), Args, DAG);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005092 DAG.setRoot(Result.second);
5093}
5094
5095void SelectionDAGLowering::visitVAStart(CallInst &I) {
5096 DAG.setRoot(DAG.getNode(ISD::VASTART, MVT::Other, getRoot(),
5097 getValue(I.getOperand(1)),
5098 DAG.getSrcValue(I.getOperand(1))));
5099}
5100
5101void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
5102 SDValue V = DAG.getVAArg(TLI.getValueType(I.getType()), getRoot(),
5103 getValue(I.getOperand(0)),
5104 DAG.getSrcValue(I.getOperand(0)));
5105 setValue(&I, V);
5106 DAG.setRoot(V.getValue(1));
5107}
5108
5109void SelectionDAGLowering::visitVAEnd(CallInst &I) {
5110 DAG.setRoot(DAG.getNode(ISD::VAEND, MVT::Other, getRoot(),
5111 getValue(I.getOperand(1)),
5112 DAG.getSrcValue(I.getOperand(1))));
5113}
5114
5115void SelectionDAGLowering::visitVACopy(CallInst &I) {
5116 DAG.setRoot(DAG.getNode(ISD::VACOPY, MVT::Other, getRoot(),
5117 getValue(I.getOperand(1)),
5118 getValue(I.getOperand(2)),
5119 DAG.getSrcValue(I.getOperand(1)),
5120 DAG.getSrcValue(I.getOperand(2))));
5121}
5122
5123/// TargetLowering::LowerArguments - This is the default LowerArguments
5124/// implementation, which just inserts a FORMAL_ARGUMENTS node. FIXME: When all
5125/// targets are migrated to using FORMAL_ARGUMENTS, this hook should be
5126/// integrated into SDISel.
5127void TargetLowering::LowerArguments(Function &F, SelectionDAG &DAG,
5128 SmallVectorImpl<SDValue> &ArgValues) {
5129 // Add CC# and isVararg as operands to the FORMAL_ARGUMENTS node.
5130 SmallVector<SDValue, 3+16> Ops;
5131 Ops.push_back(DAG.getRoot());
5132 Ops.push_back(DAG.getConstant(F.getCallingConv(), getPointerTy()));
5133 Ops.push_back(DAG.getConstant(F.isVarArg(), getPointerTy()));
5134
5135 // Add one result value for each formal argument.
5136 SmallVector<MVT, 16> RetVals;
5137 unsigned j = 1;
5138 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end();
5139 I != E; ++I, ++j) {
5140 SmallVector<MVT, 4> ValueVTs;
5141 ComputeValueVTs(*this, I->getType(), ValueVTs);
5142 for (unsigned Value = 0, NumValues = ValueVTs.size();
5143 Value != NumValues; ++Value) {
5144 MVT VT = ValueVTs[Value];
5145 const Type *ArgTy = VT.getTypeForMVT();
5146 ISD::ArgFlagsTy Flags;
5147 unsigned OriginalAlignment =
5148 getTargetData()->getABITypeAlignment(ArgTy);
5149
Devang Patel05988662008-09-25 21:00:45 +00005150 if (F.paramHasAttr(j, Attribute::ZExt))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005151 Flags.setZExt();
Devang Patel05988662008-09-25 21:00:45 +00005152 if (F.paramHasAttr(j, Attribute::SExt))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005153 Flags.setSExt();
Devang Patel05988662008-09-25 21:00:45 +00005154 if (F.paramHasAttr(j, Attribute::InReg))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005155 Flags.setInReg();
Devang Patel05988662008-09-25 21:00:45 +00005156 if (F.paramHasAttr(j, Attribute::StructRet))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005157 Flags.setSRet();
Devang Patel05988662008-09-25 21:00:45 +00005158 if (F.paramHasAttr(j, Attribute::ByVal)) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005159 Flags.setByVal();
5160 const PointerType *Ty = cast<PointerType>(I->getType());
5161 const Type *ElementTy = Ty->getElementType();
5162 unsigned FrameAlign = getByValTypeAlignment(ElementTy);
5163 unsigned FrameSize = getTargetData()->getABITypeSize(ElementTy);
5164 // For ByVal, alignment should be passed from FE. BE will guess if
5165 // this info is not there but there are cases it cannot get right.
5166 if (F.getParamAlignment(j))
5167 FrameAlign = F.getParamAlignment(j);
5168 Flags.setByValAlign(FrameAlign);
5169 Flags.setByValSize(FrameSize);
5170 }
Devang Patel05988662008-09-25 21:00:45 +00005171 if (F.paramHasAttr(j, Attribute::Nest))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005172 Flags.setNest();
5173 Flags.setOrigAlign(OriginalAlignment);
5174
5175 MVT RegisterVT = getRegisterType(VT);
5176 unsigned NumRegs = getNumRegisters(VT);
5177 for (unsigned i = 0; i != NumRegs; ++i) {
5178 RetVals.push_back(RegisterVT);
5179 ISD::ArgFlagsTy MyFlags = Flags;
5180 if (NumRegs > 1 && i == 0)
5181 MyFlags.setSplit();
5182 // if it isn't first piece, alignment must be 1
5183 else if (i > 0)
5184 MyFlags.setOrigAlign(1);
5185 Ops.push_back(DAG.getArgFlags(MyFlags));
5186 }
5187 }
5188 }
5189
5190 RetVals.push_back(MVT::Other);
5191
5192 // Create the node.
5193 SDNode *Result = DAG.getNode(ISD::FORMAL_ARGUMENTS,
5194 DAG.getVTList(&RetVals[0], RetVals.size()),
5195 &Ops[0], Ops.size()).getNode();
5196
5197 // Prelower FORMAL_ARGUMENTS. This isn't required for functionality, but
5198 // allows exposing the loads that may be part of the argument access to the
5199 // first DAGCombiner pass.
5200 SDValue TmpRes = LowerOperation(SDValue(Result, 0), DAG);
5201
5202 // The number of results should match up, except that the lowered one may have
5203 // an extra flag result.
5204 assert((Result->getNumValues() == TmpRes.getNode()->getNumValues() ||
5205 (Result->getNumValues()+1 == TmpRes.getNode()->getNumValues() &&
5206 TmpRes.getValue(Result->getNumValues()).getValueType() == MVT::Flag))
5207 && "Lowering produced unexpected number of results!");
5208
5209 // The FORMAL_ARGUMENTS node itself is likely no longer needed.
5210 if (Result != TmpRes.getNode() && Result->use_empty()) {
5211 HandleSDNode Dummy(DAG.getRoot());
5212 DAG.RemoveDeadNode(Result);
5213 }
5214
5215 Result = TmpRes.getNode();
5216
5217 unsigned NumArgRegs = Result->getNumValues() - 1;
5218 DAG.setRoot(SDValue(Result, NumArgRegs));
5219
5220 // Set up the return result vector.
5221 unsigned i = 0;
5222 unsigned Idx = 1;
5223 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E;
5224 ++I, ++Idx) {
5225 SmallVector<MVT, 4> ValueVTs;
5226 ComputeValueVTs(*this, I->getType(), ValueVTs);
5227 for (unsigned Value = 0, NumValues = ValueVTs.size();
5228 Value != NumValues; ++Value) {
5229 MVT VT = ValueVTs[Value];
5230 MVT PartVT = getRegisterType(VT);
5231
5232 unsigned NumParts = getNumRegisters(VT);
5233 SmallVector<SDValue, 4> Parts(NumParts);
5234 for (unsigned j = 0; j != NumParts; ++j)
5235 Parts[j] = SDValue(Result, i++);
5236
5237 ISD::NodeType AssertOp = ISD::DELETED_NODE;
Devang Patel05988662008-09-25 21:00:45 +00005238 if (F.paramHasAttr(Idx, Attribute::SExt))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005239 AssertOp = ISD::AssertSext;
Devang Patel05988662008-09-25 21:00:45 +00005240 else if (F.paramHasAttr(Idx, Attribute::ZExt))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005241 AssertOp = ISD::AssertZext;
5242
5243 ArgValues.push_back(getCopyFromParts(DAG, &Parts[0], NumParts, PartVT, VT,
5244 AssertOp));
5245 }
5246 }
5247 assert(i == NumArgRegs && "Argument register count mismatch!");
5248}
5249
5250
5251/// TargetLowering::LowerCallTo - This is the default LowerCallTo
5252/// implementation, which just inserts an ISD::CALL node, which is later custom
5253/// lowered by the target to something concrete. FIXME: When all targets are
5254/// migrated to using ISD::CALL, this hook should be integrated into SDISel.
5255std::pair<SDValue, SDValue>
5256TargetLowering::LowerCallTo(SDValue Chain, const Type *RetTy,
5257 bool RetSExt, bool RetZExt, bool isVarArg,
Dale Johannesen86098bd2008-09-26 19:31:26 +00005258 bool isInreg,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005259 unsigned CallingConv, bool isTailCall,
5260 SDValue Callee,
5261 ArgListTy &Args, SelectionDAG &DAG) {
Dan Gohman1937e2f2008-09-16 01:42:28 +00005262 assert((!isTailCall || PerformTailCallOpt) &&
5263 "isTailCall set when tail-call optimizations are disabled!");
5264
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005265 SmallVector<SDValue, 32> Ops;
5266 Ops.push_back(Chain); // Op#0 - Chain
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005267 Ops.push_back(Callee);
5268
5269 // Handle all of the outgoing arguments.
5270 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
5271 SmallVector<MVT, 4> ValueVTs;
5272 ComputeValueVTs(*this, Args[i].Ty, ValueVTs);
5273 for (unsigned Value = 0, NumValues = ValueVTs.size();
5274 Value != NumValues; ++Value) {
5275 MVT VT = ValueVTs[Value];
5276 const Type *ArgTy = VT.getTypeForMVT();
Chris Lattner2a0b96c2008-10-18 18:49:30 +00005277 SDValue Op = SDValue(Args[i].Node.getNode(),
5278 Args[i].Node.getResNo() + Value);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005279 ISD::ArgFlagsTy Flags;
5280 unsigned OriginalAlignment =
5281 getTargetData()->getABITypeAlignment(ArgTy);
5282
5283 if (Args[i].isZExt)
5284 Flags.setZExt();
5285 if (Args[i].isSExt)
5286 Flags.setSExt();
5287 if (Args[i].isInReg)
5288 Flags.setInReg();
5289 if (Args[i].isSRet)
5290 Flags.setSRet();
5291 if (Args[i].isByVal) {
5292 Flags.setByVal();
5293 const PointerType *Ty = cast<PointerType>(Args[i].Ty);
5294 const Type *ElementTy = Ty->getElementType();
5295 unsigned FrameAlign = getByValTypeAlignment(ElementTy);
5296 unsigned FrameSize = getTargetData()->getABITypeSize(ElementTy);
5297 // For ByVal, alignment should come from FE. BE will guess if this
5298 // info is not there but there are cases it cannot get right.
5299 if (Args[i].Alignment)
5300 FrameAlign = Args[i].Alignment;
5301 Flags.setByValAlign(FrameAlign);
5302 Flags.setByValSize(FrameSize);
5303 }
5304 if (Args[i].isNest)
5305 Flags.setNest();
5306 Flags.setOrigAlign(OriginalAlignment);
5307
5308 MVT PartVT = getRegisterType(VT);
5309 unsigned NumParts = getNumRegisters(VT);
5310 SmallVector<SDValue, 4> Parts(NumParts);
5311 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
5312
5313 if (Args[i].isSExt)
5314 ExtendKind = ISD::SIGN_EXTEND;
5315 else if (Args[i].isZExt)
5316 ExtendKind = ISD::ZERO_EXTEND;
5317
5318 getCopyToParts(DAG, Op, &Parts[0], NumParts, PartVT, ExtendKind);
5319
5320 for (unsigned i = 0; i != NumParts; ++i) {
5321 // if it isn't first piece, alignment must be 1
5322 ISD::ArgFlagsTy MyFlags = Flags;
5323 if (NumParts > 1 && i == 0)
5324 MyFlags.setSplit();
5325 else if (i != 0)
5326 MyFlags.setOrigAlign(1);
5327
5328 Ops.push_back(Parts[i]);
5329 Ops.push_back(DAG.getArgFlags(MyFlags));
5330 }
5331 }
5332 }
5333
5334 // Figure out the result value types. We start by making a list of
5335 // the potentially illegal return value types.
5336 SmallVector<MVT, 4> LoweredRetTys;
5337 SmallVector<MVT, 4> RetTys;
5338 ComputeValueVTs(*this, RetTy, RetTys);
5339
5340 // Then we translate that to a list of legal types.
5341 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
5342 MVT VT = RetTys[I];
5343 MVT RegisterVT = getRegisterType(VT);
5344 unsigned NumRegs = getNumRegisters(VT);
5345 for (unsigned i = 0; i != NumRegs; ++i)
5346 LoweredRetTys.push_back(RegisterVT);
5347 }
5348
5349 LoweredRetTys.push_back(MVT::Other); // Always has a chain.
5350
5351 // Create the CALL node.
Dale Johannesen86098bd2008-09-26 19:31:26 +00005352 SDValue Res = DAG.getCall(CallingConv, isVarArg, isTailCall, isInreg,
Dan Gohman095cc292008-09-13 01:54:27 +00005353 DAG.getVTList(&LoweredRetTys[0],
5354 LoweredRetTys.size()),
Dale Johannesen86098bd2008-09-26 19:31:26 +00005355 &Ops[0], Ops.size()
5356 );
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005357 Chain = Res.getValue(LoweredRetTys.size() - 1);
5358
5359 // Gather up the call result into a single value.
Dan Gohmanb5cc34d2008-10-07 00:12:37 +00005360 if (RetTy != Type::VoidTy && !RetTys.empty()) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005361 ISD::NodeType AssertOp = ISD::DELETED_NODE;
5362
5363 if (RetSExt)
5364 AssertOp = ISD::AssertSext;
5365 else if (RetZExt)
5366 AssertOp = ISD::AssertZext;
5367
5368 SmallVector<SDValue, 4> ReturnValues;
5369 unsigned RegNo = 0;
5370 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
5371 MVT VT = RetTys[I];
5372 MVT RegisterVT = getRegisterType(VT);
5373 unsigned NumRegs = getNumRegisters(VT);
5374 unsigned RegNoEnd = NumRegs + RegNo;
5375 SmallVector<SDValue, 4> Results;
5376 for (; RegNo != RegNoEnd; ++RegNo)
5377 Results.push_back(Res.getValue(RegNo));
5378 SDValue ReturnValue =
5379 getCopyFromParts(DAG, &Results[0], NumRegs, RegisterVT, VT,
5380 AssertOp);
5381 ReturnValues.push_back(ReturnValue);
5382 }
5383 Res = DAG.getMergeValues(DAG.getVTList(&RetTys[0], RetTys.size()),
5384 &ReturnValues[0], ReturnValues.size());
5385 }
5386
5387 return std::make_pair(Res, Chain);
5388}
5389
5390SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) {
5391 assert(0 && "LowerOperation not implemented for this target!");
5392 abort();
5393 return SDValue();
5394}
5395
5396
5397void SelectionDAGLowering::CopyValueToVirtualRegister(Value *V, unsigned Reg) {
5398 SDValue Op = getValue(V);
5399 assert((Op.getOpcode() != ISD::CopyFromReg ||
5400 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
5401 "Copy from a reg to the same reg!");
5402 assert(!TargetRegisterInfo::isPhysicalRegister(Reg) && "Is a physreg");
5403
5404 RegsForValue RFV(TLI, Reg, V->getType());
5405 SDValue Chain = DAG.getEntryNode();
5406 RFV.getCopyToRegs(Op, DAG, Chain, 0);
5407 PendingExports.push_back(Chain);
5408}
5409
5410#include "llvm/CodeGen/SelectionDAGISel.h"
5411
5412void SelectionDAGISel::
5413LowerArguments(BasicBlock *LLVMBB) {
5414 // If this is the entry block, emit arguments.
5415 Function &F = *LLVMBB->getParent();
5416 SDValue OldRoot = SDL->DAG.getRoot();
5417 SmallVector<SDValue, 16> Args;
5418 TLI.LowerArguments(F, SDL->DAG, Args);
5419
5420 unsigned a = 0;
5421 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
5422 AI != E; ++AI) {
5423 SmallVector<MVT, 4> ValueVTs;
5424 ComputeValueVTs(TLI, AI->getType(), ValueVTs);
5425 unsigned NumValues = ValueVTs.size();
5426 if (!AI->use_empty()) {
5427 SDL->setValue(AI, SDL->DAG.getMergeValues(&Args[a], NumValues));
5428 // If this argument is live outside of the entry block, insert a copy from
5429 // whereever we got it to the vreg that other BB's will reference it as.
5430 DenseMap<const Value*, unsigned>::iterator VMI=FuncInfo->ValueMap.find(AI);
5431 if (VMI != FuncInfo->ValueMap.end()) {
5432 SDL->CopyValueToVirtualRegister(AI, VMI->second);
5433 }
5434 }
5435 a += NumValues;
5436 }
5437
5438 // Finally, if the target has anything special to do, allow it to do so.
5439 // FIXME: this should insert code into the DAG!
5440 EmitFunctionEntryCode(F, SDL->DAG.getMachineFunction());
5441}
5442
5443/// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
5444/// ensure constants are generated when needed. Remember the virtual registers
5445/// that need to be added to the Machine PHI nodes as input. We cannot just
5446/// directly add them, because expansion might result in multiple MBB's for one
5447/// BB. As such, the start of the BB might correspond to a different MBB than
5448/// the end.
5449///
5450void
5451SelectionDAGISel::HandlePHINodesInSuccessorBlocks(BasicBlock *LLVMBB) {
5452 TerminatorInst *TI = LLVMBB->getTerminator();
5453
5454 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
5455
5456 // Check successor nodes' PHI nodes that expect a constant to be available
5457 // from this block.
5458 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
5459 BasicBlock *SuccBB = TI->getSuccessor(succ);
5460 if (!isa<PHINode>(SuccBB->begin())) continue;
5461 MachineBasicBlock *SuccMBB = FuncInfo->MBBMap[SuccBB];
5462
5463 // If this terminator has multiple identical successors (common for
5464 // switches), only handle each succ once.
5465 if (!SuccsHandled.insert(SuccMBB)) continue;
5466
5467 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
5468 PHINode *PN;
5469
5470 // At this point we know that there is a 1-1 correspondence between LLVM PHI
5471 // nodes and Machine PHI nodes, but the incoming operands have not been
5472 // emitted yet.
5473 for (BasicBlock::iterator I = SuccBB->begin();
5474 (PN = dyn_cast<PHINode>(I)); ++I) {
5475 // Ignore dead phi's.
5476 if (PN->use_empty()) continue;
5477
5478 unsigned Reg;
5479 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
5480
5481 if (Constant *C = dyn_cast<Constant>(PHIOp)) {
5482 unsigned &RegOut = SDL->ConstantsOut[C];
5483 if (RegOut == 0) {
5484 RegOut = FuncInfo->CreateRegForValue(C);
5485 SDL->CopyValueToVirtualRegister(C, RegOut);
5486 }
5487 Reg = RegOut;
5488 } else {
5489 Reg = FuncInfo->ValueMap[PHIOp];
5490 if (Reg == 0) {
5491 assert(isa<AllocaInst>(PHIOp) &&
5492 FuncInfo->StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
5493 "Didn't codegen value into a register!??");
5494 Reg = FuncInfo->CreateRegForValue(PHIOp);
5495 SDL->CopyValueToVirtualRegister(PHIOp, Reg);
5496 }
5497 }
5498
5499 // Remember that this register needs to added to the machine PHI node as
5500 // the input for this MBB.
5501 SmallVector<MVT, 4> ValueVTs;
5502 ComputeValueVTs(TLI, PN->getType(), ValueVTs);
5503 for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
5504 MVT VT = ValueVTs[vti];
5505 unsigned NumRegisters = TLI.getNumRegisters(VT);
5506 for (unsigned i = 0, e = NumRegisters; i != e; ++i)
5507 SDL->PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
5508 Reg += NumRegisters;
5509 }
5510 }
5511 }
5512 SDL->ConstantsOut.clear();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005513}
5514
Dan Gohman3df24e62008-09-03 23:12:08 +00005515/// This is the Fast-ISel version of HandlePHINodesInSuccessorBlocks. It only
5516/// supports legal types, and it emits MachineInstrs directly instead of
5517/// creating SelectionDAG nodes.
5518///
5519bool
5520SelectionDAGISel::HandlePHINodesInSuccessorBlocksFast(BasicBlock *LLVMBB,
5521 FastISel *F) {
5522 TerminatorInst *TI = LLVMBB->getTerminator();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005523
Dan Gohman3df24e62008-09-03 23:12:08 +00005524 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
5525 unsigned OrigNumPHINodesToUpdate = SDL->PHINodesToUpdate.size();
5526
5527 // Check successor nodes' PHI nodes that expect a constant to be available
5528 // from this block.
5529 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
5530 BasicBlock *SuccBB = TI->getSuccessor(succ);
5531 if (!isa<PHINode>(SuccBB->begin())) continue;
5532 MachineBasicBlock *SuccMBB = FuncInfo->MBBMap[SuccBB];
5533
5534 // If this terminator has multiple identical successors (common for
5535 // switches), only handle each succ once.
5536 if (!SuccsHandled.insert(SuccMBB)) continue;
5537
5538 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
5539 PHINode *PN;
5540
5541 // At this point we know that there is a 1-1 correspondence between LLVM PHI
5542 // nodes and Machine PHI nodes, but the incoming operands have not been
5543 // emitted yet.
5544 for (BasicBlock::iterator I = SuccBB->begin();
5545 (PN = dyn_cast<PHINode>(I)); ++I) {
5546 // Ignore dead phi's.
5547 if (PN->use_empty()) continue;
5548
5549 // Only handle legal types. Two interesting things to note here. First,
5550 // by bailing out early, we may leave behind some dead instructions,
5551 // since SelectionDAG's HandlePHINodesInSuccessorBlocks will insert its
5552 // own moves. Second, this check is necessary becuase FastISel doesn't
5553 // use CreateRegForValue to create registers, so it always creates
5554 // exactly one register for each non-void instruction.
5555 MVT VT = TLI.getValueType(PN->getType(), /*AllowUnknown=*/true);
5556 if (VT == MVT::Other || !TLI.isTypeLegal(VT)) {
Dan Gohman74321ab2008-09-10 21:01:31 +00005557 // Promote MVT::i1.
5558 if (VT == MVT::i1)
5559 VT = TLI.getTypeToTransformTo(VT);
5560 else {
5561 SDL->PHINodesToUpdate.resize(OrigNumPHINodesToUpdate);
5562 return false;
5563 }
Dan Gohman3df24e62008-09-03 23:12:08 +00005564 }
5565
5566 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
5567
5568 unsigned Reg = F->getRegForValue(PHIOp);
5569 if (Reg == 0) {
5570 SDL->PHINodesToUpdate.resize(OrigNumPHINodesToUpdate);
5571 return false;
5572 }
5573 SDL->PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg));
5574 }
5575 }
5576
5577 return true;
5578}