blob: d04daeb76b5ce4481c8035e63be47c7c0e8e8e29 [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) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000905 SmallVector<MVT, 4> ValueVTs;
906 ComputeValueVTs(TLI, I.getOperand(i)->getType(), ValueVTs);
Dan Gohman7ea1ca62008-10-21 20:00:42 +0000907 unsigned NumValues = ValueVTs.size();
908 if (NumValues == 0) continue;
909
910 SDValue RetOp = getValue(I.getOperand(i));
911 for (unsigned j = 0, f = NumValues; j != f; ++j) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000912 MVT VT = ValueVTs[j];
913
914 // FIXME: C calling convention requires the return type to be promoted to
Dale Johannesenc9c6da62008-09-25 20:47:45 +0000915 // at least 32-bit. But this is not necessary for non-C calling
916 // conventions.
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000917 if (VT.isInteger()) {
918 MVT MinVT = TLI.getRegisterType(MVT::i32);
919 if (VT.bitsLT(MinVT))
920 VT = MinVT;
921 }
922
923 unsigned NumParts = TLI.getNumRegisters(VT);
924 MVT PartVT = TLI.getRegisterType(VT);
925 SmallVector<SDValue, 4> Parts(NumParts);
926 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
927
928 const Function *F = I.getParent()->getParent();
Devang Patel05988662008-09-25 21:00:45 +0000929 if (F->paramHasAttr(0, Attribute::SExt))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000930 ExtendKind = ISD::SIGN_EXTEND;
Devang Patel05988662008-09-25 21:00:45 +0000931 else if (F->paramHasAttr(0, Attribute::ZExt))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000932 ExtendKind = ISD::ZERO_EXTEND;
933
934 getCopyToParts(DAG, SDValue(RetOp.getNode(), RetOp.getResNo() + j),
935 &Parts[0], NumParts, PartVT, ExtendKind);
936
Dale Johannesenc9c6da62008-09-25 20:47:45 +0000937 // 'inreg' on function refers to return value
938 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
Devang Patel05988662008-09-25 21:00:45 +0000939 if (F->paramHasAttr(0, Attribute::InReg))
Dale Johannesenc9c6da62008-09-25 20:47:45 +0000940 Flags.setInReg();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000941 for (unsigned i = 0; i < NumParts; ++i) {
942 NewValues.push_back(Parts[i]);
Dale Johannesenc9c6da62008-09-25 20:47:45 +0000943 NewValues.push_back(DAG.getArgFlags(Flags));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000944 }
945 }
946 }
947 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other,
948 &NewValues[0], NewValues.size()));
949}
950
951/// ExportFromCurrentBlock - If this condition isn't known to be exported from
952/// the current basic block, add it to ValueMap now so that we'll get a
953/// CopyTo/FromReg.
954void SelectionDAGLowering::ExportFromCurrentBlock(Value *V) {
955 // No need to export constants.
956 if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
957
958 // Already exported?
959 if (FuncInfo.isExportedInst(V)) return;
960
961 unsigned Reg = FuncInfo.InitializeRegForValue(V);
962 CopyValueToVirtualRegister(V, Reg);
963}
964
965bool SelectionDAGLowering::isExportableFromCurrentBlock(Value *V,
966 const BasicBlock *FromBB) {
967 // The operands of the setcc have to be in this block. We don't know
968 // how to export them from some other block.
969 if (Instruction *VI = dyn_cast<Instruction>(V)) {
970 // Can export from current BB.
971 if (VI->getParent() == FromBB)
972 return true;
973
974 // Is already exported, noop.
975 return FuncInfo.isExportedInst(V);
976 }
977
978 // If this is an argument, we can export it if the BB is the entry block or
979 // if it is already exported.
980 if (isa<Argument>(V)) {
981 if (FromBB == &FromBB->getParent()->getEntryBlock())
982 return true;
983
984 // Otherwise, can only export this if it is already exported.
985 return FuncInfo.isExportedInst(V);
986 }
987
988 // Otherwise, constants can always be exported.
989 return true;
990}
991
992static bool InBlock(const Value *V, const BasicBlock *BB) {
993 if (const Instruction *I = dyn_cast<Instruction>(V))
994 return I->getParent() == BB;
995 return true;
996}
997
Dan Gohman8c1a6ca2008-10-17 18:18:45 +0000998/// getFCmpCondCode - Return the ISD condition code corresponding to
999/// the given LLVM IR floating-point condition code. This includes
1000/// consideration of global floating-point math flags.
1001///
1002static ISD::CondCode getFCmpCondCode(FCmpInst::Predicate Pred) {
1003 ISD::CondCode FPC, FOC;
1004 switch (Pred) {
1005 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
1006 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
1007 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
1008 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
1009 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
1010 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
1011 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
1012 case FCmpInst::FCMP_ORD: FOC = FPC = ISD::SETO; break;
1013 case FCmpInst::FCMP_UNO: FOC = FPC = ISD::SETUO; break;
1014 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
1015 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
1016 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
1017 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
1018 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
1019 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
1020 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
1021 default:
1022 assert(0 && "Invalid FCmp predicate opcode!");
1023 FOC = FPC = ISD::SETFALSE;
1024 break;
1025 }
1026 if (FiniteOnlyFPMath())
1027 return FOC;
1028 else
1029 return FPC;
1030}
1031
1032/// getICmpCondCode - Return the ISD condition code corresponding to
1033/// the given LLVM IR integer condition code.
1034///
1035static ISD::CondCode getICmpCondCode(ICmpInst::Predicate Pred) {
1036 switch (Pred) {
1037 case ICmpInst::ICMP_EQ: return ISD::SETEQ;
1038 case ICmpInst::ICMP_NE: return ISD::SETNE;
1039 case ICmpInst::ICMP_SLE: return ISD::SETLE;
1040 case ICmpInst::ICMP_ULE: return ISD::SETULE;
1041 case ICmpInst::ICMP_SGE: return ISD::SETGE;
1042 case ICmpInst::ICMP_UGE: return ISD::SETUGE;
1043 case ICmpInst::ICMP_SLT: return ISD::SETLT;
1044 case ICmpInst::ICMP_ULT: return ISD::SETULT;
1045 case ICmpInst::ICMP_SGT: return ISD::SETGT;
1046 case ICmpInst::ICMP_UGT: return ISD::SETUGT;
1047 default:
1048 assert(0 && "Invalid ICmp predicate opcode!");
1049 return ISD::SETNE;
1050 }
1051}
1052
Dan Gohmanc2277342008-10-17 21:16:08 +00001053/// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
1054/// This function emits a branch and is used at the leaves of an OR or an
1055/// AND operator tree.
1056///
1057void
1058SelectionDAGLowering::EmitBranchForMergedCondition(Value *Cond,
1059 MachineBasicBlock *TBB,
1060 MachineBasicBlock *FBB,
1061 MachineBasicBlock *CurBB) {
1062 const BasicBlock *BB = CurBB->getBasicBlock();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001063
Dan Gohmanc2277342008-10-17 21:16:08 +00001064 // If the leaf of the tree is a comparison, merge the condition into
1065 // the caseblock.
1066 if (CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
1067 // The operands of the cmp have to be in this block. We don't know
1068 // how to export them from some other block. If this is the first block
1069 // of the sequence, no exporting is needed.
1070 if (CurBB == CurMBB ||
1071 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
1072 isExportableFromCurrentBlock(BOp->getOperand(1), BB))) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001073 ISD::CondCode Condition;
1074 if (ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
Dan Gohman8c1a6ca2008-10-17 18:18:45 +00001075 Condition = getICmpCondCode(IC->getPredicate());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001076 } else if (FCmpInst *FC = dyn_cast<FCmpInst>(Cond)) {
Dan Gohman8c1a6ca2008-10-17 18:18:45 +00001077 Condition = getFCmpCondCode(FC->getPredicate());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001078 } else {
1079 Condition = ISD::SETEQ; // silence warning.
1080 assert(0 && "Unknown compare instruction");
1081 }
Dan Gohmanc2277342008-10-17 21:16:08 +00001082
1083 CaseBlock CB(Condition, BOp->getOperand(0),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001084 BOp->getOperand(1), NULL, TBB, FBB, CurBB);
1085 SwitchCases.push_back(CB);
1086 return;
1087 }
Dan Gohmanc2277342008-10-17 21:16:08 +00001088 }
1089
1090 // Create a CaseBlock record representing this branch.
1091 CaseBlock CB(ISD::SETEQ, Cond, ConstantInt::getTrue(),
1092 NULL, TBB, FBB, CurBB);
1093 SwitchCases.push_back(CB);
1094}
1095
1096/// FindMergedConditions - If Cond is an expression like
1097void SelectionDAGLowering::FindMergedConditions(Value *Cond,
1098 MachineBasicBlock *TBB,
1099 MachineBasicBlock *FBB,
1100 MachineBasicBlock *CurBB,
1101 unsigned Opc) {
1102 // If this node is not part of the or/and tree, emit it as a branch.
1103 Instruction *BOp = dyn_cast<Instruction>(Cond);
1104 if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
1105 (unsigned)BOp->getOpcode() != Opc || !BOp->hasOneUse() ||
1106 BOp->getParent() != CurBB->getBasicBlock() ||
1107 !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
1108 !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
1109 EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001110 return;
1111 }
1112
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001113 // Create TmpBB after CurBB.
1114 MachineFunction::iterator BBI = CurBB;
1115 MachineFunction &MF = DAG.getMachineFunction();
1116 MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
1117 CurBB->getParent()->insert(++BBI, TmpBB);
1118
1119 if (Opc == Instruction::Or) {
1120 // Codegen X | Y as:
1121 // jmp_if_X TBB
1122 // jmp TmpBB
1123 // TmpBB:
1124 // jmp_if_Y TBB
1125 // jmp FBB
1126 //
1127
1128 // Emit the LHS condition.
1129 FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, Opc);
1130
1131 // Emit the RHS condition into TmpBB.
1132 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
1133 } else {
1134 assert(Opc == Instruction::And && "Unknown merge op!");
1135 // Codegen X & Y as:
1136 // jmp_if_X TmpBB
1137 // jmp FBB
1138 // TmpBB:
1139 // jmp_if_Y TBB
1140 // jmp FBB
1141 //
1142 // This requires creation of TmpBB after CurBB.
1143
1144 // Emit the LHS condition.
1145 FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, Opc);
1146
1147 // Emit the RHS condition into TmpBB.
1148 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
1149 }
1150}
1151
1152/// If the set of cases should be emitted as a series of branches, return true.
1153/// If we should emit this as a bunch of and/or'd together conditions, return
1154/// false.
1155bool
1156SelectionDAGLowering::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases){
1157 if (Cases.size() != 2) return true;
1158
1159 // If this is two comparisons of the same values or'd or and'd together, they
1160 // will get folded into a single comparison, so don't emit two blocks.
1161 if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
1162 Cases[0].CmpRHS == Cases[1].CmpRHS) ||
1163 (Cases[0].CmpRHS == Cases[1].CmpLHS &&
1164 Cases[0].CmpLHS == Cases[1].CmpRHS)) {
1165 return false;
1166 }
1167
1168 return true;
1169}
1170
1171void SelectionDAGLowering::visitBr(BranchInst &I) {
1172 // Update machine-CFG edges.
1173 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
1174
1175 // Figure out which block is immediately after the current one.
1176 MachineBasicBlock *NextBlock = 0;
1177 MachineFunction::iterator BBI = CurMBB;
1178 if (++BBI != CurMBB->getParent()->end())
1179 NextBlock = BBI;
1180
1181 if (I.isUnconditional()) {
1182 // Update machine-CFG edges.
1183 CurMBB->addSuccessor(Succ0MBB);
1184
1185 // If this is not a fall-through branch, emit the branch.
1186 if (Succ0MBB != NextBlock)
1187 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getControlRoot(),
1188 DAG.getBasicBlock(Succ0MBB)));
1189 return;
1190 }
1191
1192 // If this condition is one of the special cases we handle, do special stuff
1193 // now.
1194 Value *CondVal = I.getCondition();
1195 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
1196
1197 // If this is a series of conditions that are or'd or and'd together, emit
1198 // this as a sequence of branches instead of setcc's with and/or operations.
1199 // For example, instead of something like:
1200 // cmp A, B
1201 // C = seteq
1202 // cmp D, E
1203 // F = setle
1204 // or C, F
1205 // jnz foo
1206 // Emit:
1207 // cmp A, B
1208 // je foo
1209 // cmp D, E
1210 // jle foo
1211 //
1212 if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
1213 if (BOp->hasOneUse() &&
1214 (BOp->getOpcode() == Instruction::And ||
1215 BOp->getOpcode() == Instruction::Or)) {
1216 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, CurMBB, BOp->getOpcode());
1217 // If the compares in later blocks need to use values not currently
1218 // exported from this block, export them now. This block should always
1219 // be the first entry.
1220 assert(SwitchCases[0].ThisBB == CurMBB && "Unexpected lowering!");
1221
1222 // Allow some cases to be rejected.
1223 if (ShouldEmitAsBranches(SwitchCases)) {
1224 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
1225 ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
1226 ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
1227 }
1228
1229 // Emit the branch for this block.
1230 visitSwitchCase(SwitchCases[0]);
1231 SwitchCases.erase(SwitchCases.begin());
1232 return;
1233 }
1234
1235 // Okay, we decided not to do this, remove any inserted MBB's and clear
1236 // SwitchCases.
1237 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
1238 CurMBB->getParent()->erase(SwitchCases[i].ThisBB);
1239
1240 SwitchCases.clear();
1241 }
1242 }
1243
1244 // Create a CaseBlock record representing this branch.
1245 CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(),
1246 NULL, Succ0MBB, Succ1MBB, CurMBB);
1247 // Use visitSwitchCase to actually insert the fast branch sequence for this
1248 // cond branch.
1249 visitSwitchCase(CB);
1250}
1251
1252/// visitSwitchCase - Emits the necessary code to represent a single node in
1253/// the binary search tree resulting from lowering a switch instruction.
1254void SelectionDAGLowering::visitSwitchCase(CaseBlock &CB) {
1255 SDValue Cond;
1256 SDValue CondLHS = getValue(CB.CmpLHS);
1257
1258 // Build the setcc now.
1259 if (CB.CmpMHS == NULL) {
1260 // Fold "(X == true)" to X and "(X == false)" to !X to
1261 // handle common cases produced by branch lowering.
1262 if (CB.CmpRHS == ConstantInt::getTrue() && CB.CC == ISD::SETEQ)
1263 Cond = CondLHS;
1264 else if (CB.CmpRHS == ConstantInt::getFalse() && CB.CC == ISD::SETEQ) {
1265 SDValue True = DAG.getConstant(1, CondLHS.getValueType());
1266 Cond = DAG.getNode(ISD::XOR, CondLHS.getValueType(), CondLHS, True);
1267 } else
1268 Cond = DAG.getSetCC(MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
1269 } else {
1270 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
1271
1272 uint64_t Low = cast<ConstantInt>(CB.CmpLHS)->getSExtValue();
1273 uint64_t High = cast<ConstantInt>(CB.CmpRHS)->getSExtValue();
1274
1275 SDValue CmpOp = getValue(CB.CmpMHS);
1276 MVT VT = CmpOp.getValueType();
1277
1278 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
1279 Cond = DAG.getSetCC(MVT::i1, CmpOp, DAG.getConstant(High, VT), ISD::SETLE);
1280 } else {
1281 SDValue SUB = DAG.getNode(ISD::SUB, VT, CmpOp, DAG.getConstant(Low, VT));
1282 Cond = DAG.getSetCC(MVT::i1, SUB,
1283 DAG.getConstant(High-Low, VT), ISD::SETULE);
1284 }
1285 }
1286
1287 // Update successor info
1288 CurMBB->addSuccessor(CB.TrueBB);
1289 CurMBB->addSuccessor(CB.FalseBB);
1290
1291 // Set NextBlock to be the MBB immediately after the current one, if any.
1292 // This is used to avoid emitting unnecessary branches to the next block.
1293 MachineBasicBlock *NextBlock = 0;
1294 MachineFunction::iterator BBI = CurMBB;
1295 if (++BBI != CurMBB->getParent()->end())
1296 NextBlock = BBI;
1297
1298 // If the lhs block is the next block, invert the condition so that we can
1299 // fall through to the lhs instead of the rhs block.
1300 if (CB.TrueBB == NextBlock) {
1301 std::swap(CB.TrueBB, CB.FalseBB);
1302 SDValue True = DAG.getConstant(1, Cond.getValueType());
1303 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
1304 }
1305 SDValue BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, getControlRoot(), Cond,
1306 DAG.getBasicBlock(CB.TrueBB));
1307
1308 // If the branch was constant folded, fix up the CFG.
1309 if (BrCond.getOpcode() == ISD::BR) {
1310 CurMBB->removeSuccessor(CB.FalseBB);
1311 DAG.setRoot(BrCond);
1312 } else {
1313 // Otherwise, go ahead and insert the false branch.
1314 if (BrCond == getControlRoot())
1315 CurMBB->removeSuccessor(CB.TrueBB);
1316
1317 if (CB.FalseBB == NextBlock)
1318 DAG.setRoot(BrCond);
1319 else
1320 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond,
1321 DAG.getBasicBlock(CB.FalseBB)));
1322 }
1323}
1324
1325/// visitJumpTable - Emit JumpTable node in the current MBB
1326void SelectionDAGLowering::visitJumpTable(JumpTable &JT) {
1327 // Emit the code for the jump table
1328 assert(JT.Reg != -1U && "Should lower JT Header first!");
1329 MVT PTy = TLI.getPointerTy();
1330 SDValue Index = DAG.getCopyFromReg(getControlRoot(), JT.Reg, PTy);
1331 SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
1332 DAG.setRoot(DAG.getNode(ISD::BR_JT, MVT::Other, Index.getValue(1),
1333 Table, Index));
1334 return;
1335}
1336
1337/// visitJumpTableHeader - This function emits necessary code to produce index
1338/// in the JumpTable from switch case.
1339void SelectionDAGLowering::visitJumpTableHeader(JumpTable &JT,
1340 JumpTableHeader &JTH) {
1341 // Subtract the lowest switch case value from the value being switched on
1342 // and conditional branch to default mbb if the result is greater than the
1343 // difference between smallest and largest cases.
1344 SDValue SwitchOp = getValue(JTH.SValue);
1345 MVT VT = SwitchOp.getValueType();
1346 SDValue SUB = DAG.getNode(ISD::SUB, VT, SwitchOp,
1347 DAG.getConstant(JTH.First, VT));
1348
1349 // The SDNode we just created, which holds the value being switched on
1350 // minus the the smallest case value, needs to be copied to a virtual
1351 // register so it can be used as an index into the jump table in a
1352 // subsequent basic block. This value may be smaller or larger than the
1353 // target's pointer type, and therefore require extension or truncating.
1354 if (VT.bitsGT(TLI.getPointerTy()))
1355 SwitchOp = DAG.getNode(ISD::TRUNCATE, TLI.getPointerTy(), SUB);
1356 else
1357 SwitchOp = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(), SUB);
1358
1359 unsigned JumpTableReg = FuncInfo.MakeReg(TLI.getPointerTy());
1360 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), JumpTableReg, SwitchOp);
1361 JT.Reg = JumpTableReg;
1362
1363 // Emit the range check for the jump table, and branch to the default
1364 // block for the switch statement if the value being switched on exceeds
1365 // the largest case in the switch.
1366 SDValue CMP = DAG.getSetCC(TLI.getSetCCResultType(SUB), SUB,
1367 DAG.getConstant(JTH.Last-JTH.First,VT),
1368 ISD::SETUGT);
1369
1370 // Set NextBlock to be the MBB immediately after the current one, if any.
1371 // This is used to avoid emitting unnecessary branches to the next block.
1372 MachineBasicBlock *NextBlock = 0;
1373 MachineFunction::iterator BBI = CurMBB;
1374 if (++BBI != CurMBB->getParent()->end())
1375 NextBlock = BBI;
1376
1377 SDValue BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, CopyTo, CMP,
1378 DAG.getBasicBlock(JT.Default));
1379
1380 if (JT.MBB == NextBlock)
1381 DAG.setRoot(BrCond);
1382 else
1383 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond,
1384 DAG.getBasicBlock(JT.MBB)));
1385
1386 return;
1387}
1388
1389/// visitBitTestHeader - This function emits necessary code to produce value
1390/// suitable for "bit tests"
1391void SelectionDAGLowering::visitBitTestHeader(BitTestBlock &B) {
1392 // Subtract the minimum value
1393 SDValue SwitchOp = getValue(B.SValue);
1394 MVT VT = SwitchOp.getValueType();
1395 SDValue SUB = DAG.getNode(ISD::SUB, VT, SwitchOp,
1396 DAG.getConstant(B.First, VT));
1397
1398 // Check range
1399 SDValue RangeCmp = DAG.getSetCC(TLI.getSetCCResultType(SUB), SUB,
1400 DAG.getConstant(B.Range, VT),
1401 ISD::SETUGT);
1402
1403 SDValue ShiftOp;
1404 if (VT.bitsGT(TLI.getShiftAmountTy()))
1405 ShiftOp = DAG.getNode(ISD::TRUNCATE, TLI.getShiftAmountTy(), SUB);
1406 else
1407 ShiftOp = DAG.getNode(ISD::ZERO_EXTEND, TLI.getShiftAmountTy(), SUB);
1408
1409 // Make desired shift
1410 SDValue SwitchVal = DAG.getNode(ISD::SHL, TLI.getPointerTy(),
1411 DAG.getConstant(1, TLI.getPointerTy()),
1412 ShiftOp);
1413
1414 unsigned SwitchReg = FuncInfo.MakeReg(TLI.getPointerTy());
1415 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), SwitchReg, SwitchVal);
1416 B.Reg = SwitchReg;
1417
1418 // Set NextBlock to be the MBB immediately after the current one, if any.
1419 // This is used to avoid emitting unnecessary branches to the next block.
1420 MachineBasicBlock *NextBlock = 0;
1421 MachineFunction::iterator BBI = CurMBB;
1422 if (++BBI != CurMBB->getParent()->end())
1423 NextBlock = BBI;
1424
1425 MachineBasicBlock* MBB = B.Cases[0].ThisBB;
1426
1427 CurMBB->addSuccessor(B.Default);
1428 CurMBB->addSuccessor(MBB);
1429
1430 SDValue BrRange = DAG.getNode(ISD::BRCOND, MVT::Other, CopyTo, RangeCmp,
1431 DAG.getBasicBlock(B.Default));
1432
1433 if (MBB == NextBlock)
1434 DAG.setRoot(BrRange);
1435 else
1436 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, CopyTo,
1437 DAG.getBasicBlock(MBB)));
1438
1439 return;
1440}
1441
1442/// visitBitTestCase - this function produces one "bit test"
1443void SelectionDAGLowering::visitBitTestCase(MachineBasicBlock* NextMBB,
1444 unsigned Reg,
1445 BitTestCase &B) {
1446 // Emit bit tests and jumps
1447 SDValue SwitchVal = DAG.getCopyFromReg(getControlRoot(), Reg,
1448 TLI.getPointerTy());
1449
1450 SDValue AndOp = DAG.getNode(ISD::AND, TLI.getPointerTy(), SwitchVal,
1451 DAG.getConstant(B.Mask, TLI.getPointerTy()));
1452 SDValue AndCmp = DAG.getSetCC(TLI.getSetCCResultType(AndOp), AndOp,
1453 DAG.getConstant(0, TLI.getPointerTy()),
1454 ISD::SETNE);
1455
1456 CurMBB->addSuccessor(B.TargetBB);
1457 CurMBB->addSuccessor(NextMBB);
1458
1459 SDValue BrAnd = DAG.getNode(ISD::BRCOND, MVT::Other, getControlRoot(),
1460 AndCmp, DAG.getBasicBlock(B.TargetBB));
1461
1462 // Set NextBlock to be the MBB immediately after the current one, if any.
1463 // This is used to avoid emitting unnecessary branches to the next block.
1464 MachineBasicBlock *NextBlock = 0;
1465 MachineFunction::iterator BBI = CurMBB;
1466 if (++BBI != CurMBB->getParent()->end())
1467 NextBlock = BBI;
1468
1469 if (NextMBB == NextBlock)
1470 DAG.setRoot(BrAnd);
1471 else
1472 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrAnd,
1473 DAG.getBasicBlock(NextMBB)));
1474
1475 return;
1476}
1477
1478void SelectionDAGLowering::visitInvoke(InvokeInst &I) {
1479 // Retrieve successors.
1480 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
1481 MachineBasicBlock *LandingPad = FuncInfo.MBBMap[I.getSuccessor(1)];
1482
1483 if (isa<InlineAsm>(I.getCalledValue()))
1484 visitInlineAsm(&I);
1485 else
1486 LowerCallTo(&I, getValue(I.getOperand(0)), false, LandingPad);
1487
1488 // If the value of the invoke is used outside of its defining block, make it
1489 // available as a virtual register.
1490 if (!I.use_empty()) {
1491 DenseMap<const Value*, unsigned>::iterator VMI = FuncInfo.ValueMap.find(&I);
1492 if (VMI != FuncInfo.ValueMap.end())
1493 CopyValueToVirtualRegister(&I, VMI->second);
1494 }
1495
1496 // Update successor info
1497 CurMBB->addSuccessor(Return);
1498 CurMBB->addSuccessor(LandingPad);
1499
1500 // Drop into normal successor.
1501 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getControlRoot(),
1502 DAG.getBasicBlock(Return)));
1503}
1504
1505void SelectionDAGLowering::visitUnwind(UnwindInst &I) {
1506}
1507
1508/// handleSmallSwitchCaseRange - Emit a series of specific tests (suitable for
1509/// small case ranges).
1510bool SelectionDAGLowering::handleSmallSwitchRange(CaseRec& CR,
1511 CaseRecVector& WorkList,
1512 Value* SV,
1513 MachineBasicBlock* Default) {
1514 Case& BackCase = *(CR.Range.second-1);
1515
1516 // Size is the number of Cases represented by this range.
1517 unsigned Size = CR.Range.second - CR.Range.first;
1518 if (Size > 3)
1519 return false;
1520
1521 // Get the MachineFunction which holds the current MBB. This is used when
1522 // inserting any additional MBBs necessary to represent the switch.
1523 MachineFunction *CurMF = CurMBB->getParent();
1524
1525 // Figure out which block is immediately after the current one.
1526 MachineBasicBlock *NextBlock = 0;
1527 MachineFunction::iterator BBI = CR.CaseBB;
1528
1529 if (++BBI != CurMBB->getParent()->end())
1530 NextBlock = BBI;
1531
1532 // TODO: If any two of the cases has the same destination, and if one value
1533 // is the same as the other, but has one bit unset that the other has set,
1534 // use bit manipulation to do two compares at once. For example:
1535 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
1536
1537 // Rearrange the case blocks so that the last one falls through if possible.
1538 if (NextBlock && Default != NextBlock && BackCase.BB != NextBlock) {
1539 // The last case block won't fall through into 'NextBlock' if we emit the
1540 // branches in this order. See if rearranging a case value would help.
1541 for (CaseItr I = CR.Range.first, E = CR.Range.second-1; I != E; ++I) {
1542 if (I->BB == NextBlock) {
1543 std::swap(*I, BackCase);
1544 break;
1545 }
1546 }
1547 }
1548
1549 // Create a CaseBlock record representing a conditional branch to
1550 // the Case's target mbb if the value being switched on SV is equal
1551 // to C.
1552 MachineBasicBlock *CurBlock = CR.CaseBB;
1553 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I) {
1554 MachineBasicBlock *FallThrough;
1555 if (I != E-1) {
1556 FallThrough = CurMF->CreateMachineBasicBlock(CurBlock->getBasicBlock());
1557 CurMF->insert(BBI, FallThrough);
1558 } else {
1559 // If the last case doesn't match, go to the default block.
1560 FallThrough = Default;
1561 }
1562
1563 Value *RHS, *LHS, *MHS;
1564 ISD::CondCode CC;
1565 if (I->High == I->Low) {
1566 // This is just small small case range :) containing exactly 1 case
1567 CC = ISD::SETEQ;
1568 LHS = SV; RHS = I->High; MHS = NULL;
1569 } else {
1570 CC = ISD::SETLE;
1571 LHS = I->Low; MHS = SV; RHS = I->High;
1572 }
1573 CaseBlock CB(CC, LHS, RHS, MHS, I->BB, FallThrough, CurBlock);
1574
1575 // If emitting the first comparison, just call visitSwitchCase to emit the
1576 // code into the current block. Otherwise, push the CaseBlock onto the
1577 // vector to be later processed by SDISel, and insert the node's MBB
1578 // before the next MBB.
1579 if (CurBlock == CurMBB)
1580 visitSwitchCase(CB);
1581 else
1582 SwitchCases.push_back(CB);
1583
1584 CurBlock = FallThrough;
1585 }
1586
1587 return true;
1588}
1589
1590static inline bool areJTsAllowed(const TargetLowering &TLI) {
1591 return !DisableJumpTables &&
1592 (TLI.isOperationLegal(ISD::BR_JT, MVT::Other) ||
1593 TLI.isOperationLegal(ISD::BRIND, MVT::Other));
1594}
1595
1596/// handleJTSwitchCase - Emit jumptable for current switch case range
1597bool SelectionDAGLowering::handleJTSwitchCase(CaseRec& CR,
1598 CaseRecVector& WorkList,
1599 Value* SV,
1600 MachineBasicBlock* Default) {
1601 Case& FrontCase = *CR.Range.first;
1602 Case& BackCase = *(CR.Range.second-1);
1603
1604 int64_t First = cast<ConstantInt>(FrontCase.Low)->getSExtValue();
1605 int64_t Last = cast<ConstantInt>(BackCase.High)->getSExtValue();
1606
1607 uint64_t TSize = 0;
1608 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1609 I!=E; ++I)
1610 TSize += I->size();
1611
1612 if (!areJTsAllowed(TLI) || TSize <= 3)
1613 return false;
1614
1615 double Density = (double)TSize / (double)((Last - First) + 1ULL);
1616 if (Density < 0.4)
1617 return false;
1618
1619 DOUT << "Lowering jump table\n"
1620 << "First entry: " << First << ". Last entry: " << Last << "\n"
1621 << "Size: " << TSize << ". Density: " << Density << "\n\n";
1622
1623 // Get the MachineFunction which holds the current MBB. This is used when
1624 // inserting any additional MBBs necessary to represent the switch.
1625 MachineFunction *CurMF = CurMBB->getParent();
1626
1627 // Figure out which block is immediately after the current one.
1628 MachineBasicBlock *NextBlock = 0;
1629 MachineFunction::iterator BBI = CR.CaseBB;
1630
1631 if (++BBI != CurMBB->getParent()->end())
1632 NextBlock = BBI;
1633
1634 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1635
1636 // Create a new basic block to hold the code for loading the address
1637 // of the jump table, and jumping to it. Update successor information;
1638 // we will either branch to the default case for the switch, or the jump
1639 // table.
1640 MachineBasicBlock *JumpTableBB = CurMF->CreateMachineBasicBlock(LLVMBB);
1641 CurMF->insert(BBI, JumpTableBB);
1642 CR.CaseBB->addSuccessor(Default);
1643 CR.CaseBB->addSuccessor(JumpTableBB);
1644
1645 // Build a vector of destination BBs, corresponding to each target
1646 // of the jump table. If the value of the jump table slot corresponds to
1647 // a case statement, push the case's BB onto the vector, otherwise, push
1648 // the default BB.
1649 std::vector<MachineBasicBlock*> DestBBs;
1650 int64_t TEI = First;
1651 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++TEI) {
1652 int64_t Low = cast<ConstantInt>(I->Low)->getSExtValue();
1653 int64_t High = cast<ConstantInt>(I->High)->getSExtValue();
1654
1655 if ((Low <= TEI) && (TEI <= High)) {
1656 DestBBs.push_back(I->BB);
1657 if (TEI==High)
1658 ++I;
1659 } else {
1660 DestBBs.push_back(Default);
1661 }
1662 }
1663
1664 // Update successor info. Add one edge to each unique successor.
1665 BitVector SuccsHandled(CR.CaseBB->getParent()->getNumBlockIDs());
1666 for (std::vector<MachineBasicBlock*>::iterator I = DestBBs.begin(),
1667 E = DestBBs.end(); I != E; ++I) {
1668 if (!SuccsHandled[(*I)->getNumber()]) {
1669 SuccsHandled[(*I)->getNumber()] = true;
1670 JumpTableBB->addSuccessor(*I);
1671 }
1672 }
1673
1674 // Create a jump table index for this jump table, or return an existing
1675 // one.
1676 unsigned JTI = CurMF->getJumpTableInfo()->getJumpTableIndex(DestBBs);
1677
1678 // Set the jump table information so that we can codegen it as a second
1679 // MachineBasicBlock
1680 JumpTable JT(-1U, JTI, JumpTableBB, Default);
1681 JumpTableHeader JTH(First, Last, SV, CR.CaseBB, (CR.CaseBB == CurMBB));
1682 if (CR.CaseBB == CurMBB)
1683 visitJumpTableHeader(JT, JTH);
1684
1685 JTCases.push_back(JumpTableBlock(JTH, JT));
1686
1687 return true;
1688}
1689
1690/// handleBTSplitSwitchCase - emit comparison and split binary search tree into
1691/// 2 subtrees.
1692bool SelectionDAGLowering::handleBTSplitSwitchCase(CaseRec& CR,
1693 CaseRecVector& WorkList,
1694 Value* SV,
1695 MachineBasicBlock* Default) {
1696 // Get the MachineFunction which holds the current MBB. This is used when
1697 // inserting any additional MBBs necessary to represent the switch.
1698 MachineFunction *CurMF = CurMBB->getParent();
1699
1700 // Figure out which block is immediately after the current one.
1701 MachineBasicBlock *NextBlock = 0;
1702 MachineFunction::iterator BBI = CR.CaseBB;
1703
1704 if (++BBI != CurMBB->getParent()->end())
1705 NextBlock = BBI;
1706
1707 Case& FrontCase = *CR.Range.first;
1708 Case& BackCase = *(CR.Range.second-1);
1709 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1710
1711 // Size is the number of Cases represented by this range.
1712 unsigned Size = CR.Range.second - CR.Range.first;
1713
1714 int64_t First = cast<ConstantInt>(FrontCase.Low)->getSExtValue();
1715 int64_t Last = cast<ConstantInt>(BackCase.High)->getSExtValue();
1716 double FMetric = 0;
1717 CaseItr Pivot = CR.Range.first + Size/2;
1718
1719 // Select optimal pivot, maximizing sum density of LHS and RHS. This will
1720 // (heuristically) allow us to emit JumpTable's later.
1721 uint64_t TSize = 0;
1722 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1723 I!=E; ++I)
1724 TSize += I->size();
1725
1726 uint64_t LSize = FrontCase.size();
1727 uint64_t RSize = TSize-LSize;
1728 DOUT << "Selecting best pivot: \n"
1729 << "First: " << First << ", Last: " << Last <<"\n"
1730 << "LSize: " << LSize << ", RSize: " << RSize << "\n";
1731 for (CaseItr I = CR.Range.first, J=I+1, E = CR.Range.second;
1732 J!=E; ++I, ++J) {
1733 int64_t LEnd = cast<ConstantInt>(I->High)->getSExtValue();
1734 int64_t RBegin = cast<ConstantInt>(J->Low)->getSExtValue();
1735 assert((RBegin-LEnd>=1) && "Invalid case distance");
1736 double LDensity = (double)LSize / (double)((LEnd - First) + 1ULL);
1737 double RDensity = (double)RSize / (double)((Last - RBegin) + 1ULL);
1738 double Metric = Log2_64(RBegin-LEnd)*(LDensity+RDensity);
1739 // Should always split in some non-trivial place
1740 DOUT <<"=>Step\n"
1741 << "LEnd: " << LEnd << ", RBegin: " << RBegin << "\n"
1742 << "LDensity: " << LDensity << ", RDensity: " << RDensity << "\n"
1743 << "Metric: " << Metric << "\n";
1744 if (FMetric < Metric) {
1745 Pivot = J;
1746 FMetric = Metric;
1747 DOUT << "Current metric set to: " << FMetric << "\n";
1748 }
1749
1750 LSize += J->size();
1751 RSize -= J->size();
1752 }
1753 if (areJTsAllowed(TLI)) {
1754 // If our case is dense we *really* should handle it earlier!
1755 assert((FMetric > 0) && "Should handle dense range earlier!");
1756 } else {
1757 Pivot = CR.Range.first + Size/2;
1758 }
1759
1760 CaseRange LHSR(CR.Range.first, Pivot);
1761 CaseRange RHSR(Pivot, CR.Range.second);
1762 Constant *C = Pivot->Low;
1763 MachineBasicBlock *FalseBB = 0, *TrueBB = 0;
1764
1765 // We know that we branch to the LHS if the Value being switched on is
1766 // less than the Pivot value, C. We use this to optimize our binary
1767 // tree a bit, by recognizing that if SV is greater than or equal to the
1768 // LHS's Case Value, and that Case Value is exactly one less than the
1769 // Pivot's Value, then we can branch directly to the LHS's Target,
1770 // rather than creating a leaf node for it.
1771 if ((LHSR.second - LHSR.first) == 1 &&
1772 LHSR.first->High == CR.GE &&
1773 cast<ConstantInt>(C)->getSExtValue() ==
1774 (cast<ConstantInt>(CR.GE)->getSExtValue() + 1LL)) {
1775 TrueBB = LHSR.first->BB;
1776 } else {
1777 TrueBB = CurMF->CreateMachineBasicBlock(LLVMBB);
1778 CurMF->insert(BBI, TrueBB);
1779 WorkList.push_back(CaseRec(TrueBB, C, CR.GE, LHSR));
1780 }
1781
1782 // Similar to the optimization above, if the Value being switched on is
1783 // known to be less than the Constant CR.LT, and the current Case Value
1784 // is CR.LT - 1, then we can branch directly to the target block for
1785 // the current Case Value, rather than emitting a RHS leaf node for it.
1786 if ((RHSR.second - RHSR.first) == 1 && CR.LT &&
1787 cast<ConstantInt>(RHSR.first->Low)->getSExtValue() ==
1788 (cast<ConstantInt>(CR.LT)->getSExtValue() - 1LL)) {
1789 FalseBB = RHSR.first->BB;
1790 } else {
1791 FalseBB = CurMF->CreateMachineBasicBlock(LLVMBB);
1792 CurMF->insert(BBI, FalseBB);
1793 WorkList.push_back(CaseRec(FalseBB,CR.LT,C,RHSR));
1794 }
1795
1796 // Create a CaseBlock record representing a conditional branch to
1797 // the LHS node if the value being switched on SV is less than C.
1798 // Otherwise, branch to LHS.
1799 CaseBlock CB(ISD::SETLT, SV, C, NULL, TrueBB, FalseBB, CR.CaseBB);
1800
1801 if (CR.CaseBB == CurMBB)
1802 visitSwitchCase(CB);
1803 else
1804 SwitchCases.push_back(CB);
1805
1806 return true;
1807}
1808
1809/// handleBitTestsSwitchCase - if current case range has few destination and
1810/// range span less, than machine word bitwidth, encode case range into series
1811/// of masks and emit bit tests with these masks.
1812bool SelectionDAGLowering::handleBitTestsSwitchCase(CaseRec& CR,
1813 CaseRecVector& WorkList,
1814 Value* SV,
1815 MachineBasicBlock* Default){
1816 unsigned IntPtrBits = TLI.getPointerTy().getSizeInBits();
1817
1818 Case& FrontCase = *CR.Range.first;
1819 Case& BackCase = *(CR.Range.second-1);
1820
1821 // Get the MachineFunction which holds the current MBB. This is used when
1822 // inserting any additional MBBs necessary to represent the switch.
1823 MachineFunction *CurMF = CurMBB->getParent();
1824
1825 unsigned numCmps = 0;
1826 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1827 I!=E; ++I) {
1828 // Single case counts one, case range - two.
1829 if (I->Low == I->High)
1830 numCmps +=1;
1831 else
1832 numCmps +=2;
1833 }
1834
1835 // Count unique destinations
1836 SmallSet<MachineBasicBlock*, 4> Dests;
1837 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
1838 Dests.insert(I->BB);
1839 if (Dests.size() > 3)
1840 // Don't bother the code below, if there are too much unique destinations
1841 return false;
1842 }
1843 DOUT << "Total number of unique destinations: " << Dests.size() << "\n"
1844 << "Total number of comparisons: " << numCmps << "\n";
1845
1846 // Compute span of values.
1847 Constant* minValue = FrontCase.Low;
1848 Constant* maxValue = BackCase.High;
1849 uint64_t range = cast<ConstantInt>(maxValue)->getSExtValue() -
1850 cast<ConstantInt>(minValue)->getSExtValue();
1851 DOUT << "Compare range: " << range << "\n"
1852 << "Low bound: " << cast<ConstantInt>(minValue)->getSExtValue() << "\n"
1853 << "High bound: " << cast<ConstantInt>(maxValue)->getSExtValue() << "\n";
1854
1855 if (range>=IntPtrBits ||
1856 (!(Dests.size() == 1 && numCmps >= 3) &&
1857 !(Dests.size() == 2 && numCmps >= 5) &&
1858 !(Dests.size() >= 3 && numCmps >= 6)))
1859 return false;
1860
1861 DOUT << "Emitting bit tests\n";
1862 int64_t lowBound = 0;
1863
1864 // Optimize the case where all the case values fit in a
1865 // word without having to subtract minValue. In this case,
1866 // we can optimize away the subtraction.
1867 if (cast<ConstantInt>(minValue)->getSExtValue() >= 0 &&
1868 cast<ConstantInt>(maxValue)->getSExtValue() < IntPtrBits) {
1869 range = cast<ConstantInt>(maxValue)->getSExtValue();
1870 } else {
1871 lowBound = cast<ConstantInt>(minValue)->getSExtValue();
1872 }
1873
1874 CaseBitsVector CasesBits;
1875 unsigned i, count = 0;
1876
1877 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
1878 MachineBasicBlock* Dest = I->BB;
1879 for (i = 0; i < count; ++i)
1880 if (Dest == CasesBits[i].BB)
1881 break;
1882
1883 if (i == count) {
1884 assert((count < 3) && "Too much destinations to test!");
1885 CasesBits.push_back(CaseBits(0, Dest, 0));
1886 count++;
1887 }
1888
1889 uint64_t lo = cast<ConstantInt>(I->Low)->getSExtValue() - lowBound;
1890 uint64_t hi = cast<ConstantInt>(I->High)->getSExtValue() - lowBound;
1891
1892 for (uint64_t j = lo; j <= hi; j++) {
1893 CasesBits[i].Mask |= 1ULL << j;
1894 CasesBits[i].Bits++;
1895 }
1896
1897 }
1898 std::sort(CasesBits.begin(), CasesBits.end(), CaseBitsCmp());
1899
1900 BitTestInfo BTC;
1901
1902 // Figure out which block is immediately after the current one.
1903 MachineFunction::iterator BBI = CR.CaseBB;
1904 ++BBI;
1905
1906 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1907
1908 DOUT << "Cases:\n";
1909 for (unsigned i = 0, e = CasesBits.size(); i!=e; ++i) {
1910 DOUT << "Mask: " << CasesBits[i].Mask << ", Bits: " << CasesBits[i].Bits
1911 << ", BB: " << CasesBits[i].BB << "\n";
1912
1913 MachineBasicBlock *CaseBB = CurMF->CreateMachineBasicBlock(LLVMBB);
1914 CurMF->insert(BBI, CaseBB);
1915 BTC.push_back(BitTestCase(CasesBits[i].Mask,
1916 CaseBB,
1917 CasesBits[i].BB));
1918 }
1919
1920 BitTestBlock BTB(lowBound, range, SV,
1921 -1U, (CR.CaseBB == CurMBB),
1922 CR.CaseBB, Default, BTC);
1923
1924 if (CR.CaseBB == CurMBB)
1925 visitBitTestHeader(BTB);
1926
1927 BitTestCases.push_back(BTB);
1928
1929 return true;
1930}
1931
1932
1933/// Clusterify - Transform simple list of Cases into list of CaseRange's
1934unsigned SelectionDAGLowering::Clusterify(CaseVector& Cases,
1935 const SwitchInst& SI) {
1936 unsigned numCmps = 0;
1937
1938 // Start with "simple" cases
1939 for (unsigned i = 1; i < SI.getNumSuccessors(); ++i) {
1940 MachineBasicBlock *SMBB = FuncInfo.MBBMap[SI.getSuccessor(i)];
1941 Cases.push_back(Case(SI.getSuccessorValue(i),
1942 SI.getSuccessorValue(i),
1943 SMBB));
1944 }
1945 std::sort(Cases.begin(), Cases.end(), CaseCmp());
1946
1947 // Merge case into clusters
1948 if (Cases.size()>=2)
1949 // Must recompute end() each iteration because it may be
1950 // invalidated by erase if we hold on to it
1951 for (CaseItr I=Cases.begin(), J=++(Cases.begin()); J!=Cases.end(); ) {
1952 int64_t nextValue = cast<ConstantInt>(J->Low)->getSExtValue();
1953 int64_t currentValue = cast<ConstantInt>(I->High)->getSExtValue();
1954 MachineBasicBlock* nextBB = J->BB;
1955 MachineBasicBlock* currentBB = I->BB;
1956
1957 // If the two neighboring cases go to the same destination, merge them
1958 // into a single case.
1959 if ((nextValue-currentValue==1) && (currentBB == nextBB)) {
1960 I->High = J->High;
1961 J = Cases.erase(J);
1962 } else {
1963 I = J++;
1964 }
1965 }
1966
1967 for (CaseItr I=Cases.begin(), E=Cases.end(); I!=E; ++I, ++numCmps) {
1968 if (I->Low != I->High)
1969 // A range counts double, since it requires two compares.
1970 ++numCmps;
1971 }
1972
1973 return numCmps;
1974}
1975
1976void SelectionDAGLowering::visitSwitch(SwitchInst &SI) {
1977 // Figure out which block is immediately after the current one.
1978 MachineBasicBlock *NextBlock = 0;
1979 MachineFunction::iterator BBI = CurMBB;
1980
1981 MachineBasicBlock *Default = FuncInfo.MBBMap[SI.getDefaultDest()];
1982
1983 // If there is only the default destination, branch to it if it is not the
1984 // next basic block. Otherwise, just fall through.
1985 if (SI.getNumOperands() == 2) {
1986 // Update machine-CFG edges.
1987
1988 // If this is not a fall-through branch, emit the branch.
1989 CurMBB->addSuccessor(Default);
1990 if (Default != NextBlock)
1991 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getControlRoot(),
1992 DAG.getBasicBlock(Default)));
1993
1994 return;
1995 }
1996
1997 // If there are any non-default case statements, create a vector of Cases
1998 // representing each one, and sort the vector so that we can efficiently
1999 // create a binary search tree from them.
2000 CaseVector Cases;
2001 unsigned numCmps = Clusterify(Cases, SI);
2002 DOUT << "Clusterify finished. Total clusters: " << Cases.size()
2003 << ". Total compares: " << numCmps << "\n";
2004
2005 // Get the Value to be switched on and default basic blocks, which will be
2006 // inserted into CaseBlock records, representing basic blocks in the binary
2007 // search tree.
2008 Value *SV = SI.getOperand(0);
2009
2010 // Push the initial CaseRec onto the worklist
2011 CaseRecVector WorkList;
2012 WorkList.push_back(CaseRec(CurMBB,0,0,CaseRange(Cases.begin(),Cases.end())));
2013
2014 while (!WorkList.empty()) {
2015 // Grab a record representing a case range to process off the worklist
2016 CaseRec CR = WorkList.back();
2017 WorkList.pop_back();
2018
2019 if (handleBitTestsSwitchCase(CR, WorkList, SV, Default))
2020 continue;
2021
2022 // If the range has few cases (two or less) emit a series of specific
2023 // tests.
2024 if (handleSmallSwitchRange(CR, WorkList, SV, Default))
2025 continue;
2026
2027 // If the switch has more than 5 blocks, and at least 40% dense, and the
2028 // target supports indirect branches, then emit a jump table rather than
2029 // lowering the switch to a binary tree of conditional branches.
2030 if (handleJTSwitchCase(CR, WorkList, SV, Default))
2031 continue;
2032
2033 // Emit binary tree. We need to pick a pivot, and push left and right ranges
2034 // onto the worklist. Leafs are handled via handleSmallSwitchRange() call.
2035 handleBTSplitSwitchCase(CR, WorkList, SV, Default);
2036 }
2037}
2038
2039
2040void SelectionDAGLowering::visitSub(User &I) {
2041 // -0.0 - X --> fneg
2042 const Type *Ty = I.getType();
2043 if (isa<VectorType>(Ty)) {
2044 if (ConstantVector *CV = dyn_cast<ConstantVector>(I.getOperand(0))) {
2045 const VectorType *DestTy = cast<VectorType>(I.getType());
2046 const Type *ElTy = DestTy->getElementType();
2047 if (ElTy->isFloatingPoint()) {
2048 unsigned VL = DestTy->getNumElements();
2049 std::vector<Constant*> NZ(VL, ConstantFP::getNegativeZero(ElTy));
2050 Constant *CNZ = ConstantVector::get(&NZ[0], NZ.size());
2051 if (CV == CNZ) {
2052 SDValue Op2 = getValue(I.getOperand(1));
2053 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
2054 return;
2055 }
2056 }
2057 }
2058 }
2059 if (Ty->isFloatingPoint()) {
2060 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
2061 if (CFP->isExactlyValue(ConstantFP::getNegativeZero(Ty)->getValueAPF())) {
2062 SDValue Op2 = getValue(I.getOperand(1));
2063 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
2064 return;
2065 }
2066 }
2067
2068 visitBinary(I, Ty->isFPOrFPVector() ? ISD::FSUB : ISD::SUB);
2069}
2070
2071void SelectionDAGLowering::visitBinary(User &I, unsigned OpCode) {
2072 SDValue Op1 = getValue(I.getOperand(0));
2073 SDValue Op2 = getValue(I.getOperand(1));
2074
2075 setValue(&I, DAG.getNode(OpCode, Op1.getValueType(), Op1, Op2));
2076}
2077
2078void SelectionDAGLowering::visitShift(User &I, unsigned Opcode) {
2079 SDValue Op1 = getValue(I.getOperand(0));
2080 SDValue Op2 = getValue(I.getOperand(1));
2081 if (!isa<VectorType>(I.getType())) {
2082 if (TLI.getShiftAmountTy().bitsLT(Op2.getValueType()))
2083 Op2 = DAG.getNode(ISD::TRUNCATE, TLI.getShiftAmountTy(), Op2);
2084 else if (TLI.getShiftAmountTy().bitsGT(Op2.getValueType()))
2085 Op2 = DAG.getNode(ISD::ANY_EXTEND, TLI.getShiftAmountTy(), Op2);
2086 }
2087
2088 setValue(&I, DAG.getNode(Opcode, Op1.getValueType(), Op1, Op2));
2089}
2090
2091void SelectionDAGLowering::visitICmp(User &I) {
2092 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
2093 if (ICmpInst *IC = dyn_cast<ICmpInst>(&I))
2094 predicate = IC->getPredicate();
2095 else if (ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
2096 predicate = ICmpInst::Predicate(IC->getPredicate());
2097 SDValue Op1 = getValue(I.getOperand(0));
2098 SDValue Op2 = getValue(I.getOperand(1));
Dan Gohman8c1a6ca2008-10-17 18:18:45 +00002099 ISD::CondCode Opcode = getICmpCondCode(predicate);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002100 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Opcode));
2101}
2102
2103void SelectionDAGLowering::visitFCmp(User &I) {
2104 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
2105 if (FCmpInst *FC = dyn_cast<FCmpInst>(&I))
2106 predicate = FC->getPredicate();
2107 else if (ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
2108 predicate = FCmpInst::Predicate(FC->getPredicate());
2109 SDValue Op1 = getValue(I.getOperand(0));
2110 SDValue Op2 = getValue(I.getOperand(1));
Dan Gohman8c1a6ca2008-10-17 18:18:45 +00002111 ISD::CondCode Condition = getFCmpCondCode(predicate);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002112 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Condition));
2113}
2114
2115void SelectionDAGLowering::visitVICmp(User &I) {
2116 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
2117 if (VICmpInst *IC = dyn_cast<VICmpInst>(&I))
2118 predicate = IC->getPredicate();
2119 else if (ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
2120 predicate = ICmpInst::Predicate(IC->getPredicate());
2121 SDValue Op1 = getValue(I.getOperand(0));
2122 SDValue Op2 = getValue(I.getOperand(1));
Dan Gohman8c1a6ca2008-10-17 18:18:45 +00002123 ISD::CondCode Opcode = getICmpCondCode(predicate);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002124 setValue(&I, DAG.getVSetCC(Op1.getValueType(), Op1, Op2, Opcode));
2125}
2126
2127void SelectionDAGLowering::visitVFCmp(User &I) {
2128 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
2129 if (VFCmpInst *FC = dyn_cast<VFCmpInst>(&I))
2130 predicate = FC->getPredicate();
2131 else if (ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
2132 predicate = FCmpInst::Predicate(FC->getPredicate());
2133 SDValue Op1 = getValue(I.getOperand(0));
2134 SDValue Op2 = getValue(I.getOperand(1));
Dan Gohman8c1a6ca2008-10-17 18:18:45 +00002135 ISD::CondCode Condition = getFCmpCondCode(predicate);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002136 MVT DestVT = TLI.getValueType(I.getType());
2137
2138 setValue(&I, DAG.getVSetCC(DestVT, Op1, Op2, Condition));
2139}
2140
2141void SelectionDAGLowering::visitSelect(User &I) {
Dan Gohman7ea1ca62008-10-21 20:00:42 +00002142 SmallVector<MVT, 4> ValueVTs;
2143 ComputeValueVTs(TLI, I.getType(), ValueVTs);
2144 unsigned NumValues = ValueVTs.size();
2145 if (NumValues != 0) {
2146 SmallVector<SDValue, 4> Values(NumValues);
2147 SDValue Cond = getValue(I.getOperand(0));
2148 SDValue TrueVal = getValue(I.getOperand(1));
2149 SDValue FalseVal = getValue(I.getOperand(2));
2150
2151 for (unsigned i = 0; i != NumValues; ++i)
2152 Values[i] = DAG.getNode(ISD::SELECT, TrueVal.getValueType(), Cond,
2153 SDValue(TrueVal.getNode(), TrueVal.getResNo() + i),
2154 SDValue(FalseVal.getNode(), FalseVal.getResNo() + i));
2155
2156 setValue(&I, DAG.getMergeValues(DAG.getVTList(&ValueVTs[0], NumValues),
2157 &Values[0], NumValues));
2158 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002159}
2160
2161
2162void SelectionDAGLowering::visitTrunc(User &I) {
2163 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
2164 SDValue N = getValue(I.getOperand(0));
2165 MVT DestVT = TLI.getValueType(I.getType());
2166 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
2167}
2168
2169void SelectionDAGLowering::visitZExt(User &I) {
2170 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2171 // ZExt also can't be a cast to bool for same reason. So, nothing much to do
2172 SDValue N = getValue(I.getOperand(0));
2173 MVT DestVT = TLI.getValueType(I.getType());
2174 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
2175}
2176
2177void SelectionDAGLowering::visitSExt(User &I) {
2178 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2179 // SExt also can't be a cast to bool for same reason. So, nothing much to do
2180 SDValue N = getValue(I.getOperand(0));
2181 MVT DestVT = TLI.getValueType(I.getType());
2182 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, DestVT, N));
2183}
2184
2185void SelectionDAGLowering::visitFPTrunc(User &I) {
2186 // FPTrunc 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_ROUND, DestVT, N, DAG.getIntPtrConstant(0)));
2190}
2191
2192void SelectionDAGLowering::visitFPExt(User &I){
2193 // FPTrunc 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_EXTEND, DestVT, N));
2197}
2198
2199void SelectionDAGLowering::visitFPToUI(User &I) {
2200 // FPToUI 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::FP_TO_UINT, DestVT, N));
2204}
2205
2206void SelectionDAGLowering::visitFPToSI(User &I) {
2207 // FPToSI is never a no-op cast, no need to check
2208 SDValue N = getValue(I.getOperand(0));
2209 MVT DestVT = TLI.getValueType(I.getType());
2210 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, DestVT, N));
2211}
2212
2213void SelectionDAGLowering::visitUIToFP(User &I) {
2214 // UIToFP is never a no-op cast, no need to check
2215 SDValue N = getValue(I.getOperand(0));
2216 MVT DestVT = TLI.getValueType(I.getType());
2217 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, DestVT, N));
2218}
2219
2220void SelectionDAGLowering::visitSIToFP(User &I){
Bill Wendling181b6272008-10-19 20:34:04 +00002221 // SIToFP is never a no-op cast, no need to check
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002222 SDValue N = getValue(I.getOperand(0));
2223 MVT DestVT = TLI.getValueType(I.getType());
2224 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, DestVT, N));
2225}
2226
2227void SelectionDAGLowering::visitPtrToInt(User &I) {
2228 // What to do depends on the size of the integer and the size of the pointer.
2229 // We can either truncate, zero extend, or no-op, accordingly.
2230 SDValue N = getValue(I.getOperand(0));
2231 MVT SrcVT = N.getValueType();
2232 MVT DestVT = TLI.getValueType(I.getType());
2233 SDValue Result;
2234 if (DestVT.bitsLT(SrcVT))
2235 Result = DAG.getNode(ISD::TRUNCATE, DestVT, N);
2236 else
2237 // Note: ZERO_EXTEND can handle cases where the sizes are equal too
2238 Result = DAG.getNode(ISD::ZERO_EXTEND, DestVT, N);
2239 setValue(&I, Result);
2240}
2241
2242void SelectionDAGLowering::visitIntToPtr(User &I) {
2243 // What to do depends on the size of the integer and the size of the pointer.
2244 // We can either truncate, zero extend, or no-op, accordingly.
2245 SDValue N = getValue(I.getOperand(0));
2246 MVT SrcVT = N.getValueType();
2247 MVT DestVT = TLI.getValueType(I.getType());
2248 if (DestVT.bitsLT(SrcVT))
2249 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
2250 else
2251 // Note: ZERO_EXTEND can handle cases where the sizes are equal too
2252 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
2253}
2254
2255void SelectionDAGLowering::visitBitCast(User &I) {
2256 SDValue N = getValue(I.getOperand(0));
2257 MVT DestVT = TLI.getValueType(I.getType());
2258
2259 // BitCast assures us that source and destination are the same size so this
2260 // is either a BIT_CONVERT or a no-op.
2261 if (DestVT != N.getValueType())
2262 setValue(&I, DAG.getNode(ISD::BIT_CONVERT, DestVT, N)); // convert types
2263 else
2264 setValue(&I, N); // noop cast.
2265}
2266
2267void SelectionDAGLowering::visitInsertElement(User &I) {
2268 SDValue InVec = getValue(I.getOperand(0));
2269 SDValue InVal = getValue(I.getOperand(1));
2270 SDValue InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
2271 getValue(I.getOperand(2)));
2272
2273 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT,
2274 TLI.getValueType(I.getType()),
2275 InVec, InVal, InIdx));
2276}
2277
2278void SelectionDAGLowering::visitExtractElement(User &I) {
2279 SDValue InVec = getValue(I.getOperand(0));
2280 SDValue InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
2281 getValue(I.getOperand(1)));
2282 setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
2283 TLI.getValueType(I.getType()), InVec, InIdx));
2284}
2285
2286void SelectionDAGLowering::visitShuffleVector(User &I) {
2287 SDValue V1 = getValue(I.getOperand(0));
2288 SDValue V2 = getValue(I.getOperand(1));
2289 SDValue Mask = getValue(I.getOperand(2));
2290
2291 setValue(&I, DAG.getNode(ISD::VECTOR_SHUFFLE,
2292 TLI.getValueType(I.getType()),
2293 V1, V2, Mask));
2294}
2295
2296void SelectionDAGLowering::visitInsertValue(InsertValueInst &I) {
2297 const Value *Op0 = I.getOperand(0);
2298 const Value *Op1 = I.getOperand(1);
2299 const Type *AggTy = I.getType();
2300 const Type *ValTy = Op1->getType();
2301 bool IntoUndef = isa<UndefValue>(Op0);
2302 bool FromUndef = isa<UndefValue>(Op1);
2303
2304 unsigned LinearIndex = ComputeLinearIndex(TLI, AggTy,
2305 I.idx_begin(), I.idx_end());
2306
2307 SmallVector<MVT, 4> AggValueVTs;
2308 ComputeValueVTs(TLI, AggTy, AggValueVTs);
2309 SmallVector<MVT, 4> ValValueVTs;
2310 ComputeValueVTs(TLI, ValTy, ValValueVTs);
2311
2312 unsigned NumAggValues = AggValueVTs.size();
2313 unsigned NumValValues = ValValueVTs.size();
2314 SmallVector<SDValue, 4> Values(NumAggValues);
2315
2316 SDValue Agg = getValue(Op0);
2317 SDValue Val = getValue(Op1);
2318 unsigned i = 0;
2319 // Copy the beginning value(s) from the original aggregate.
2320 for (; i != LinearIndex; ++i)
2321 Values[i] = IntoUndef ? DAG.getNode(ISD::UNDEF, AggValueVTs[i]) :
2322 SDValue(Agg.getNode(), Agg.getResNo() + i);
2323 // Copy values from the inserted value(s).
2324 for (; i != LinearIndex + NumValValues; ++i)
2325 Values[i] = FromUndef ? DAG.getNode(ISD::UNDEF, AggValueVTs[i]) :
2326 SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
2327 // Copy remaining value(s) from the original aggregate.
2328 for (; i != NumAggValues; ++i)
2329 Values[i] = IntoUndef ? DAG.getNode(ISD::UNDEF, AggValueVTs[i]) :
2330 SDValue(Agg.getNode(), Agg.getResNo() + i);
2331
2332 setValue(&I, DAG.getMergeValues(DAG.getVTList(&AggValueVTs[0], NumAggValues),
2333 &Values[0], NumAggValues));
2334}
2335
2336void SelectionDAGLowering::visitExtractValue(ExtractValueInst &I) {
2337 const Value *Op0 = I.getOperand(0);
2338 const Type *AggTy = Op0->getType();
2339 const Type *ValTy = I.getType();
2340 bool OutOfUndef = isa<UndefValue>(Op0);
2341
2342 unsigned LinearIndex = ComputeLinearIndex(TLI, AggTy,
2343 I.idx_begin(), I.idx_end());
2344
2345 SmallVector<MVT, 4> ValValueVTs;
2346 ComputeValueVTs(TLI, ValTy, ValValueVTs);
2347
2348 unsigned NumValValues = ValValueVTs.size();
2349 SmallVector<SDValue, 4> Values(NumValValues);
2350
2351 SDValue Agg = getValue(Op0);
2352 // Copy out the selected value(s).
2353 for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
2354 Values[i - LinearIndex] =
2355 OutOfUndef ? DAG.getNode(ISD::UNDEF, Agg.getNode()->getValueType(Agg.getResNo() + i)) :
2356 SDValue(Agg.getNode(), Agg.getResNo() + i);
2357
2358 setValue(&I, DAG.getMergeValues(DAG.getVTList(&ValValueVTs[0], NumValValues),
2359 &Values[0], NumValValues));
2360}
2361
2362
2363void SelectionDAGLowering::visitGetElementPtr(User &I) {
2364 SDValue N = getValue(I.getOperand(0));
2365 const Type *Ty = I.getOperand(0)->getType();
2366
2367 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
2368 OI != E; ++OI) {
2369 Value *Idx = *OI;
2370 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
2371 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
2372 if (Field) {
2373 // N = N + Offset
2374 uint64_t Offset = TD->getStructLayout(StTy)->getElementOffset(Field);
2375 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
2376 DAG.getIntPtrConstant(Offset));
2377 }
2378 Ty = StTy->getElementType(Field);
2379 } else {
2380 Ty = cast<SequentialType>(Ty)->getElementType();
2381
2382 // If this is a constant subscript, handle it quickly.
2383 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
2384 if (CI->getZExtValue() == 0) continue;
2385 uint64_t Offs =
2386 TD->getABITypeSize(Ty)*cast<ConstantInt>(CI)->getSExtValue();
2387 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
2388 DAG.getIntPtrConstant(Offs));
2389 continue;
2390 }
2391
2392 // N = N + Idx * ElementSize;
2393 uint64_t ElementSize = TD->getABITypeSize(Ty);
2394 SDValue IdxN = getValue(Idx);
2395
2396 // If the index is smaller or larger than intptr_t, truncate or extend
2397 // it.
2398 if (IdxN.getValueType().bitsLT(N.getValueType()))
2399 IdxN = DAG.getNode(ISD::SIGN_EXTEND, N.getValueType(), IdxN);
2400 else if (IdxN.getValueType().bitsGT(N.getValueType()))
2401 IdxN = DAG.getNode(ISD::TRUNCATE, N.getValueType(), IdxN);
2402
2403 // If this is a multiply by a power of two, turn it into a shl
2404 // immediately. This is a very common case.
2405 if (ElementSize != 1) {
2406 if (isPowerOf2_64(ElementSize)) {
2407 unsigned Amt = Log2_64(ElementSize);
2408 IdxN = DAG.getNode(ISD::SHL, N.getValueType(), IdxN,
2409 DAG.getConstant(Amt, TLI.getShiftAmountTy()));
2410 } else {
2411 SDValue Scale = DAG.getIntPtrConstant(ElementSize);
2412 IdxN = DAG.getNode(ISD::MUL, N.getValueType(), IdxN, Scale);
2413 }
2414 }
2415
2416 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
2417 }
2418 }
2419 setValue(&I, N);
2420}
2421
2422void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
2423 // If this is a fixed sized alloca in the entry block of the function,
2424 // allocate it statically on the stack.
2425 if (FuncInfo.StaticAllocaMap.count(&I))
2426 return; // getValue will auto-populate this.
2427
2428 const Type *Ty = I.getAllocatedType();
2429 uint64_t TySize = TLI.getTargetData()->getABITypeSize(Ty);
2430 unsigned Align =
2431 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
2432 I.getAlignment());
2433
2434 SDValue AllocSize = getValue(I.getArraySize());
2435 MVT IntPtr = TLI.getPointerTy();
2436 if (IntPtr.bitsLT(AllocSize.getValueType()))
2437 AllocSize = DAG.getNode(ISD::TRUNCATE, IntPtr, AllocSize);
2438 else if (IntPtr.bitsGT(AllocSize.getValueType()))
2439 AllocSize = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, AllocSize);
2440
2441 AllocSize = DAG.getNode(ISD::MUL, IntPtr, AllocSize,
2442 DAG.getIntPtrConstant(TySize));
2443
2444 // Handle alignment. If the requested alignment is less than or equal to
2445 // the stack alignment, ignore it. If the size is greater than or equal to
2446 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
2447 unsigned StackAlign =
2448 TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
2449 if (Align <= StackAlign)
2450 Align = 0;
2451
2452 // Round the size of the allocation up to the stack alignment size
2453 // by add SA-1 to the size.
2454 AllocSize = DAG.getNode(ISD::ADD, AllocSize.getValueType(), AllocSize,
2455 DAG.getIntPtrConstant(StackAlign-1));
2456 // Mask out the low bits for alignment purposes.
2457 AllocSize = DAG.getNode(ISD::AND, AllocSize.getValueType(), AllocSize,
2458 DAG.getIntPtrConstant(~(uint64_t)(StackAlign-1)));
2459
2460 SDValue Ops[] = { getRoot(), AllocSize, DAG.getIntPtrConstant(Align) };
2461 const MVT *VTs = DAG.getNodeValueTypes(AllocSize.getValueType(),
2462 MVT::Other);
2463 SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, VTs, 2, Ops, 3);
2464 setValue(&I, DSA);
2465 DAG.setRoot(DSA.getValue(1));
2466
2467 // Inform the Frame Information that we have just allocated a variable-sized
2468 // object.
2469 CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
2470}
2471
2472void SelectionDAGLowering::visitLoad(LoadInst &I) {
2473 const Value *SV = I.getOperand(0);
2474 SDValue Ptr = getValue(SV);
2475
2476 const Type *Ty = I.getType();
2477 bool isVolatile = I.isVolatile();
2478 unsigned Alignment = I.getAlignment();
2479
2480 SmallVector<MVT, 4> ValueVTs;
2481 SmallVector<uint64_t, 4> Offsets;
2482 ComputeValueVTs(TLI, Ty, ValueVTs, &Offsets);
2483 unsigned NumValues = ValueVTs.size();
2484 if (NumValues == 0)
2485 return;
2486
2487 SDValue Root;
2488 bool ConstantMemory = false;
2489 if (I.isVolatile())
2490 // Serialize volatile loads with other side effects.
2491 Root = getRoot();
2492 else if (AA->pointsToConstantMemory(SV)) {
2493 // Do not serialize (non-volatile) loads of constant memory with anything.
2494 Root = DAG.getEntryNode();
2495 ConstantMemory = true;
2496 } else {
2497 // Do not serialize non-volatile loads against each other.
2498 Root = DAG.getRoot();
2499 }
2500
2501 SmallVector<SDValue, 4> Values(NumValues);
2502 SmallVector<SDValue, 4> Chains(NumValues);
2503 MVT PtrVT = Ptr.getValueType();
2504 for (unsigned i = 0; i != NumValues; ++i) {
2505 SDValue L = DAG.getLoad(ValueVTs[i], Root,
2506 DAG.getNode(ISD::ADD, PtrVT, Ptr,
2507 DAG.getConstant(Offsets[i], PtrVT)),
2508 SV, Offsets[i],
2509 isVolatile, Alignment);
2510 Values[i] = L;
2511 Chains[i] = L.getValue(1);
2512 }
2513
2514 if (!ConstantMemory) {
2515 SDValue Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
2516 &Chains[0], NumValues);
2517 if (isVolatile)
2518 DAG.setRoot(Chain);
2519 else
2520 PendingLoads.push_back(Chain);
2521 }
2522
2523 setValue(&I, DAG.getMergeValues(DAG.getVTList(&ValueVTs[0], NumValues),
2524 &Values[0], NumValues));
2525}
2526
2527
2528void SelectionDAGLowering::visitStore(StoreInst &I) {
2529 Value *SrcV = I.getOperand(0);
2530 Value *PtrV = I.getOperand(1);
2531
2532 SmallVector<MVT, 4> ValueVTs;
2533 SmallVector<uint64_t, 4> Offsets;
2534 ComputeValueVTs(TLI, SrcV->getType(), ValueVTs, &Offsets);
2535 unsigned NumValues = ValueVTs.size();
2536 if (NumValues == 0)
2537 return;
2538
2539 // Get the lowered operands. Note that we do this after
2540 // checking if NumResults is zero, because with zero results
2541 // the operands won't have values in the map.
2542 SDValue Src = getValue(SrcV);
2543 SDValue Ptr = getValue(PtrV);
2544
2545 SDValue Root = getRoot();
2546 SmallVector<SDValue, 4> Chains(NumValues);
2547 MVT PtrVT = Ptr.getValueType();
2548 bool isVolatile = I.isVolatile();
2549 unsigned Alignment = I.getAlignment();
2550 for (unsigned i = 0; i != NumValues; ++i)
2551 Chains[i] = DAG.getStore(Root, SDValue(Src.getNode(), Src.getResNo() + i),
2552 DAG.getNode(ISD::ADD, PtrVT, Ptr,
2553 DAG.getConstant(Offsets[i], PtrVT)),
2554 PtrV, Offsets[i],
2555 isVolatile, Alignment);
2556
2557 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other, &Chains[0], NumValues));
2558}
2559
2560/// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
2561/// node.
2562void SelectionDAGLowering::visitTargetIntrinsic(CallInst &I,
2563 unsigned Intrinsic) {
2564 bool HasChain = !I.doesNotAccessMemory();
2565 bool OnlyLoad = HasChain && I.onlyReadsMemory();
2566
2567 // Build the operand list.
2568 SmallVector<SDValue, 8> Ops;
2569 if (HasChain) { // If this intrinsic has side-effects, chainify it.
2570 if (OnlyLoad) {
2571 // We don't need to serialize loads against other loads.
2572 Ops.push_back(DAG.getRoot());
2573 } else {
2574 Ops.push_back(getRoot());
2575 }
2576 }
2577
2578 // Add the intrinsic ID as an integer operand.
2579 Ops.push_back(DAG.getConstant(Intrinsic, TLI.getPointerTy()));
2580
2581 // Add all operands of the call to the operand list.
2582 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
2583 SDValue Op = getValue(I.getOperand(i));
2584 assert(TLI.isTypeLegal(Op.getValueType()) &&
2585 "Intrinsic uses a non-legal type?");
2586 Ops.push_back(Op);
2587 }
2588
2589 std::vector<MVT> VTs;
2590 if (I.getType() != Type::VoidTy) {
2591 MVT VT = TLI.getValueType(I.getType());
2592 if (VT.isVector()) {
2593 const VectorType *DestTy = cast<VectorType>(I.getType());
2594 MVT EltVT = TLI.getValueType(DestTy->getElementType());
2595
2596 VT = MVT::getVectorVT(EltVT, DestTy->getNumElements());
2597 assert(VT != MVT::Other && "Intrinsic uses a non-legal type?");
2598 }
2599
2600 assert(TLI.isTypeLegal(VT) && "Intrinsic uses a non-legal type?");
2601 VTs.push_back(VT);
2602 }
2603 if (HasChain)
2604 VTs.push_back(MVT::Other);
2605
2606 const MVT *VTList = DAG.getNodeValueTypes(VTs);
2607
2608 // Create the node.
2609 SDValue Result;
2610 if (!HasChain)
2611 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VTList, VTs.size(),
2612 &Ops[0], Ops.size());
2613 else if (I.getType() != Type::VoidTy)
2614 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, VTList, VTs.size(),
2615 &Ops[0], Ops.size());
2616 else
2617 Result = DAG.getNode(ISD::INTRINSIC_VOID, VTList, VTs.size(),
2618 &Ops[0], Ops.size());
2619
2620 if (HasChain) {
2621 SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
2622 if (OnlyLoad)
2623 PendingLoads.push_back(Chain);
2624 else
2625 DAG.setRoot(Chain);
2626 }
2627 if (I.getType() != Type::VoidTy) {
2628 if (const VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
2629 MVT VT = TLI.getValueType(PTy);
2630 Result = DAG.getNode(ISD::BIT_CONVERT, VT, Result);
2631 }
2632 setValue(&I, Result);
2633 }
2634}
2635
2636/// ExtractTypeInfo - Returns the type info, possibly bitcast, encoded in V.
2637static GlobalVariable *ExtractTypeInfo(Value *V) {
2638 V = V->stripPointerCasts();
2639 GlobalVariable *GV = dyn_cast<GlobalVariable>(V);
2640 assert ((GV || isa<ConstantPointerNull>(V)) &&
2641 "TypeInfo must be a global variable or NULL");
2642 return GV;
2643}
2644
2645namespace llvm {
2646
2647/// AddCatchInfo - Extract the personality and type infos from an eh.selector
2648/// call, and add them to the specified machine basic block.
2649void AddCatchInfo(CallInst &I, MachineModuleInfo *MMI,
2650 MachineBasicBlock *MBB) {
2651 // Inform the MachineModuleInfo of the personality for this landing pad.
2652 ConstantExpr *CE = cast<ConstantExpr>(I.getOperand(2));
2653 assert(CE->getOpcode() == Instruction::BitCast &&
2654 isa<Function>(CE->getOperand(0)) &&
2655 "Personality should be a function");
2656 MMI->addPersonality(MBB, cast<Function>(CE->getOperand(0)));
2657
2658 // Gather all the type infos for this landing pad and pass them along to
2659 // MachineModuleInfo.
2660 std::vector<GlobalVariable *> TyInfo;
2661 unsigned N = I.getNumOperands();
2662
2663 for (unsigned i = N - 1; i > 2; --i) {
2664 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(i))) {
2665 unsigned FilterLength = CI->getZExtValue();
2666 unsigned FirstCatch = i + FilterLength + !FilterLength;
2667 assert (FirstCatch <= N && "Invalid filter length");
2668
2669 if (FirstCatch < N) {
2670 TyInfo.reserve(N - FirstCatch);
2671 for (unsigned j = FirstCatch; j < N; ++j)
2672 TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
2673 MMI->addCatchTypeInfo(MBB, TyInfo);
2674 TyInfo.clear();
2675 }
2676
2677 if (!FilterLength) {
2678 // Cleanup.
2679 MMI->addCleanup(MBB);
2680 } else {
2681 // Filter.
2682 TyInfo.reserve(FilterLength - 1);
2683 for (unsigned j = i + 1; j < FirstCatch; ++j)
2684 TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
2685 MMI->addFilterTypeInfo(MBB, TyInfo);
2686 TyInfo.clear();
2687 }
2688
2689 N = i;
2690 }
2691 }
2692
2693 if (N > 3) {
2694 TyInfo.reserve(N - 3);
2695 for (unsigned j = 3; j < N; ++j)
2696 TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
2697 MMI->addCatchTypeInfo(MBB, TyInfo);
2698 }
2699}
2700
2701}
2702
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00002703/// GetSignificand - Get the significand and build it into a floating-point
2704/// number with exponent of 1:
2705///
2706/// Op = (Op & 0x007fffff) | 0x3f800000;
2707///
2708/// where Op is the hexidecimal representation of floating point value.
Bill Wendling39150252008-09-09 20:39:27 +00002709static SDValue
2710GetSignificand(SelectionDAG &DAG, SDValue Op) {
2711 SDValue t1 = DAG.getNode(ISD::AND, MVT::i32, Op,
2712 DAG.getConstant(0x007fffff, MVT::i32));
2713 SDValue t2 = DAG.getNode(ISD::OR, MVT::i32, t1,
2714 DAG.getConstant(0x3f800000, MVT::i32));
2715 return DAG.getNode(ISD::BIT_CONVERT, MVT::f32, t2);
2716}
2717
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00002718/// GetExponent - Get the exponent:
2719///
2720/// (float)((Op1 >> 23) - 127);
2721///
2722/// where Op is the hexidecimal representation of floating point value.
Bill Wendling39150252008-09-09 20:39:27 +00002723static SDValue
2724GetExponent(SelectionDAG &DAG, SDValue Op) {
Bill Wendlingfc2508e2008-09-10 06:26:10 +00002725 SDValue t1 = DAG.getNode(ISD::SRL, MVT::i32, Op,
Bill Wendling39150252008-09-09 20:39:27 +00002726 DAG.getConstant(23, MVT::i32));
Bill Wendlingfc2508e2008-09-10 06:26:10 +00002727 SDValue t2 = DAG.getNode(ISD::SUB, MVT::i32, t1,
Bill Wendling39150252008-09-09 20:39:27 +00002728 DAG.getConstant(127, MVT::i32));
Bill Wendlingfc2508e2008-09-10 06:26:10 +00002729 return DAG.getNode(ISD::UINT_TO_FP, MVT::f32, t2);
Bill Wendling39150252008-09-09 20:39:27 +00002730}
2731
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00002732/// getF32Constant - Get 32-bit floating point constant.
2733static SDValue
2734getF32Constant(SelectionDAG &DAG, unsigned Flt) {
2735 return DAG.getConstantFP(APFloat(APInt(32, Flt)), MVT::f32);
2736}
2737
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002738/// Inlined utility function to implement binary input atomic intrinsics for
2739/// visitIntrinsicCall: I is a call instruction
2740/// Op is the associated NodeType for I
2741const char *
2742SelectionDAGLowering::implVisitBinaryAtomic(CallInst& I, ISD::NodeType Op) {
2743 SDValue Root = getRoot();
2744 SDValue L = DAG.getAtomic(Op, Root,
2745 getValue(I.getOperand(1)),
2746 getValue(I.getOperand(2)),
2747 I.getOperand(1));
2748 setValue(&I, L);
2749 DAG.setRoot(L.getValue(1));
2750 return 0;
2751}
2752
Bill Wendlingb4ec2832008-09-09 22:13:54 +00002753/// visitExp - Lower an exp intrinsic. Handles the special sequences for
2754/// limited-precision mode.
Dale Johannesen59e577f2008-09-05 18:38:42 +00002755void
2756SelectionDAGLowering::visitExp(CallInst &I) {
2757 SDValue result;
Bill Wendlingb4ec2832008-09-09 22:13:54 +00002758
2759 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
2760 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
2761 SDValue Op = getValue(I.getOperand(1));
2762
2763 // Put the exponent in the right bit position for later addition to the
2764 // final result:
2765 //
2766 // #define LOG2OFe 1.4426950f
2767 // IntegerPartOfX = ((int32_t)(X * LOG2OFe));
2768 SDValue t0 = DAG.getNode(ISD::FMUL, MVT::f32, Op,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00002769 getF32Constant(DAG, 0x3fb8aa3b));
Bill Wendlingb4ec2832008-09-09 22:13:54 +00002770 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, MVT::i32, t0);
2771
2772 // FractionalPartOfX = (X * LOG2OFe) - (float)IntegerPartOfX;
2773 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, MVT::f32, IntegerPartOfX);
2774 SDValue X = DAG.getNode(ISD::FSUB, MVT::f32, t0, t1);
2775
2776 // IntegerPartOfX <<= 23;
2777 IntegerPartOfX = DAG.getNode(ISD::SHL, MVT::i32, IntegerPartOfX,
2778 DAG.getConstant(23, MVT::i32));
2779
2780 if (LimitFloatPrecision <= 6) {
2781 // For floating-point precision of 6:
2782 //
2783 // TwoToFractionalPartOfX =
2784 // 0.997535578f +
2785 // (0.735607626f + 0.252464424f * x) * x;
2786 //
2787 // error 0.0144103317, which is 6 bits
2788 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00002789 getF32Constant(DAG, 0x3e814304));
Bill Wendlingb4ec2832008-09-09 22:13:54 +00002790 SDValue t3 = DAG.getNode(ISD::FADD, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00002791 getF32Constant(DAG, 0x3f3c50c8));
Bill Wendlingb4ec2832008-09-09 22:13:54 +00002792 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
2793 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00002794 getF32Constant(DAG, 0x3f7f5e7e));
Bill Wendlingb4ec2832008-09-09 22:13:54 +00002795 SDValue TwoToFracPartOfX = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, t5);
2796
2797 // Add the exponent into the result in integer domain.
2798 SDValue t6 = DAG.getNode(ISD::ADD, MVT::i32,
2799 TwoToFracPartOfX, IntegerPartOfX);
2800
2801 result = DAG.getNode(ISD::BIT_CONVERT, MVT::f32, t6);
2802 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
2803 // For floating-point precision of 12:
2804 //
2805 // TwoToFractionalPartOfX =
2806 // 0.999892986f +
2807 // (0.696457318f +
2808 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
2809 //
2810 // 0.000107046256 error, which is 13 to 14 bits
2811 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00002812 getF32Constant(DAG, 0x3da235e3));
Bill Wendlingb4ec2832008-09-09 22:13:54 +00002813 SDValue t3 = DAG.getNode(ISD::FADD, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00002814 getF32Constant(DAG, 0x3e65b8f3));
Bill Wendlingb4ec2832008-09-09 22:13:54 +00002815 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
2816 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00002817 getF32Constant(DAG, 0x3f324b07));
Bill Wendlingb4ec2832008-09-09 22:13:54 +00002818 SDValue t6 = DAG.getNode(ISD::FMUL, MVT::f32, t5, X);
2819 SDValue t7 = DAG.getNode(ISD::FADD, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00002820 getF32Constant(DAG, 0x3f7ff8fd));
Bill Wendlingb4ec2832008-09-09 22:13:54 +00002821 SDValue TwoToFracPartOfX = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, t7);
2822
2823 // Add the exponent into the result in integer domain.
2824 SDValue t8 = DAG.getNode(ISD::ADD, MVT::i32,
2825 TwoToFracPartOfX, IntegerPartOfX);
2826
2827 result = DAG.getNode(ISD::BIT_CONVERT, MVT::f32, t8);
2828 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
2829 // For floating-point precision of 18:
2830 //
2831 // TwoToFractionalPartOfX =
2832 // 0.999999982f +
2833 // (0.693148872f +
2834 // (0.240227044f +
2835 // (0.554906021e-1f +
2836 // (0.961591928e-2f +
2837 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
2838 //
2839 // error 2.47208000*10^(-7), which is better than 18 bits
2840 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00002841 getF32Constant(DAG, 0x3924b03e));
Bill Wendlingb4ec2832008-09-09 22:13:54 +00002842 SDValue t3 = DAG.getNode(ISD::FADD, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00002843 getF32Constant(DAG, 0x3ab24b87));
Bill Wendlingb4ec2832008-09-09 22:13:54 +00002844 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
2845 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00002846 getF32Constant(DAG, 0x3c1d8c17));
Bill Wendlingb4ec2832008-09-09 22:13:54 +00002847 SDValue t6 = DAG.getNode(ISD::FMUL, MVT::f32, t5, X);
2848 SDValue t7 = DAG.getNode(ISD::FADD, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00002849 getF32Constant(DAG, 0x3d634a1d));
Bill Wendlingb4ec2832008-09-09 22:13:54 +00002850 SDValue t8 = DAG.getNode(ISD::FMUL, MVT::f32, t7, X);
2851 SDValue t9 = DAG.getNode(ISD::FADD, MVT::f32, t8,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00002852 getF32Constant(DAG, 0x3e75fe14));
Bill Wendlingb4ec2832008-09-09 22:13:54 +00002853 SDValue t10 = DAG.getNode(ISD::FMUL, MVT::f32, t9, X);
2854 SDValue t11 = DAG.getNode(ISD::FADD, MVT::f32, t10,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00002855 getF32Constant(DAG, 0x3f317234));
Bill Wendlingb4ec2832008-09-09 22:13:54 +00002856 SDValue t12 = DAG.getNode(ISD::FMUL, MVT::f32, t11, X);
2857 SDValue t13 = DAG.getNode(ISD::FADD, MVT::f32, t12,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00002858 getF32Constant(DAG, 0x3f800000));
Bill Wendlingb4ec2832008-09-09 22:13:54 +00002859 SDValue TwoToFracPartOfX = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, t13);
2860
2861 // Add the exponent into the result in integer domain.
2862 SDValue t14 = DAG.getNode(ISD::ADD, MVT::i32,
2863 TwoToFracPartOfX, IntegerPartOfX);
2864
2865 result = DAG.getNode(ISD::BIT_CONVERT, MVT::f32, t14);
2866 }
2867 } else {
2868 // No special expansion.
2869 result = DAG.getNode(ISD::FEXP,
2870 getValue(I.getOperand(1)).getValueType(),
2871 getValue(I.getOperand(1)));
2872 }
2873
Dale Johannesen59e577f2008-09-05 18:38:42 +00002874 setValue(&I, result);
2875}
2876
Bill Wendling39150252008-09-09 20:39:27 +00002877/// visitLog - Lower a log intrinsic. Handles the special sequences for
2878/// limited-precision mode.
Dale Johannesen59e577f2008-09-05 18:38:42 +00002879void
2880SelectionDAGLowering::visitLog(CallInst &I) {
2881 SDValue result;
Bill Wendling39150252008-09-09 20:39:27 +00002882
2883 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
2884 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
2885 SDValue Op = getValue(I.getOperand(1));
2886 SDValue Op1 = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, Op);
2887
2888 // Scale the exponent by log(2) [0.69314718f].
2889 SDValue Exp = GetExponent(DAG, Op1);
2890 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, MVT::f32, Exp,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00002891 getF32Constant(DAG, 0x3f317218));
Bill Wendling39150252008-09-09 20:39:27 +00002892
2893 // Get the significand and build it into a floating-point number with
2894 // exponent of 1.
2895 SDValue X = GetSignificand(DAG, Op1);
2896
2897 if (LimitFloatPrecision <= 6) {
2898 // For floating-point precision of 6:
2899 //
2900 // LogofMantissa =
2901 // -1.1609546f +
2902 // (1.4034025f - 0.23903021f * x) * x;
2903 //
2904 // error 0.0034276066, which is better than 8 bits
2905 SDValue t0 = DAG.getNode(ISD::FMUL, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00002906 getF32Constant(DAG, 0xbe74c456));
Bill Wendling39150252008-09-09 20:39:27 +00002907 SDValue t1 = DAG.getNode(ISD::FADD, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00002908 getF32Constant(DAG, 0x3fb3a2b1));
Bill Wendling39150252008-09-09 20:39:27 +00002909 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, t1, X);
2910 SDValue LogOfMantissa = DAG.getNode(ISD::FSUB, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00002911 getF32Constant(DAG, 0x3f949a29));
Bill Wendling39150252008-09-09 20:39:27 +00002912
2913 result = DAG.getNode(ISD::FADD, MVT::f32, LogOfExponent, LogOfMantissa);
2914 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
2915 // For floating-point precision of 12:
2916 //
2917 // LogOfMantissa =
2918 // -1.7417939f +
2919 // (2.8212026f +
2920 // (-1.4699568f +
2921 // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
2922 //
2923 // error 0.000061011436, which is 14 bits
2924 SDValue t0 = DAG.getNode(ISD::FMUL, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00002925 getF32Constant(DAG, 0xbd67b6d6));
Bill Wendling39150252008-09-09 20:39:27 +00002926 SDValue t1 = DAG.getNode(ISD::FADD, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00002927 getF32Constant(DAG, 0x3ee4f4b8));
Bill Wendling39150252008-09-09 20:39:27 +00002928 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, t1, X);
2929 SDValue t3 = DAG.getNode(ISD::FSUB, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00002930 getF32Constant(DAG, 0x3fbc278b));
Bill Wendling39150252008-09-09 20:39:27 +00002931 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
2932 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00002933 getF32Constant(DAG, 0x40348e95));
Bill Wendling39150252008-09-09 20:39:27 +00002934 SDValue t6 = DAG.getNode(ISD::FMUL, MVT::f32, t5, X);
2935 SDValue LogOfMantissa = DAG.getNode(ISD::FSUB, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00002936 getF32Constant(DAG, 0x3fdef31a));
Bill Wendling39150252008-09-09 20:39:27 +00002937
2938 result = DAG.getNode(ISD::FADD, MVT::f32, LogOfExponent, LogOfMantissa);
2939 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
2940 // For floating-point precision of 18:
2941 //
2942 // LogOfMantissa =
2943 // -2.1072184f +
2944 // (4.2372794f +
2945 // (-3.7029485f +
2946 // (2.2781945f +
2947 // (-0.87823314f +
2948 // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
2949 //
2950 // error 0.0000023660568, which is better than 18 bits
2951 SDValue t0 = DAG.getNode(ISD::FMUL, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00002952 getF32Constant(DAG, 0xbc91e5ac));
Bill Wendling39150252008-09-09 20:39:27 +00002953 SDValue t1 = DAG.getNode(ISD::FADD, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00002954 getF32Constant(DAG, 0x3e4350aa));
Bill Wendling39150252008-09-09 20:39:27 +00002955 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, t1, X);
2956 SDValue t3 = DAG.getNode(ISD::FSUB, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00002957 getF32Constant(DAG, 0x3f60d3e3));
Bill Wendling39150252008-09-09 20:39:27 +00002958 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
2959 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00002960 getF32Constant(DAG, 0x4011cdf0));
Bill Wendling39150252008-09-09 20:39:27 +00002961 SDValue t6 = DAG.getNode(ISD::FMUL, MVT::f32, t5, X);
2962 SDValue t7 = DAG.getNode(ISD::FSUB, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00002963 getF32Constant(DAG, 0x406cfd1c));
Bill Wendling39150252008-09-09 20:39:27 +00002964 SDValue t8 = DAG.getNode(ISD::FMUL, MVT::f32, t7, X);
2965 SDValue t9 = DAG.getNode(ISD::FADD, MVT::f32, t8,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00002966 getF32Constant(DAG, 0x408797cb));
Bill Wendling39150252008-09-09 20:39:27 +00002967 SDValue t10 = DAG.getNode(ISD::FMUL, MVT::f32, t9, X);
2968 SDValue LogOfMantissa = DAG.getNode(ISD::FSUB, MVT::f32, t10,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00002969 getF32Constant(DAG, 0x4006dcab));
Bill Wendling39150252008-09-09 20:39:27 +00002970
2971 result = DAG.getNode(ISD::FADD, MVT::f32, LogOfExponent, LogOfMantissa);
2972 }
2973 } else {
2974 // No special expansion.
2975 result = DAG.getNode(ISD::FLOG,
2976 getValue(I.getOperand(1)).getValueType(),
2977 getValue(I.getOperand(1)));
2978 }
2979
Dale Johannesen59e577f2008-09-05 18:38:42 +00002980 setValue(&I, result);
2981}
2982
Bill Wendling3eb59402008-09-09 00:28:24 +00002983/// visitLog2 - Lower a log2 intrinsic. Handles the special sequences for
2984/// limited-precision mode.
Dale Johannesen59e577f2008-09-05 18:38:42 +00002985void
2986SelectionDAGLowering::visitLog2(CallInst &I) {
2987 SDValue result;
Bill Wendling3eb59402008-09-09 00:28:24 +00002988
Dale Johannesen853244f2008-09-05 23:49:37 +00002989 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
Bill Wendling3eb59402008-09-09 00:28:24 +00002990 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
2991 SDValue Op = getValue(I.getOperand(1));
2992 SDValue Op1 = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, Op);
2993
Bill Wendling39150252008-09-09 20:39:27 +00002994 // Get the exponent.
2995 SDValue LogOfExponent = GetExponent(DAG, Op1);
Bill Wendling3eb59402008-09-09 00:28:24 +00002996
2997 // Get the significand and build it into a floating-point number with
Bill Wendling39150252008-09-09 20:39:27 +00002998 // exponent of 1.
2999 SDValue X = GetSignificand(DAG, Op1);
Bill Wendling3eb59402008-09-09 00:28:24 +00003000
3001 // Different possible minimax approximations of significand in
3002 // floating-point for various degrees of accuracy over [1,2].
3003 if (LimitFloatPrecision <= 6) {
3004 // For floating-point precision of 6:
3005 //
3006 // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
3007 //
3008 // error 0.0049451742, which is more than 7 bits
Bill Wendling39150252008-09-09 20:39:27 +00003009 SDValue t0 = DAG.getNode(ISD::FMUL, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003010 getF32Constant(DAG, 0xbeb08fe0));
Bill Wendling39150252008-09-09 20:39:27 +00003011 SDValue t1 = DAG.getNode(ISD::FADD, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003012 getF32Constant(DAG, 0x40019463));
Bill Wendling39150252008-09-09 20:39:27 +00003013 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, t1, X);
3014 SDValue Log2ofMantissa = DAG.getNode(ISD::FSUB, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003015 getF32Constant(DAG, 0x3fd6633d));
Bill Wendling3eb59402008-09-09 00:28:24 +00003016
3017 result = DAG.getNode(ISD::FADD, MVT::f32, LogOfExponent, Log2ofMantissa);
3018 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3019 // For floating-point precision of 12:
3020 //
3021 // Log2ofMantissa =
3022 // -2.51285454f +
3023 // (4.07009056f +
3024 // (-2.12067489f +
3025 // (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
3026 //
3027 // error 0.0000876136000, which is better than 13 bits
Bill Wendling39150252008-09-09 20:39:27 +00003028 SDValue t0 = DAG.getNode(ISD::FMUL, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003029 getF32Constant(DAG, 0xbda7262e));
Bill Wendling39150252008-09-09 20:39:27 +00003030 SDValue t1 = DAG.getNode(ISD::FADD, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003031 getF32Constant(DAG, 0x3f25280b));
Bill Wendling39150252008-09-09 20:39:27 +00003032 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, t1, X);
3033 SDValue t3 = DAG.getNode(ISD::FSUB, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003034 getF32Constant(DAG, 0x4007b923));
Bill Wendling39150252008-09-09 20:39:27 +00003035 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3036 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003037 getF32Constant(DAG, 0x40823e2f));
Bill Wendling39150252008-09-09 20:39:27 +00003038 SDValue t6 = DAG.getNode(ISD::FMUL, MVT::f32, t5, X);
3039 SDValue Log2ofMantissa = DAG.getNode(ISD::FSUB, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003040 getF32Constant(DAG, 0x4020d29c));
Bill Wendling3eb59402008-09-09 00:28:24 +00003041
3042 result = DAG.getNode(ISD::FADD, MVT::f32, LogOfExponent, Log2ofMantissa);
3043 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3044 // For floating-point precision of 18:
3045 //
3046 // Log2ofMantissa =
3047 // -3.0400495f +
3048 // (6.1129976f +
3049 // (-5.3420409f +
3050 // (3.2865683f +
3051 // (-1.2669343f +
3052 // (0.27515199f -
3053 // 0.25691327e-1f * x) * x) * x) * x) * x) * x;
3054 //
3055 // error 0.0000018516, which is better than 18 bits
Bill Wendling39150252008-09-09 20:39:27 +00003056 SDValue t0 = DAG.getNode(ISD::FMUL, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003057 getF32Constant(DAG, 0xbcd2769e));
Bill Wendling39150252008-09-09 20:39:27 +00003058 SDValue t1 = DAG.getNode(ISD::FADD, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003059 getF32Constant(DAG, 0x3e8ce0b9));
Bill Wendling39150252008-09-09 20:39:27 +00003060 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, t1, X);
3061 SDValue t3 = DAG.getNode(ISD::FSUB, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003062 getF32Constant(DAG, 0x3fa22ae7));
Bill Wendling39150252008-09-09 20:39:27 +00003063 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3064 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003065 getF32Constant(DAG, 0x40525723));
Bill Wendling39150252008-09-09 20:39:27 +00003066 SDValue t6 = DAG.getNode(ISD::FMUL, MVT::f32, t5, X);
3067 SDValue t7 = DAG.getNode(ISD::FSUB, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003068 getF32Constant(DAG, 0x40aaf200));
Bill Wendling39150252008-09-09 20:39:27 +00003069 SDValue t8 = DAG.getNode(ISD::FMUL, MVT::f32, t7, X);
3070 SDValue t9 = DAG.getNode(ISD::FADD, MVT::f32, t8,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003071 getF32Constant(DAG, 0x40c39dad));
Bill Wendling3eb59402008-09-09 00:28:24 +00003072 SDValue t10 = DAG.getNode(ISD::FMUL, MVT::f32, t9, X);
Bill Wendling39150252008-09-09 20:39:27 +00003073 SDValue Log2ofMantissa = DAG.getNode(ISD::FSUB, MVT::f32, t10,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003074 getF32Constant(DAG, 0x4042902c));
Bill Wendling3eb59402008-09-09 00:28:24 +00003075
3076 result = DAG.getNode(ISD::FADD, MVT::f32, LogOfExponent, Log2ofMantissa);
3077 }
Dale Johannesen853244f2008-09-05 23:49:37 +00003078 } else {
Bill Wendling3eb59402008-09-09 00:28:24 +00003079 // No special expansion.
Dale Johannesen853244f2008-09-05 23:49:37 +00003080 result = DAG.getNode(ISD::FLOG2,
3081 getValue(I.getOperand(1)).getValueType(),
3082 getValue(I.getOperand(1)));
3083 }
Bill Wendling3eb59402008-09-09 00:28:24 +00003084
Dale Johannesen59e577f2008-09-05 18:38:42 +00003085 setValue(&I, result);
3086}
3087
Bill Wendling3eb59402008-09-09 00:28:24 +00003088/// visitLog10 - Lower a log10 intrinsic. Handles the special sequences for
3089/// limited-precision mode.
Dale Johannesen59e577f2008-09-05 18:38:42 +00003090void
3091SelectionDAGLowering::visitLog10(CallInst &I) {
3092 SDValue result;
Bill Wendling181b6272008-10-19 20:34:04 +00003093
Dale Johannesen852680a2008-09-05 21:27:19 +00003094 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
Bill Wendling3eb59402008-09-09 00:28:24 +00003095 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3096 SDValue Op = getValue(I.getOperand(1));
3097 SDValue Op1 = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, Op);
3098
Bill Wendling39150252008-09-09 20:39:27 +00003099 // Scale the exponent by log10(2) [0.30102999f].
3100 SDValue Exp = GetExponent(DAG, Op1);
3101 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, MVT::f32, Exp,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003102 getF32Constant(DAG, 0x3e9a209a));
Bill Wendling3eb59402008-09-09 00:28:24 +00003103
3104 // Get the significand and build it into a floating-point number with
Bill Wendling39150252008-09-09 20:39:27 +00003105 // exponent of 1.
3106 SDValue X = GetSignificand(DAG, Op1);
Bill Wendling3eb59402008-09-09 00:28:24 +00003107
3108 if (LimitFloatPrecision <= 6) {
Bill Wendlingbd297bc2008-09-09 18:42:23 +00003109 // For floating-point precision of 6:
3110 //
3111 // Log10ofMantissa =
3112 // -0.50419619f +
3113 // (0.60948995f - 0.10380950f * x) * x;
3114 //
3115 // error 0.0014886165, which is 6 bits
Bill Wendling39150252008-09-09 20:39:27 +00003116 SDValue t0 = DAG.getNode(ISD::FMUL, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003117 getF32Constant(DAG, 0xbdd49a13));
Bill Wendling39150252008-09-09 20:39:27 +00003118 SDValue t1 = DAG.getNode(ISD::FADD, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003119 getF32Constant(DAG, 0x3f1c0789));
Bill Wendling39150252008-09-09 20:39:27 +00003120 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, t1, X);
3121 SDValue Log10ofMantissa = DAG.getNode(ISD::FSUB, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003122 getF32Constant(DAG, 0x3f011300));
Bill Wendlingbd297bc2008-09-09 18:42:23 +00003123
3124 result = DAG.getNode(ISD::FADD, MVT::f32, LogOfExponent, Log10ofMantissa);
Bill Wendling3eb59402008-09-09 00:28:24 +00003125 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3126 // For floating-point precision of 12:
3127 //
3128 // Log10ofMantissa =
3129 // -0.64831180f +
3130 // (0.91751397f +
3131 // (-0.31664806f + 0.47637168e-1f * x) * x) * x;
3132 //
3133 // error 0.00019228036, which is better than 12 bits
Bill Wendling39150252008-09-09 20:39:27 +00003134 SDValue t0 = DAG.getNode(ISD::FMUL, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003135 getF32Constant(DAG, 0x3d431f31));
Bill Wendling39150252008-09-09 20:39:27 +00003136 SDValue t1 = DAG.getNode(ISD::FSUB, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003137 getF32Constant(DAG, 0x3ea21fb2));
Bill Wendling39150252008-09-09 20:39:27 +00003138 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, t1, X);
3139 SDValue t3 = DAG.getNode(ISD::FADD, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003140 getF32Constant(DAG, 0x3f6ae232));
Bill Wendling39150252008-09-09 20:39:27 +00003141 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3142 SDValue Log10ofMantissa = DAG.getNode(ISD::FSUB, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003143 getF32Constant(DAG, 0x3f25f7c3));
Bill Wendling3eb59402008-09-09 00:28:24 +00003144
3145 result = DAG.getNode(ISD::FADD, MVT::f32, LogOfExponent, Log10ofMantissa);
3146 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
Bill Wendlingbd297bc2008-09-09 18:42:23 +00003147 // For floating-point precision of 18:
3148 //
3149 // Log10ofMantissa =
3150 // -0.84299375f +
3151 // (1.5327582f +
3152 // (-1.0688956f +
3153 // (0.49102474f +
3154 // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
3155 //
3156 // error 0.0000037995730, which is better than 18 bits
Bill Wendling39150252008-09-09 20:39:27 +00003157 SDValue t0 = DAG.getNode(ISD::FMUL, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003158 getF32Constant(DAG, 0x3c5d51ce));
Bill Wendling39150252008-09-09 20:39:27 +00003159 SDValue t1 = DAG.getNode(ISD::FSUB, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003160 getF32Constant(DAG, 0x3e00685a));
Bill Wendling39150252008-09-09 20:39:27 +00003161 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, t1, X);
3162 SDValue t3 = DAG.getNode(ISD::FADD, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003163 getF32Constant(DAG, 0x3efb6798));
Bill Wendling39150252008-09-09 20:39:27 +00003164 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3165 SDValue t5 = DAG.getNode(ISD::FSUB, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003166 getF32Constant(DAG, 0x3f88d192));
Bill Wendling39150252008-09-09 20:39:27 +00003167 SDValue t6 = DAG.getNode(ISD::FMUL, MVT::f32, t5, X);
3168 SDValue t7 = DAG.getNode(ISD::FADD, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003169 getF32Constant(DAG, 0x3fc4316c));
Bill Wendlingbd297bc2008-09-09 18:42:23 +00003170 SDValue t8 = DAG.getNode(ISD::FMUL, MVT::f32, t7, X);
Bill Wendling39150252008-09-09 20:39:27 +00003171 SDValue Log10ofMantissa = DAG.getNode(ISD::FSUB, MVT::f32, t8,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003172 getF32Constant(DAG, 0x3f57ce70));
Bill Wendlingbd297bc2008-09-09 18:42:23 +00003173
3174 result = DAG.getNode(ISD::FADD, MVT::f32, LogOfExponent, Log10ofMantissa);
Bill Wendling3eb59402008-09-09 00:28:24 +00003175 }
Dale Johannesen852680a2008-09-05 21:27:19 +00003176 } else {
Bill Wendling3eb59402008-09-09 00:28:24 +00003177 // No special expansion.
Dale Johannesen852680a2008-09-05 21:27:19 +00003178 result = DAG.getNode(ISD::FLOG10,
3179 getValue(I.getOperand(1)).getValueType(),
3180 getValue(I.getOperand(1)));
3181 }
Bill Wendling3eb59402008-09-09 00:28:24 +00003182
Dale Johannesen59e577f2008-09-05 18:38:42 +00003183 setValue(&I, result);
3184}
3185
Bill Wendlinge10c8142008-09-09 22:39:21 +00003186/// visitExp2 - Lower an exp2 intrinsic. Handles the special sequences for
3187/// limited-precision mode.
Dale Johannesen601d3c02008-09-05 01:48:15 +00003188void
3189SelectionDAGLowering::visitExp2(CallInst &I) {
3190 SDValue result;
Bill Wendlinge10c8142008-09-09 22:39:21 +00003191
Dale Johannesen601d3c02008-09-05 01:48:15 +00003192 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
Bill Wendlinge10c8142008-09-09 22:39:21 +00003193 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3194 SDValue Op = getValue(I.getOperand(1));
3195
3196 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, MVT::i32, Op);
3197
3198 // FractionalPartOfX = x - (float)IntegerPartOfX;
3199 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, MVT::f32, IntegerPartOfX);
3200 SDValue X = DAG.getNode(ISD::FSUB, MVT::f32, Op, t1);
3201
3202 // IntegerPartOfX <<= 23;
3203 IntegerPartOfX = DAG.getNode(ISD::SHL, MVT::i32, IntegerPartOfX,
3204 DAG.getConstant(23, MVT::i32));
3205
3206 if (LimitFloatPrecision <= 6) {
3207 // For floating-point precision of 6:
3208 //
3209 // TwoToFractionalPartOfX =
3210 // 0.997535578f +
3211 // (0.735607626f + 0.252464424f * x) * x;
3212 //
3213 // error 0.0144103317, which is 6 bits
3214 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003215 getF32Constant(DAG, 0x3e814304));
Bill Wendlinge10c8142008-09-09 22:39:21 +00003216 SDValue t3 = DAG.getNode(ISD::FADD, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003217 getF32Constant(DAG, 0x3f3c50c8));
Bill Wendlinge10c8142008-09-09 22:39:21 +00003218 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3219 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003220 getF32Constant(DAG, 0x3f7f5e7e));
Bill Wendlinge10c8142008-09-09 22:39:21 +00003221 SDValue t6 = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, t5);
3222 SDValue TwoToFractionalPartOfX =
3223 DAG.getNode(ISD::ADD, MVT::i32, t6, IntegerPartOfX);
3224
3225 result = DAG.getNode(ISD::BIT_CONVERT, MVT::f32, TwoToFractionalPartOfX);
3226 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3227 // For floating-point precision of 12:
3228 //
3229 // TwoToFractionalPartOfX =
3230 // 0.999892986f +
3231 // (0.696457318f +
3232 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
3233 //
3234 // error 0.000107046256, which is 13 to 14 bits
3235 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003236 getF32Constant(DAG, 0x3da235e3));
Bill Wendlinge10c8142008-09-09 22:39:21 +00003237 SDValue t3 = DAG.getNode(ISD::FADD, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003238 getF32Constant(DAG, 0x3e65b8f3));
Bill Wendlinge10c8142008-09-09 22:39:21 +00003239 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3240 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003241 getF32Constant(DAG, 0x3f324b07));
Bill Wendlinge10c8142008-09-09 22:39:21 +00003242 SDValue t6 = DAG.getNode(ISD::FMUL, MVT::f32, t5, X);
3243 SDValue t7 = DAG.getNode(ISD::FADD, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003244 getF32Constant(DAG, 0x3f7ff8fd));
Bill Wendlinge10c8142008-09-09 22:39:21 +00003245 SDValue t8 = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, t7);
3246 SDValue TwoToFractionalPartOfX =
3247 DAG.getNode(ISD::ADD, MVT::i32, t8, IntegerPartOfX);
3248
3249 result = DAG.getNode(ISD::BIT_CONVERT, MVT::f32, TwoToFractionalPartOfX);
3250 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3251 // For floating-point precision of 18:
3252 //
3253 // TwoToFractionalPartOfX =
3254 // 0.999999982f +
3255 // (0.693148872f +
3256 // (0.240227044f +
3257 // (0.554906021e-1f +
3258 // (0.961591928e-2f +
3259 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
3260 // error 2.47208000*10^(-7), which is better than 18 bits
3261 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003262 getF32Constant(DAG, 0x3924b03e));
Bill Wendlinge10c8142008-09-09 22:39:21 +00003263 SDValue t3 = DAG.getNode(ISD::FADD, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003264 getF32Constant(DAG, 0x3ab24b87));
Bill Wendlinge10c8142008-09-09 22:39:21 +00003265 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3266 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003267 getF32Constant(DAG, 0x3c1d8c17));
Bill Wendlinge10c8142008-09-09 22:39:21 +00003268 SDValue t6 = DAG.getNode(ISD::FMUL, MVT::f32, t5, X);
3269 SDValue t7 = DAG.getNode(ISD::FADD, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003270 getF32Constant(DAG, 0x3d634a1d));
Bill Wendlinge10c8142008-09-09 22:39:21 +00003271 SDValue t8 = DAG.getNode(ISD::FMUL, MVT::f32, t7, X);
3272 SDValue t9 = DAG.getNode(ISD::FADD, MVT::f32, t8,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003273 getF32Constant(DAG, 0x3e75fe14));
Bill Wendlinge10c8142008-09-09 22:39:21 +00003274 SDValue t10 = DAG.getNode(ISD::FMUL, MVT::f32, t9, X);
3275 SDValue t11 = DAG.getNode(ISD::FADD, MVT::f32, t10,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003276 getF32Constant(DAG, 0x3f317234));
Bill Wendlinge10c8142008-09-09 22:39:21 +00003277 SDValue t12 = DAG.getNode(ISD::FMUL, MVT::f32, t11, X);
3278 SDValue t13 = DAG.getNode(ISD::FADD, MVT::f32, t12,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003279 getF32Constant(DAG, 0x3f800000));
Bill Wendlinge10c8142008-09-09 22:39:21 +00003280 SDValue t14 = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, t13);
3281 SDValue TwoToFractionalPartOfX =
3282 DAG.getNode(ISD::ADD, MVT::i32, t14, IntegerPartOfX);
3283
3284 result = DAG.getNode(ISD::BIT_CONVERT, MVT::f32, TwoToFractionalPartOfX);
3285 }
Dale Johannesen601d3c02008-09-05 01:48:15 +00003286 } else {
Bill Wendling3eb59402008-09-09 00:28:24 +00003287 // No special expansion.
Dale Johannesen601d3c02008-09-05 01:48:15 +00003288 result = DAG.getNode(ISD::FEXP2,
3289 getValue(I.getOperand(1)).getValueType(),
3290 getValue(I.getOperand(1)));
3291 }
Bill Wendlinge10c8142008-09-09 22:39:21 +00003292
Dale Johannesen601d3c02008-09-05 01:48:15 +00003293 setValue(&I, result);
3294}
3295
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003296/// visitPow - Lower a pow intrinsic. Handles the special sequences for
3297/// limited-precision mode with x == 10.0f.
3298void
3299SelectionDAGLowering::visitPow(CallInst &I) {
3300 SDValue result;
3301 Value *Val = I.getOperand(1);
3302 bool IsExp10 = false;
3303
3304 if (getValue(Val).getValueType() == MVT::f32 &&
Bill Wendling277fc242008-09-10 00:24:59 +00003305 getValue(I.getOperand(2)).getValueType() == MVT::f32 &&
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003306 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3307 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(Val))) {
3308 if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
3309 APFloat Ten(10.0f);
3310 IsExp10 = CFP->getValueAPF().bitwiseIsEqual(Ten);
3311 }
3312 }
3313 }
3314
3315 if (IsExp10 && LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3316 SDValue Op = getValue(I.getOperand(2));
3317
3318 // Put the exponent in the right bit position for later addition to the
3319 // final result:
3320 //
3321 // #define LOG2OF10 3.3219281f
3322 // IntegerPartOfX = (int32_t)(x * LOG2OF10);
3323 SDValue t0 = DAG.getNode(ISD::FMUL, MVT::f32, Op,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003324 getF32Constant(DAG, 0x40549a78));
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003325 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, MVT::i32, t0);
3326
3327 // FractionalPartOfX = x - (float)IntegerPartOfX;
3328 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, MVT::f32, IntegerPartOfX);
3329 SDValue X = DAG.getNode(ISD::FSUB, MVT::f32, t0, t1);
3330
3331 // IntegerPartOfX <<= 23;
3332 IntegerPartOfX = DAG.getNode(ISD::SHL, MVT::i32, IntegerPartOfX,
3333 DAG.getConstant(23, MVT::i32));
3334
3335 if (LimitFloatPrecision <= 6) {
3336 // For floating-point precision of 6:
3337 //
3338 // twoToFractionalPartOfX =
3339 // 0.997535578f +
3340 // (0.735607626f + 0.252464424f * x) * x;
3341 //
3342 // error 0.0144103317, which is 6 bits
3343 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003344 getF32Constant(DAG, 0x3e814304));
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003345 SDValue t3 = DAG.getNode(ISD::FADD, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003346 getF32Constant(DAG, 0x3f3c50c8));
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003347 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3348 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003349 getF32Constant(DAG, 0x3f7f5e7e));
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003350 SDValue t6 = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, t5);
3351 SDValue TwoToFractionalPartOfX =
3352 DAG.getNode(ISD::ADD, MVT::i32, t6, IntegerPartOfX);
3353
3354 result = DAG.getNode(ISD::BIT_CONVERT, MVT::f32, TwoToFractionalPartOfX);
3355 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3356 // For floating-point precision of 12:
3357 //
3358 // TwoToFractionalPartOfX =
3359 // 0.999892986f +
3360 // (0.696457318f +
3361 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
3362 //
3363 // error 0.000107046256, which is 13 to 14 bits
3364 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003365 getF32Constant(DAG, 0x3da235e3));
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003366 SDValue t3 = DAG.getNode(ISD::FADD, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003367 getF32Constant(DAG, 0x3e65b8f3));
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003368 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3369 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003370 getF32Constant(DAG, 0x3f324b07));
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003371 SDValue t6 = DAG.getNode(ISD::FMUL, MVT::f32, t5, X);
3372 SDValue t7 = DAG.getNode(ISD::FADD, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003373 getF32Constant(DAG, 0x3f7ff8fd));
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003374 SDValue t8 = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, t7);
3375 SDValue TwoToFractionalPartOfX =
3376 DAG.getNode(ISD::ADD, MVT::i32, t8, IntegerPartOfX);
3377
3378 result = DAG.getNode(ISD::BIT_CONVERT, MVT::f32, TwoToFractionalPartOfX);
3379 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3380 // For floating-point precision of 18:
3381 //
3382 // TwoToFractionalPartOfX =
3383 // 0.999999982f +
3384 // (0.693148872f +
3385 // (0.240227044f +
3386 // (0.554906021e-1f +
3387 // (0.961591928e-2f +
3388 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
3389 // error 2.47208000*10^(-7), which is better than 18 bits
3390 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003391 getF32Constant(DAG, 0x3924b03e));
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003392 SDValue t3 = DAG.getNode(ISD::FADD, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003393 getF32Constant(DAG, 0x3ab24b87));
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003394 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3395 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003396 getF32Constant(DAG, 0x3c1d8c17));
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003397 SDValue t6 = DAG.getNode(ISD::FMUL, MVT::f32, t5, X);
3398 SDValue t7 = DAG.getNode(ISD::FADD, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003399 getF32Constant(DAG, 0x3d634a1d));
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003400 SDValue t8 = DAG.getNode(ISD::FMUL, MVT::f32, t7, X);
3401 SDValue t9 = DAG.getNode(ISD::FADD, MVT::f32, t8,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003402 getF32Constant(DAG, 0x3e75fe14));
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003403 SDValue t10 = DAG.getNode(ISD::FMUL, MVT::f32, t9, X);
3404 SDValue t11 = DAG.getNode(ISD::FADD, MVT::f32, t10,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003405 getF32Constant(DAG, 0x3f317234));
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003406 SDValue t12 = DAG.getNode(ISD::FMUL, MVT::f32, t11, X);
3407 SDValue t13 = DAG.getNode(ISD::FADD, MVT::f32, t12,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003408 getF32Constant(DAG, 0x3f800000));
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003409 SDValue t14 = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, t13);
3410 SDValue TwoToFractionalPartOfX =
3411 DAG.getNode(ISD::ADD, MVT::i32, t14, IntegerPartOfX);
3412
3413 result = DAG.getNode(ISD::BIT_CONVERT, MVT::f32, TwoToFractionalPartOfX);
3414 }
3415 } else {
3416 // No special expansion.
3417 result = DAG.getNode(ISD::FPOW,
3418 getValue(I.getOperand(1)).getValueType(),
3419 getValue(I.getOperand(1)),
3420 getValue(I.getOperand(2)));
3421 }
3422
3423 setValue(&I, result);
3424}
3425
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003426/// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
3427/// we want to emit this as a call to a named external function, return the name
3428/// otherwise lower it and return null.
3429const char *
3430SelectionDAGLowering::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
3431 switch (Intrinsic) {
3432 default:
3433 // By default, turn this into a target intrinsic node.
3434 visitTargetIntrinsic(I, Intrinsic);
3435 return 0;
3436 case Intrinsic::vastart: visitVAStart(I); return 0;
3437 case Intrinsic::vaend: visitVAEnd(I); return 0;
3438 case Intrinsic::vacopy: visitVACopy(I); return 0;
3439 case Intrinsic::returnaddress:
3440 setValue(&I, DAG.getNode(ISD::RETURNADDR, TLI.getPointerTy(),
3441 getValue(I.getOperand(1))));
3442 return 0;
Bill Wendlingd5d81912008-09-26 22:10:44 +00003443 case Intrinsic::frameaddress:
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003444 setValue(&I, DAG.getNode(ISD::FRAMEADDR, TLI.getPointerTy(),
3445 getValue(I.getOperand(1))));
3446 return 0;
3447 case Intrinsic::setjmp:
3448 return "_setjmp"+!TLI.usesUnderscoreSetJmp();
3449 break;
3450 case Intrinsic::longjmp:
3451 return "_longjmp"+!TLI.usesUnderscoreLongJmp();
3452 break;
3453 case Intrinsic::memcpy_i32:
3454 case Intrinsic::memcpy_i64: {
3455 SDValue Op1 = getValue(I.getOperand(1));
3456 SDValue Op2 = getValue(I.getOperand(2));
3457 SDValue Op3 = getValue(I.getOperand(3));
3458 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
3459 DAG.setRoot(DAG.getMemcpy(getRoot(), Op1, Op2, Op3, Align, false,
3460 I.getOperand(1), 0, I.getOperand(2), 0));
3461 return 0;
3462 }
3463 case Intrinsic::memset_i32:
3464 case Intrinsic::memset_i64: {
3465 SDValue Op1 = getValue(I.getOperand(1));
3466 SDValue Op2 = getValue(I.getOperand(2));
3467 SDValue Op3 = getValue(I.getOperand(3));
3468 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
3469 DAG.setRoot(DAG.getMemset(getRoot(), Op1, Op2, Op3, Align,
3470 I.getOperand(1), 0));
3471 return 0;
3472 }
3473 case Intrinsic::memmove_i32:
3474 case Intrinsic::memmove_i64: {
3475 SDValue Op1 = getValue(I.getOperand(1));
3476 SDValue Op2 = getValue(I.getOperand(2));
3477 SDValue Op3 = getValue(I.getOperand(3));
3478 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
3479
3480 // If the source and destination are known to not be aliases, we can
3481 // lower memmove as memcpy.
3482 uint64_t Size = -1ULL;
3483 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op3))
Dan Gohmanf5aeb1a2008-09-12 16:56:44 +00003484 Size = C->getZExtValue();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003485 if (AA->alias(I.getOperand(1), Size, I.getOperand(2), Size) ==
3486 AliasAnalysis::NoAlias) {
3487 DAG.setRoot(DAG.getMemcpy(getRoot(), Op1, Op2, Op3, Align, false,
3488 I.getOperand(1), 0, I.getOperand(2), 0));
3489 return 0;
3490 }
3491
3492 DAG.setRoot(DAG.getMemmove(getRoot(), Op1, Op2, Op3, Align,
3493 I.getOperand(1), 0, I.getOperand(2), 0));
3494 return 0;
3495 }
3496 case Intrinsic::dbg_stoppoint: {
3497 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3498 DbgStopPointInst &SPI = cast<DbgStopPointInst>(I);
3499 if (MMI && SPI.getContext() && MMI->Verify(SPI.getContext())) {
3500 DebugInfoDesc *DD = MMI->getDescFor(SPI.getContext());
3501 assert(DD && "Not a debug information descriptor");
3502 DAG.setRoot(DAG.getDbgStopPoint(getRoot(),
3503 SPI.getLine(),
3504 SPI.getColumn(),
3505 cast<CompileUnitDesc>(DD)));
3506 }
3507
3508 return 0;
3509 }
3510 case Intrinsic::dbg_region_start: {
3511 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3512 DbgRegionStartInst &RSI = cast<DbgRegionStartInst>(I);
3513 if (MMI && RSI.getContext() && MMI->Verify(RSI.getContext())) {
3514 unsigned LabelID = MMI->RecordRegionStart(RSI.getContext());
3515 DAG.setRoot(DAG.getLabel(ISD::DBG_LABEL, getRoot(), LabelID));
3516 }
3517
3518 return 0;
3519 }
3520 case Intrinsic::dbg_region_end: {
3521 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3522 DbgRegionEndInst &REI = cast<DbgRegionEndInst>(I);
3523 if (MMI && REI.getContext() && MMI->Verify(REI.getContext())) {
3524 unsigned LabelID = MMI->RecordRegionEnd(REI.getContext());
3525 DAG.setRoot(DAG.getLabel(ISD::DBG_LABEL, getRoot(), LabelID));
3526 }
3527
3528 return 0;
3529 }
3530 case Intrinsic::dbg_func_start: {
3531 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3532 if (!MMI) return 0;
3533 DbgFuncStartInst &FSI = cast<DbgFuncStartInst>(I);
3534 Value *SP = FSI.getSubprogram();
3535 if (SP && MMI->Verify(SP)) {
3536 // llvm.dbg.func.start implicitly defines a dbg_stoppoint which is
3537 // what (most?) gdb expects.
3538 DebugInfoDesc *DD = MMI->getDescFor(SP);
3539 assert(DD && "Not a debug information descriptor");
3540 SubprogramDesc *Subprogram = cast<SubprogramDesc>(DD);
3541 const CompileUnitDesc *CompileUnit = Subprogram->getFile();
3542 unsigned SrcFile = MMI->RecordSource(CompileUnit);
3543 // Record the source line but does create a label. It will be emitted
3544 // at asm emission time.
3545 MMI->RecordSourceLine(Subprogram->getLine(), 0, SrcFile);
3546 }
3547
3548 return 0;
3549 }
3550 case Intrinsic::dbg_declare: {
3551 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3552 DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
3553 Value *Variable = DI.getVariable();
3554 if (MMI && Variable && MMI->Verify(Variable))
3555 DAG.setRoot(DAG.getNode(ISD::DECLARE, MVT::Other, getRoot(),
3556 getValue(DI.getAddress()), getValue(Variable)));
3557 return 0;
3558 }
3559
3560 case Intrinsic::eh_exception: {
3561 if (!CurMBB->isLandingPad()) {
3562 // FIXME: Mark exception register as live in. Hack for PR1508.
3563 unsigned Reg = TLI.getExceptionAddressRegister();
3564 if (Reg) CurMBB->addLiveIn(Reg);
3565 }
3566 // Insert the EXCEPTIONADDR instruction.
3567 SDVTList VTs = DAG.getVTList(TLI.getPointerTy(), MVT::Other);
3568 SDValue Ops[1];
3569 Ops[0] = DAG.getRoot();
3570 SDValue Op = DAG.getNode(ISD::EXCEPTIONADDR, VTs, Ops, 1);
3571 setValue(&I, Op);
3572 DAG.setRoot(Op.getValue(1));
3573 return 0;
3574 }
3575
3576 case Intrinsic::eh_selector_i32:
3577 case Intrinsic::eh_selector_i64: {
3578 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3579 MVT VT = (Intrinsic == Intrinsic::eh_selector_i32 ?
3580 MVT::i32 : MVT::i64);
3581
3582 if (MMI) {
3583 if (CurMBB->isLandingPad())
3584 AddCatchInfo(I, MMI, CurMBB);
3585 else {
3586#ifndef NDEBUG
3587 FuncInfo.CatchInfoLost.insert(&I);
3588#endif
3589 // FIXME: Mark exception selector register as live in. Hack for PR1508.
3590 unsigned Reg = TLI.getExceptionSelectorRegister();
3591 if (Reg) CurMBB->addLiveIn(Reg);
3592 }
3593
3594 // Insert the EHSELECTION instruction.
3595 SDVTList VTs = DAG.getVTList(VT, MVT::Other);
3596 SDValue Ops[2];
3597 Ops[0] = getValue(I.getOperand(1));
3598 Ops[1] = getRoot();
3599 SDValue Op = DAG.getNode(ISD::EHSELECTION, VTs, Ops, 2);
3600 setValue(&I, Op);
3601 DAG.setRoot(Op.getValue(1));
3602 } else {
3603 setValue(&I, DAG.getConstant(0, VT));
3604 }
3605
3606 return 0;
3607 }
3608
3609 case Intrinsic::eh_typeid_for_i32:
3610 case Intrinsic::eh_typeid_for_i64: {
3611 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3612 MVT VT = (Intrinsic == Intrinsic::eh_typeid_for_i32 ?
3613 MVT::i32 : MVT::i64);
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00003614
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003615 if (MMI) {
3616 // Find the type id for the given typeinfo.
3617 GlobalVariable *GV = ExtractTypeInfo(I.getOperand(1));
3618
3619 unsigned TypeID = MMI->getTypeIDFor(GV);
3620 setValue(&I, DAG.getConstant(TypeID, VT));
3621 } else {
3622 // Return something different to eh_selector.
3623 setValue(&I, DAG.getConstant(1, VT));
3624 }
3625
3626 return 0;
3627 }
3628
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00003629 case Intrinsic::eh_return_i32:
3630 case Intrinsic::eh_return_i64:
3631 if (MachineModuleInfo *MMI = DAG.getMachineModuleInfo()) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003632 MMI->setCallsEHReturn(true);
3633 DAG.setRoot(DAG.getNode(ISD::EH_RETURN,
3634 MVT::Other,
3635 getControlRoot(),
3636 getValue(I.getOperand(1)),
3637 getValue(I.getOperand(2))));
3638 } else {
3639 setValue(&I, DAG.getConstant(0, TLI.getPointerTy()));
3640 }
3641
3642 return 0;
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00003643 case Intrinsic::eh_unwind_init:
3644 if (MachineModuleInfo *MMI = DAG.getMachineModuleInfo()) {
3645 MMI->setCallsUnwindInit(true);
3646 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003647
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00003648 return 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003649
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00003650 case Intrinsic::eh_dwarf_cfa: {
3651 MVT VT = getValue(I.getOperand(1)).getValueType();
3652 SDValue CfaArg;
3653 if (VT.bitsGT(TLI.getPointerTy()))
3654 CfaArg = DAG.getNode(ISD::TRUNCATE,
3655 TLI.getPointerTy(), getValue(I.getOperand(1)));
3656 else
3657 CfaArg = DAG.getNode(ISD::SIGN_EXTEND,
3658 TLI.getPointerTy(), getValue(I.getOperand(1)));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003659
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00003660 SDValue Offset = DAG.getNode(ISD::ADD,
3661 TLI.getPointerTy(),
3662 DAG.getNode(ISD::FRAME_TO_ARGS_OFFSET,
3663 TLI.getPointerTy()),
3664 CfaArg);
3665 setValue(&I, DAG.getNode(ISD::ADD,
3666 TLI.getPointerTy(),
3667 DAG.getNode(ISD::FRAMEADDR,
3668 TLI.getPointerTy(),
3669 DAG.getConstant(0,
3670 TLI.getPointerTy())),
3671 Offset));
3672 return 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003673 }
3674
3675 case Intrinsic::sqrt:
3676 setValue(&I, DAG.getNode(ISD::FSQRT,
3677 getValue(I.getOperand(1)).getValueType(),
3678 getValue(I.getOperand(1))));
3679 return 0;
3680 case Intrinsic::powi:
3681 setValue(&I, DAG.getNode(ISD::FPOWI,
3682 getValue(I.getOperand(1)).getValueType(),
3683 getValue(I.getOperand(1)),
3684 getValue(I.getOperand(2))));
3685 return 0;
3686 case Intrinsic::sin:
3687 setValue(&I, DAG.getNode(ISD::FSIN,
3688 getValue(I.getOperand(1)).getValueType(),
3689 getValue(I.getOperand(1))));
3690 return 0;
3691 case Intrinsic::cos:
3692 setValue(&I, DAG.getNode(ISD::FCOS,
3693 getValue(I.getOperand(1)).getValueType(),
3694 getValue(I.getOperand(1))));
3695 return 0;
Dale Johannesen7794f2a2008-09-04 00:47:13 +00003696 case Intrinsic::log:
Dale Johannesen59e577f2008-09-05 18:38:42 +00003697 visitLog(I);
Dale Johannesen7794f2a2008-09-04 00:47:13 +00003698 return 0;
3699 case Intrinsic::log2:
Dale Johannesen59e577f2008-09-05 18:38:42 +00003700 visitLog2(I);
Dale Johannesen7794f2a2008-09-04 00:47:13 +00003701 return 0;
3702 case Intrinsic::log10:
Dale Johannesen59e577f2008-09-05 18:38:42 +00003703 visitLog10(I);
Dale Johannesen7794f2a2008-09-04 00:47:13 +00003704 return 0;
3705 case Intrinsic::exp:
Dale Johannesen59e577f2008-09-05 18:38:42 +00003706 visitExp(I);
Dale Johannesen7794f2a2008-09-04 00:47:13 +00003707 return 0;
3708 case Intrinsic::exp2:
Dale Johannesen601d3c02008-09-05 01:48:15 +00003709 visitExp2(I);
Dale Johannesen7794f2a2008-09-04 00:47:13 +00003710 return 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003711 case Intrinsic::pow:
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003712 visitPow(I);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003713 return 0;
3714 case Intrinsic::pcmarker: {
3715 SDValue Tmp = getValue(I.getOperand(1));
3716 DAG.setRoot(DAG.getNode(ISD::PCMARKER, MVT::Other, getRoot(), Tmp));
3717 return 0;
3718 }
3719 case Intrinsic::readcyclecounter: {
3720 SDValue Op = getRoot();
3721 SDValue Tmp = DAG.getNode(ISD::READCYCLECOUNTER,
3722 DAG.getNodeValueTypes(MVT::i64, MVT::Other), 2,
3723 &Op, 1);
3724 setValue(&I, Tmp);
3725 DAG.setRoot(Tmp.getValue(1));
3726 return 0;
3727 }
3728 case Intrinsic::part_select: {
3729 // Currently not implemented: just abort
3730 assert(0 && "part_select intrinsic not implemented");
3731 abort();
3732 }
3733 case Intrinsic::part_set: {
3734 // Currently not implemented: just abort
3735 assert(0 && "part_set intrinsic not implemented");
3736 abort();
3737 }
3738 case Intrinsic::bswap:
3739 setValue(&I, DAG.getNode(ISD::BSWAP,
3740 getValue(I.getOperand(1)).getValueType(),
3741 getValue(I.getOperand(1))));
3742 return 0;
3743 case Intrinsic::cttz: {
3744 SDValue Arg = getValue(I.getOperand(1));
3745 MVT Ty = Arg.getValueType();
3746 SDValue result = DAG.getNode(ISD::CTTZ, Ty, Arg);
3747 setValue(&I, result);
3748 return 0;
3749 }
3750 case Intrinsic::ctlz: {
3751 SDValue Arg = getValue(I.getOperand(1));
3752 MVT Ty = Arg.getValueType();
3753 SDValue result = DAG.getNode(ISD::CTLZ, Ty, Arg);
3754 setValue(&I, result);
3755 return 0;
3756 }
3757 case Intrinsic::ctpop: {
3758 SDValue Arg = getValue(I.getOperand(1));
3759 MVT Ty = Arg.getValueType();
3760 SDValue result = DAG.getNode(ISD::CTPOP, Ty, Arg);
3761 setValue(&I, result);
3762 return 0;
3763 }
3764 case Intrinsic::stacksave: {
3765 SDValue Op = getRoot();
3766 SDValue Tmp = DAG.getNode(ISD::STACKSAVE,
3767 DAG.getNodeValueTypes(TLI.getPointerTy(), MVT::Other), 2, &Op, 1);
3768 setValue(&I, Tmp);
3769 DAG.setRoot(Tmp.getValue(1));
3770 return 0;
3771 }
3772 case Intrinsic::stackrestore: {
3773 SDValue Tmp = getValue(I.getOperand(1));
3774 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, MVT::Other, getRoot(), Tmp));
3775 return 0;
3776 }
3777 case Intrinsic::var_annotation:
3778 // Discard annotate attributes
3779 return 0;
3780
3781 case Intrinsic::init_trampoline: {
3782 const Function *F = cast<Function>(I.getOperand(2)->stripPointerCasts());
3783
3784 SDValue Ops[6];
3785 Ops[0] = getRoot();
3786 Ops[1] = getValue(I.getOperand(1));
3787 Ops[2] = getValue(I.getOperand(2));
3788 Ops[3] = getValue(I.getOperand(3));
3789 Ops[4] = DAG.getSrcValue(I.getOperand(1));
3790 Ops[5] = DAG.getSrcValue(F);
3791
3792 SDValue Tmp = DAG.getNode(ISD::TRAMPOLINE,
3793 DAG.getNodeValueTypes(TLI.getPointerTy(),
3794 MVT::Other), 2,
3795 Ops, 6);
3796
3797 setValue(&I, Tmp);
3798 DAG.setRoot(Tmp.getValue(1));
3799 return 0;
3800 }
3801
3802 case Intrinsic::gcroot:
3803 if (GFI) {
3804 Value *Alloca = I.getOperand(1);
3805 Constant *TypeMap = cast<Constant>(I.getOperand(2));
3806
3807 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
3808 GFI->addStackRoot(FI->getIndex(), TypeMap);
3809 }
3810 return 0;
3811
3812 case Intrinsic::gcread:
3813 case Intrinsic::gcwrite:
3814 assert(0 && "GC failed to lower gcread/gcwrite intrinsics!");
3815 return 0;
3816
3817 case Intrinsic::flt_rounds: {
3818 setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, MVT::i32));
3819 return 0;
3820 }
3821
3822 case Intrinsic::trap: {
3823 DAG.setRoot(DAG.getNode(ISD::TRAP, MVT::Other, getRoot()));
3824 return 0;
3825 }
3826 case Intrinsic::prefetch: {
3827 SDValue Ops[4];
3828 Ops[0] = getRoot();
3829 Ops[1] = getValue(I.getOperand(1));
3830 Ops[2] = getValue(I.getOperand(2));
3831 Ops[3] = getValue(I.getOperand(3));
3832 DAG.setRoot(DAG.getNode(ISD::PREFETCH, MVT::Other, &Ops[0], 4));
3833 return 0;
3834 }
3835
3836 case Intrinsic::memory_barrier: {
3837 SDValue Ops[6];
3838 Ops[0] = getRoot();
3839 for (int x = 1; x < 6; ++x)
3840 Ops[x] = getValue(I.getOperand(x));
3841
3842 DAG.setRoot(DAG.getNode(ISD::MEMBARRIER, MVT::Other, &Ops[0], 6));
3843 return 0;
3844 }
3845 case Intrinsic::atomic_cmp_swap: {
3846 SDValue Root = getRoot();
3847 SDValue L;
3848 switch (getValue(I.getOperand(2)).getValueType().getSimpleVT()) {
3849 case MVT::i8:
3850 L = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP_8, 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::i16:
3857 L = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP_16, Root,
3858 getValue(I.getOperand(1)),
3859 getValue(I.getOperand(2)),
3860 getValue(I.getOperand(3)),
3861 I.getOperand(1));
3862 break;
3863 case MVT::i32:
3864 L = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP_32, Root,
3865 getValue(I.getOperand(1)),
3866 getValue(I.getOperand(2)),
3867 getValue(I.getOperand(3)),
3868 I.getOperand(1));
3869 break;
3870 case MVT::i64:
3871 L = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP_64, Root,
3872 getValue(I.getOperand(1)),
3873 getValue(I.getOperand(2)),
3874 getValue(I.getOperand(3)),
3875 I.getOperand(1));
3876 break;
3877 default:
3878 assert(0 && "Invalid atomic type");
3879 abort();
3880 }
3881 setValue(&I, L);
3882 DAG.setRoot(L.getValue(1));
3883 return 0;
3884 }
3885 case Intrinsic::atomic_load_add:
3886 switch (getValue(I.getOperand(2)).getValueType().getSimpleVT()) {
3887 case MVT::i8:
3888 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_ADD_8);
3889 case MVT::i16:
3890 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_ADD_16);
3891 case MVT::i32:
3892 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_ADD_32);
3893 case MVT::i64:
3894 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_ADD_64);
3895 default:
3896 assert(0 && "Invalid atomic type");
3897 abort();
3898 }
3899 case Intrinsic::atomic_load_sub:
3900 switch (getValue(I.getOperand(2)).getValueType().getSimpleVT()) {
3901 case MVT::i8:
3902 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_SUB_8);
3903 case MVT::i16:
3904 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_SUB_16);
3905 case MVT::i32:
3906 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_SUB_32);
3907 case MVT::i64:
3908 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_SUB_64);
3909 default:
3910 assert(0 && "Invalid atomic type");
3911 abort();
3912 }
3913 case Intrinsic::atomic_load_or:
3914 switch (getValue(I.getOperand(2)).getValueType().getSimpleVT()) {
3915 case MVT::i8:
3916 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_OR_8);
3917 case MVT::i16:
3918 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_OR_16);
3919 case MVT::i32:
3920 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_OR_32);
3921 case MVT::i64:
3922 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_OR_64);
3923 default:
3924 assert(0 && "Invalid atomic type");
3925 abort();
3926 }
3927 case Intrinsic::atomic_load_xor:
3928 switch (getValue(I.getOperand(2)).getValueType().getSimpleVT()) {
3929 case MVT::i8:
3930 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_XOR_8);
3931 case MVT::i16:
3932 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_XOR_16);
3933 case MVT::i32:
3934 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_XOR_32);
3935 case MVT::i64:
3936 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_XOR_64);
3937 default:
3938 assert(0 && "Invalid atomic type");
3939 abort();
3940 }
3941 case Intrinsic::atomic_load_and:
3942 switch (getValue(I.getOperand(2)).getValueType().getSimpleVT()) {
3943 case MVT::i8:
3944 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_AND_8);
3945 case MVT::i16:
3946 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_AND_16);
3947 case MVT::i32:
3948 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_AND_32);
3949 case MVT::i64:
3950 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_AND_64);
3951 default:
3952 assert(0 && "Invalid atomic type");
3953 abort();
3954 }
3955 case Intrinsic::atomic_load_nand:
3956 switch (getValue(I.getOperand(2)).getValueType().getSimpleVT()) {
3957 case MVT::i8:
3958 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_NAND_8);
3959 case MVT::i16:
3960 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_NAND_16);
3961 case MVT::i32:
3962 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_NAND_32);
3963 case MVT::i64:
3964 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_NAND_64);
3965 default:
3966 assert(0 && "Invalid atomic type");
3967 abort();
3968 }
3969 case Intrinsic::atomic_load_max:
3970 switch (getValue(I.getOperand(2)).getValueType().getSimpleVT()) {
3971 case MVT::i8:
3972 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MAX_8);
3973 case MVT::i16:
3974 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MAX_16);
3975 case MVT::i32:
3976 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MAX_32);
3977 case MVT::i64:
3978 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MAX_64);
3979 default:
3980 assert(0 && "Invalid atomic type");
3981 abort();
3982 }
3983 case Intrinsic::atomic_load_min:
3984 switch (getValue(I.getOperand(2)).getValueType().getSimpleVT()) {
3985 case MVT::i8:
3986 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MIN_8);
3987 case MVT::i16:
3988 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MIN_16);
3989 case MVT::i32:
3990 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MIN_32);
3991 case MVT::i64:
3992 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MIN_64);
3993 default:
3994 assert(0 && "Invalid atomic type");
3995 abort();
3996 }
3997 case Intrinsic::atomic_load_umin:
3998 switch (getValue(I.getOperand(2)).getValueType().getSimpleVT()) {
3999 case MVT::i8:
4000 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMIN_8);
4001 case MVT::i16:
4002 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMIN_16);
4003 case MVT::i32:
4004 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMIN_32);
4005 case MVT::i64:
4006 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMIN_64);
4007 default:
4008 assert(0 && "Invalid atomic type");
4009 abort();
4010 }
4011 case Intrinsic::atomic_load_umax:
4012 switch (getValue(I.getOperand(2)).getValueType().getSimpleVT()) {
4013 case MVT::i8:
4014 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMAX_8);
4015 case MVT::i16:
4016 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMAX_16);
4017 case MVT::i32:
4018 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMAX_32);
4019 case MVT::i64:
4020 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMAX_64);
4021 default:
4022 assert(0 && "Invalid atomic type");
4023 abort();
4024 }
4025 case Intrinsic::atomic_swap:
4026 switch (getValue(I.getOperand(2)).getValueType().getSimpleVT()) {
4027 case MVT::i8:
4028 return implVisitBinaryAtomic(I, ISD::ATOMIC_SWAP_8);
4029 case MVT::i16:
4030 return implVisitBinaryAtomic(I, ISD::ATOMIC_SWAP_16);
4031 case MVT::i32:
4032 return implVisitBinaryAtomic(I, ISD::ATOMIC_SWAP_32);
4033 case MVT::i64:
4034 return implVisitBinaryAtomic(I, ISD::ATOMIC_SWAP_64);
4035 default:
4036 assert(0 && "Invalid atomic type");
4037 abort();
4038 }
4039 }
4040}
4041
4042
4043void SelectionDAGLowering::LowerCallTo(CallSite CS, SDValue Callee,
4044 bool IsTailCall,
4045 MachineBasicBlock *LandingPad) {
4046 const PointerType *PT = cast<PointerType>(CS.getCalledValue()->getType());
4047 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
4048 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
4049 unsigned BeginLabel = 0, EndLabel = 0;
4050
4051 TargetLowering::ArgListTy Args;
4052 TargetLowering::ArgListEntry Entry;
4053 Args.reserve(CS.arg_size());
4054 for (CallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
4055 i != e; ++i) {
4056 SDValue ArgNode = getValue(*i);
4057 Entry.Node = ArgNode; Entry.Ty = (*i)->getType();
4058
4059 unsigned attrInd = i - CS.arg_begin() + 1;
Devang Patel05988662008-09-25 21:00:45 +00004060 Entry.isSExt = CS.paramHasAttr(attrInd, Attribute::SExt);
4061 Entry.isZExt = CS.paramHasAttr(attrInd, Attribute::ZExt);
4062 Entry.isInReg = CS.paramHasAttr(attrInd, Attribute::InReg);
4063 Entry.isSRet = CS.paramHasAttr(attrInd, Attribute::StructRet);
4064 Entry.isNest = CS.paramHasAttr(attrInd, Attribute::Nest);
4065 Entry.isByVal = CS.paramHasAttr(attrInd, Attribute::ByVal);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004066 Entry.Alignment = CS.getParamAlignment(attrInd);
4067 Args.push_back(Entry);
4068 }
4069
4070 if (LandingPad && MMI) {
4071 // Insert a label before the invoke call to mark the try range. This can be
4072 // used to detect deletion of the invoke via the MachineModuleInfo.
4073 BeginLabel = MMI->NextLabelID();
4074 // Both PendingLoads and PendingExports must be flushed here;
4075 // this call might not return.
4076 (void)getRoot();
4077 DAG.setRoot(DAG.getLabel(ISD::EH_LABEL, getControlRoot(), BeginLabel));
4078 }
4079
4080 std::pair<SDValue,SDValue> Result =
4081 TLI.LowerCallTo(getRoot(), CS.getType(),
Devang Patel05988662008-09-25 21:00:45 +00004082 CS.paramHasAttr(0, Attribute::SExt),
Dale Johannesen86098bd2008-09-26 19:31:26 +00004083 CS.paramHasAttr(0, Attribute::ZExt), FTy->isVarArg(),
4084 CS.paramHasAttr(0, Attribute::InReg),
4085 CS.getCallingConv(),
Dan Gohman1937e2f2008-09-16 01:42:28 +00004086 IsTailCall && PerformTailCallOpt,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004087 Callee, Args, DAG);
4088 if (CS.getType() != Type::VoidTy)
4089 setValue(CS.getInstruction(), Result.first);
4090 DAG.setRoot(Result.second);
4091
4092 if (LandingPad && MMI) {
4093 // Insert a label at the end of the invoke call to mark the try range. This
4094 // can be used to detect deletion of the invoke via the MachineModuleInfo.
4095 EndLabel = MMI->NextLabelID();
4096 DAG.setRoot(DAG.getLabel(ISD::EH_LABEL, getRoot(), EndLabel));
4097
4098 // Inform MachineModuleInfo of range.
4099 MMI->addInvoke(LandingPad, BeginLabel, EndLabel);
4100 }
4101}
4102
4103
4104void SelectionDAGLowering::visitCall(CallInst &I) {
4105 const char *RenameFn = 0;
4106 if (Function *F = I.getCalledFunction()) {
4107 if (F->isDeclaration()) {
4108 if (unsigned IID = F->getIntrinsicID()) {
4109 RenameFn = visitIntrinsicCall(I, IID);
4110 if (!RenameFn)
4111 return;
4112 }
4113 }
4114
4115 // Check for well-known libc/libm calls. If the function is internal, it
4116 // can't be a library call.
4117 unsigned NameLen = F->getNameLen();
4118 if (!F->hasInternalLinkage() && NameLen) {
4119 const char *NameStr = F->getNameStart();
4120 if (NameStr[0] == 'c' &&
4121 ((NameLen == 8 && !strcmp(NameStr, "copysign")) ||
4122 (NameLen == 9 && !strcmp(NameStr, "copysignf")))) {
4123 if (I.getNumOperands() == 3 && // Basic sanity checks.
4124 I.getOperand(1)->getType()->isFloatingPoint() &&
4125 I.getType() == I.getOperand(1)->getType() &&
4126 I.getType() == I.getOperand(2)->getType()) {
4127 SDValue LHS = getValue(I.getOperand(1));
4128 SDValue RHS = getValue(I.getOperand(2));
4129 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, LHS.getValueType(),
4130 LHS, RHS));
4131 return;
4132 }
4133 } else if (NameStr[0] == 'f' &&
4134 ((NameLen == 4 && !strcmp(NameStr, "fabs")) ||
4135 (NameLen == 5 && !strcmp(NameStr, "fabsf")) ||
4136 (NameLen == 5 && !strcmp(NameStr, "fabsl")))) {
4137 if (I.getNumOperands() == 2 && // Basic sanity checks.
4138 I.getOperand(1)->getType()->isFloatingPoint() &&
4139 I.getType() == I.getOperand(1)->getType()) {
4140 SDValue Tmp = getValue(I.getOperand(1));
4141 setValue(&I, DAG.getNode(ISD::FABS, Tmp.getValueType(), Tmp));
4142 return;
4143 }
4144 } else if (NameStr[0] == 's' &&
4145 ((NameLen == 3 && !strcmp(NameStr, "sin")) ||
4146 (NameLen == 4 && !strcmp(NameStr, "sinf")) ||
4147 (NameLen == 4 && !strcmp(NameStr, "sinl")))) {
4148 if (I.getNumOperands() == 2 && // Basic sanity checks.
4149 I.getOperand(1)->getType()->isFloatingPoint() &&
4150 I.getType() == I.getOperand(1)->getType()) {
4151 SDValue Tmp = getValue(I.getOperand(1));
4152 setValue(&I, DAG.getNode(ISD::FSIN, Tmp.getValueType(), Tmp));
4153 return;
4154 }
4155 } else if (NameStr[0] == 'c' &&
4156 ((NameLen == 3 && !strcmp(NameStr, "cos")) ||
4157 (NameLen == 4 && !strcmp(NameStr, "cosf")) ||
4158 (NameLen == 4 && !strcmp(NameStr, "cosl")))) {
4159 if (I.getNumOperands() == 2 && // Basic sanity checks.
4160 I.getOperand(1)->getType()->isFloatingPoint() &&
4161 I.getType() == I.getOperand(1)->getType()) {
4162 SDValue Tmp = getValue(I.getOperand(1));
4163 setValue(&I, DAG.getNode(ISD::FCOS, Tmp.getValueType(), Tmp));
4164 return;
4165 }
4166 }
4167 }
4168 } else if (isa<InlineAsm>(I.getOperand(0))) {
4169 visitInlineAsm(&I);
4170 return;
4171 }
4172
4173 SDValue Callee;
4174 if (!RenameFn)
4175 Callee = getValue(I.getOperand(0));
4176 else
Bill Wendling056292f2008-09-16 21:48:12 +00004177 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004178
4179 LowerCallTo(&I, Callee, I.isTailCall());
4180}
4181
4182
4183/// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
4184/// this value and returns the result as a ValueVT value. This uses
4185/// Chain/Flag as the input and updates them for the output Chain/Flag.
4186/// If the Flag pointer is NULL, no flag is used.
4187SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
4188 SDValue &Chain,
4189 SDValue *Flag) const {
4190 // Assemble the legal parts into the final values.
4191 SmallVector<SDValue, 4> Values(ValueVTs.size());
4192 SmallVector<SDValue, 8> Parts;
4193 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
4194 // Copy the legal parts from the registers.
4195 MVT ValueVT = ValueVTs[Value];
4196 unsigned NumRegs = TLI->getNumRegisters(ValueVT);
4197 MVT RegisterVT = RegVTs[Value];
4198
4199 Parts.resize(NumRegs);
4200 for (unsigned i = 0; i != NumRegs; ++i) {
4201 SDValue P;
4202 if (Flag == 0)
4203 P = DAG.getCopyFromReg(Chain, Regs[Part+i], RegisterVT);
4204 else {
4205 P = DAG.getCopyFromReg(Chain, Regs[Part+i], RegisterVT, *Flag);
4206 *Flag = P.getValue(2);
4207 }
4208 Chain = P.getValue(1);
4209
4210 // If the source register was virtual and if we know something about it,
4211 // add an assert node.
4212 if (TargetRegisterInfo::isVirtualRegister(Regs[Part+i]) &&
4213 RegisterVT.isInteger() && !RegisterVT.isVector()) {
4214 unsigned SlotNo = Regs[Part+i]-TargetRegisterInfo::FirstVirtualRegister;
4215 FunctionLoweringInfo &FLI = DAG.getFunctionLoweringInfo();
4216 if (FLI.LiveOutRegInfo.size() > SlotNo) {
4217 FunctionLoweringInfo::LiveOutInfo &LOI = FLI.LiveOutRegInfo[SlotNo];
4218
4219 unsigned RegSize = RegisterVT.getSizeInBits();
4220 unsigned NumSignBits = LOI.NumSignBits;
4221 unsigned NumZeroBits = LOI.KnownZero.countLeadingOnes();
4222
4223 // FIXME: We capture more information than the dag can represent. For
4224 // now, just use the tightest assertzext/assertsext possible.
4225 bool isSExt = true;
4226 MVT FromVT(MVT::Other);
4227 if (NumSignBits == RegSize)
4228 isSExt = true, FromVT = MVT::i1; // ASSERT SEXT 1
4229 else if (NumZeroBits >= RegSize-1)
4230 isSExt = false, FromVT = MVT::i1; // ASSERT ZEXT 1
4231 else if (NumSignBits > RegSize-8)
4232 isSExt = true, FromVT = MVT::i8; // ASSERT SEXT 8
4233 else if (NumZeroBits >= RegSize-9)
4234 isSExt = false, FromVT = MVT::i8; // ASSERT ZEXT 8
4235 else if (NumSignBits > RegSize-16)
Bill Wendling181b6272008-10-19 20:34:04 +00004236 isSExt = true, FromVT = MVT::i16; // ASSERT SEXT 16
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004237 else if (NumZeroBits >= RegSize-17)
Bill Wendling181b6272008-10-19 20:34:04 +00004238 isSExt = false, FromVT = MVT::i16; // ASSERT ZEXT 16
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004239 else if (NumSignBits > RegSize-32)
Bill Wendling181b6272008-10-19 20:34:04 +00004240 isSExt = true, FromVT = MVT::i32; // ASSERT SEXT 32
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004241 else if (NumZeroBits >= RegSize-33)
Bill Wendling181b6272008-10-19 20:34:04 +00004242 isSExt = false, FromVT = MVT::i32; // ASSERT ZEXT 32
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004243
4244 if (FromVT != MVT::Other) {
4245 P = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext,
4246 RegisterVT, P, DAG.getValueType(FromVT));
4247
4248 }
4249 }
4250 }
4251
4252 Parts[i] = P;
4253 }
4254
4255 Values[Value] = getCopyFromParts(DAG, Parts.begin(), NumRegs, RegisterVT,
4256 ValueVT);
4257 Part += NumRegs;
4258 Parts.clear();
4259 }
4260
4261 return DAG.getMergeValues(DAG.getVTList(&ValueVTs[0], ValueVTs.size()),
4262 &Values[0], ValueVTs.size());
4263}
4264
4265/// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
4266/// specified value into the registers specified by this object. This uses
4267/// Chain/Flag as the input and updates them for the output Chain/Flag.
4268/// If the Flag pointer is NULL, no flag is used.
4269void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG,
4270 SDValue &Chain, SDValue *Flag) const {
4271 // Get the list of the values's legal parts.
4272 unsigned NumRegs = Regs.size();
4273 SmallVector<SDValue, 8> Parts(NumRegs);
4274 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
4275 MVT ValueVT = ValueVTs[Value];
4276 unsigned NumParts = TLI->getNumRegisters(ValueVT);
4277 MVT RegisterVT = RegVTs[Value];
4278
4279 getCopyToParts(DAG, Val.getValue(Val.getResNo() + Value),
4280 &Parts[Part], NumParts, RegisterVT);
4281 Part += NumParts;
4282 }
4283
4284 // Copy the parts into the registers.
4285 SmallVector<SDValue, 8> Chains(NumRegs);
4286 for (unsigned i = 0; i != NumRegs; ++i) {
4287 SDValue Part;
4288 if (Flag == 0)
4289 Part = DAG.getCopyToReg(Chain, Regs[i], Parts[i]);
4290 else {
4291 Part = DAG.getCopyToReg(Chain, Regs[i], Parts[i], *Flag);
4292 *Flag = Part.getValue(1);
4293 }
4294 Chains[i] = Part.getValue(0);
4295 }
4296
4297 if (NumRegs == 1 || Flag)
4298 // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is
4299 // flagged to it. That is the CopyToReg nodes and the user are considered
4300 // a single scheduling unit. If we create a TokenFactor and return it as
4301 // chain, then the TokenFactor is both a predecessor (operand) of the
4302 // user as well as a successor (the TF operands are flagged to the user).
4303 // c1, f1 = CopyToReg
4304 // c2, f2 = CopyToReg
4305 // c3 = TokenFactor c1, c2
4306 // ...
4307 // = op c3, ..., f2
4308 Chain = Chains[NumRegs-1];
4309 else
4310 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other, &Chains[0], NumRegs);
4311}
4312
4313/// AddInlineAsmOperands - Add this value to the specified inlineasm node
4314/// operand list. This adds the code marker and includes the number of
4315/// values added into it.
4316void RegsForValue::AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
4317 std::vector<SDValue> &Ops) const {
4318 MVT IntPtrTy = DAG.getTargetLoweringInfo().getPointerTy();
4319 Ops.push_back(DAG.getTargetConstant(Code | (Regs.size() << 3), IntPtrTy));
4320 for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
4321 unsigned NumRegs = TLI->getNumRegisters(ValueVTs[Value]);
4322 MVT RegisterVT = RegVTs[Value];
Chris Lattner58f15c42008-10-17 16:21:11 +00004323 for (unsigned i = 0; i != NumRegs; ++i) {
4324 assert(Reg < Regs.size() && "Mismatch in # registers expected");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004325 Ops.push_back(DAG.getRegister(Regs[Reg++], RegisterVT));
Chris Lattner58f15c42008-10-17 16:21:11 +00004326 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004327 }
4328}
4329
4330/// isAllocatableRegister - If the specified register is safe to allocate,
4331/// i.e. it isn't a stack pointer or some other special register, return the
4332/// register class for the register. Otherwise, return null.
4333static const TargetRegisterClass *
4334isAllocatableRegister(unsigned Reg, MachineFunction &MF,
4335 const TargetLowering &TLI,
4336 const TargetRegisterInfo *TRI) {
4337 MVT FoundVT = MVT::Other;
4338 const TargetRegisterClass *FoundRC = 0;
4339 for (TargetRegisterInfo::regclass_iterator RCI = TRI->regclass_begin(),
4340 E = TRI->regclass_end(); RCI != E; ++RCI) {
4341 MVT ThisVT = MVT::Other;
4342
4343 const TargetRegisterClass *RC = *RCI;
4344 // If none of the the value types for this register class are valid, we
4345 // can't use it. For example, 64-bit reg classes on 32-bit targets.
4346 for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
4347 I != E; ++I) {
4348 if (TLI.isTypeLegal(*I)) {
4349 // If we have already found this register in a different register class,
4350 // choose the one with the largest VT specified. For example, on
4351 // PowerPC, we favor f64 register classes over f32.
4352 if (FoundVT == MVT::Other || FoundVT.bitsLT(*I)) {
4353 ThisVT = *I;
4354 break;
4355 }
4356 }
4357 }
4358
4359 if (ThisVT == MVT::Other) continue;
4360
4361 // NOTE: This isn't ideal. In particular, this might allocate the
4362 // frame pointer in functions that need it (due to them not being taken
4363 // out of allocation, because a variable sized allocation hasn't been seen
4364 // yet). This is a slight code pessimization, but should still work.
4365 for (TargetRegisterClass::iterator I = RC->allocation_order_begin(MF),
4366 E = RC->allocation_order_end(MF); I != E; ++I)
4367 if (*I == Reg) {
4368 // We found a matching register class. Keep looking at others in case
4369 // we find one with larger registers that this physreg is also in.
4370 FoundRC = RC;
4371 FoundVT = ThisVT;
4372 break;
4373 }
4374 }
4375 return FoundRC;
4376}
4377
4378
4379namespace llvm {
4380/// AsmOperandInfo - This contains information for each constraint that we are
4381/// lowering.
Daniel Dunbarc0c3b9a2008-09-10 04:16:29 +00004382struct VISIBILITY_HIDDEN SDISelAsmOperandInfo :
4383 public TargetLowering::AsmOperandInfo {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004384 /// CallOperand - If this is the result output operand or a clobber
4385 /// this is null, otherwise it is the incoming operand to the CallInst.
4386 /// This gets modified as the asm is processed.
4387 SDValue CallOperand;
4388
4389 /// AssignedRegs - If this is a register or register class operand, this
4390 /// contains the set of register corresponding to the operand.
4391 RegsForValue AssignedRegs;
4392
4393 explicit SDISelAsmOperandInfo(const InlineAsm::ConstraintInfo &info)
4394 : TargetLowering::AsmOperandInfo(info), CallOperand(0,0) {
4395 }
4396
4397 /// MarkAllocatedRegs - Once AssignedRegs is set, mark the assigned registers
4398 /// busy in OutputRegs/InputRegs.
4399 void MarkAllocatedRegs(bool isOutReg, bool isInReg,
4400 std::set<unsigned> &OutputRegs,
4401 std::set<unsigned> &InputRegs,
4402 const TargetRegisterInfo &TRI) const {
4403 if (isOutReg) {
4404 for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i)
4405 MarkRegAndAliases(AssignedRegs.Regs[i], OutputRegs, TRI);
4406 }
4407 if (isInReg) {
4408 for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i)
4409 MarkRegAndAliases(AssignedRegs.Regs[i], InputRegs, TRI);
4410 }
4411 }
Chris Lattner81249c92008-10-17 17:05:25 +00004412
4413 /// getCallOperandValMVT - Return the MVT of the Value* that this operand
4414 /// corresponds to. If there is no Value* for this operand, it returns
4415 /// MVT::Other.
4416 MVT getCallOperandValMVT(const TargetLowering &TLI,
4417 const TargetData *TD) const {
4418 if (CallOperandVal == 0) return MVT::Other;
4419
4420 if (isa<BasicBlock>(CallOperandVal))
4421 return TLI.getPointerTy();
4422
4423 const llvm::Type *OpTy = CallOperandVal->getType();
4424
4425 // If this is an indirect operand, the operand is a pointer to the
4426 // accessed type.
4427 if (isIndirect)
4428 OpTy = cast<PointerType>(OpTy)->getElementType();
4429
4430 // If OpTy is not a single value, it may be a struct/union that we
4431 // can tile with integers.
4432 if (!OpTy->isSingleValueType() && OpTy->isSized()) {
4433 unsigned BitSize = TD->getTypeSizeInBits(OpTy);
4434 switch (BitSize) {
4435 default: break;
4436 case 1:
4437 case 8:
4438 case 16:
4439 case 32:
4440 case 64:
Chris Lattnercfc14c12008-10-17 19:59:51 +00004441 case 128:
Chris Lattner81249c92008-10-17 17:05:25 +00004442 OpTy = IntegerType::get(BitSize);
4443 break;
4444 }
4445 }
4446
4447 return TLI.getValueType(OpTy, true);
4448 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004449
4450private:
4451 /// MarkRegAndAliases - Mark the specified register and all aliases in the
4452 /// specified set.
4453 static void MarkRegAndAliases(unsigned Reg, std::set<unsigned> &Regs,
4454 const TargetRegisterInfo &TRI) {
4455 assert(TargetRegisterInfo::isPhysicalRegister(Reg) && "Isn't a physreg");
4456 Regs.insert(Reg);
4457 if (const unsigned *Aliases = TRI.getAliasSet(Reg))
4458 for (; *Aliases; ++Aliases)
4459 Regs.insert(*Aliases);
4460 }
4461};
4462} // end llvm namespace.
4463
4464
4465/// GetRegistersForValue - Assign registers (virtual or physical) for the
4466/// specified operand. We prefer to assign virtual registers, to allow the
4467/// register allocator handle the assignment process. However, if the asm uses
4468/// features that we can't model on machineinstrs, we have SDISel do the
4469/// allocation. This produces generally horrible, but correct, code.
4470///
4471/// OpInfo describes the operand.
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004472/// Input and OutputRegs are the set of already allocated physical registers.
4473///
4474void SelectionDAGLowering::
Dale Johannesen8e3455b2008-09-24 23:13:09 +00004475GetRegistersForValue(SDISelAsmOperandInfo &OpInfo,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004476 std::set<unsigned> &OutputRegs,
4477 std::set<unsigned> &InputRegs) {
4478 // Compute whether this value requires an input register, an output register,
4479 // or both.
4480 bool isOutReg = false;
4481 bool isInReg = false;
4482 switch (OpInfo.Type) {
4483 case InlineAsm::isOutput:
4484 isOutReg = true;
4485
Dale Johannesen8e3455b2008-09-24 23:13:09 +00004486 // If there is an input constraint that matches this, we need to reserve
4487 // the input register so no other inputs allocate to it.
Chris Lattner6bdcda32008-10-17 16:47:46 +00004488 isInReg = OpInfo.hasMatchingInput();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004489 break;
4490 case InlineAsm::isInput:
4491 isInReg = true;
4492 isOutReg = false;
4493 break;
4494 case InlineAsm::isClobber:
4495 isOutReg = true;
4496 isInReg = true;
4497 break;
4498 }
4499
4500
4501 MachineFunction &MF = DAG.getMachineFunction();
4502 SmallVector<unsigned, 4> Regs;
4503
4504 // If this is a constraint for a single physreg, or a constraint for a
4505 // register class, find it.
4506 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
4507 TLI.getRegForInlineAsmConstraint(OpInfo.ConstraintCode,
4508 OpInfo.ConstraintVT);
4509
4510 unsigned NumRegs = 1;
Chris Lattner01426e12008-10-21 00:45:36 +00004511 if (OpInfo.ConstraintVT != MVT::Other) {
4512 // If this is a FP input in an integer register (or visa versa) insert a bit
4513 // cast of the input value. More generally, handle any case where the input
4514 // value disagrees with the register class we plan to stick this in.
4515 if (OpInfo.Type == InlineAsm::isInput &&
4516 PhysReg.second && !PhysReg.second->hasType(OpInfo.ConstraintVT)) {
4517 // Try to convert to the first MVT that the reg class contains. If the
4518 // types are identical size, use a bitcast to convert (e.g. two differing
4519 // vector types).
4520 MVT RegVT = *PhysReg.second->vt_begin();
4521 if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) {
4522 OpInfo.CallOperand = DAG.getNode(ISD::BIT_CONVERT, RegVT,
4523 OpInfo.CallOperand);
4524 OpInfo.ConstraintVT = RegVT;
4525 } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
4526 // If the input is a FP value and we want it in FP registers, do a
4527 // bitcast to the corresponding integer type. This turns an f64 value
4528 // into i64, which can be passed with two i32 values on a 32-bit
4529 // machine.
4530 RegVT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits());
4531 OpInfo.CallOperand = DAG.getNode(ISD::BIT_CONVERT, RegVT,
4532 OpInfo.CallOperand);
4533 OpInfo.ConstraintVT = RegVT;
4534 }
4535 }
4536
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004537 NumRegs = TLI.getNumRegisters(OpInfo.ConstraintVT);
Chris Lattner01426e12008-10-21 00:45:36 +00004538 }
4539
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004540 MVT RegVT;
4541 MVT ValueVT = OpInfo.ConstraintVT;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004542
4543 // If this is a constraint for a specific physical register, like {r17},
4544 // assign it now.
4545 if (PhysReg.first) {
4546 if (OpInfo.ConstraintVT == MVT::Other)
4547 ValueVT = *PhysReg.second->vt_begin();
4548
4549 // Get the actual register value type. This is important, because the user
4550 // may have asked for (e.g.) the AX register in i32 type. We need to
4551 // remember that AX is actually i16 to get the right extension.
4552 RegVT = *PhysReg.second->vt_begin();
4553
4554 // This is a explicit reference to a physical register.
4555 Regs.push_back(PhysReg.first);
4556
4557 // If this is an expanded reference, add the rest of the regs to Regs.
4558 if (NumRegs != 1) {
4559 TargetRegisterClass::iterator I = PhysReg.second->begin();
4560 for (; *I != PhysReg.first; ++I)
4561 assert(I != PhysReg.second->end() && "Didn't find reg!");
4562
4563 // Already added the first reg.
4564 --NumRegs; ++I;
4565 for (; NumRegs; --NumRegs, ++I) {
4566 assert(I != PhysReg.second->end() && "Ran out of registers to allocate!");
4567 Regs.push_back(*I);
4568 }
4569 }
4570 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, RegVT, ValueVT);
4571 const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
4572 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TRI);
4573 return;
4574 }
4575
4576 // Otherwise, if this was a reference to an LLVM register class, create vregs
4577 // for this reference.
4578 std::vector<unsigned> RegClassRegs;
4579 const TargetRegisterClass *RC = PhysReg.second;
4580 if (RC) {
Dale Johannesen8e3455b2008-09-24 23:13:09 +00004581 // If this is a tied register, our regalloc doesn't know how to maintain
Chris Lattner58f15c42008-10-17 16:21:11 +00004582 // the constraint, so we have to pick a register to pin the input/output to.
4583 // If it isn't a matched constraint, go ahead and create vreg and let the
4584 // regalloc do its thing.
Chris Lattner6bdcda32008-10-17 16:47:46 +00004585 if (!OpInfo.hasMatchingInput()) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004586 RegVT = *PhysReg.second->vt_begin();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004587 if (OpInfo.ConstraintVT == MVT::Other)
4588 ValueVT = RegVT;
4589
4590 // Create the appropriate number of virtual registers.
4591 MachineRegisterInfo &RegInfo = MF.getRegInfo();
4592 for (; NumRegs; --NumRegs)
4593 Regs.push_back(RegInfo.createVirtualRegister(PhysReg.second));
4594
4595 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, RegVT, ValueVT);
4596 return;
4597 }
4598
4599 // Otherwise, we can't allocate it. Let the code below figure out how to
4600 // maintain these constraints.
4601 RegClassRegs.assign(PhysReg.second->begin(), PhysReg.second->end());
4602
4603 } else {
4604 // This is a reference to a register class that doesn't directly correspond
4605 // to an LLVM register class. Allocate NumRegs consecutive, available,
4606 // registers from the class.
4607 RegClassRegs = TLI.getRegClassForInlineAsmConstraint(OpInfo.ConstraintCode,
4608 OpInfo.ConstraintVT);
4609 }
4610
4611 const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
4612 unsigned NumAllocated = 0;
4613 for (unsigned i = 0, e = RegClassRegs.size(); i != e; ++i) {
4614 unsigned Reg = RegClassRegs[i];
4615 // See if this register is available.
4616 if ((isOutReg && OutputRegs.count(Reg)) || // Already used.
4617 (isInReg && InputRegs.count(Reg))) { // Already used.
4618 // Make sure we find consecutive registers.
4619 NumAllocated = 0;
4620 continue;
4621 }
4622
4623 // Check to see if this register is allocatable (i.e. don't give out the
4624 // stack pointer).
4625 if (RC == 0) {
4626 RC = isAllocatableRegister(Reg, MF, TLI, TRI);
4627 if (!RC) { // Couldn't allocate this register.
4628 // Reset NumAllocated to make sure we return consecutive registers.
4629 NumAllocated = 0;
4630 continue;
4631 }
4632 }
4633
4634 // Okay, this register is good, we can use it.
4635 ++NumAllocated;
4636
4637 // If we allocated enough consecutive registers, succeed.
4638 if (NumAllocated == NumRegs) {
4639 unsigned RegStart = (i-NumAllocated)+1;
4640 unsigned RegEnd = i+1;
4641 // Mark all of the allocated registers used.
4642 for (unsigned i = RegStart; i != RegEnd; ++i)
4643 Regs.push_back(RegClassRegs[i]);
4644
4645 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, *RC->vt_begin(),
4646 OpInfo.ConstraintVT);
4647 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TRI);
4648 return;
4649 }
4650 }
4651
4652 // Otherwise, we couldn't allocate enough registers for this.
4653}
4654
Evan Chengda43bcf2008-09-24 00:05:32 +00004655/// hasInlineAsmMemConstraint - Return true if the inline asm instruction being
4656/// processed uses a memory 'm' constraint.
4657static bool
4658hasInlineAsmMemConstraint(std::vector<InlineAsm::ConstraintInfo> &CInfos,
4659 TargetLowering &TLI) {
4660 for (unsigned i = 0, e = CInfos.size(); i != e; ++i) {
4661 InlineAsm::ConstraintInfo &CI = CInfos[i];
4662 for (unsigned j = 0, ee = CI.Codes.size(); j != ee; ++j) {
4663 TargetLowering::ConstraintType CType = TLI.getConstraintType(CI.Codes[j]);
4664 if (CType == TargetLowering::C_Memory)
4665 return true;
4666 }
4667 }
4668
4669 return false;
4670}
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004671
4672/// visitInlineAsm - Handle a call to an InlineAsm object.
4673///
4674void SelectionDAGLowering::visitInlineAsm(CallSite CS) {
4675 InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
4676
4677 /// ConstraintOperands - Information about all of the constraints.
4678 std::vector<SDISelAsmOperandInfo> ConstraintOperands;
4679
4680 SDValue Chain = getRoot();
4681 SDValue Flag;
4682
4683 std::set<unsigned> OutputRegs, InputRegs;
4684
4685 // Do a prepass over the constraints, canonicalizing them, and building up the
4686 // ConstraintOperands list.
4687 std::vector<InlineAsm::ConstraintInfo>
4688 ConstraintInfos = IA->ParseConstraints();
4689
Evan Chengda43bcf2008-09-24 00:05:32 +00004690 bool hasMemory = hasInlineAsmMemConstraint(ConstraintInfos, TLI);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004691
4692 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst.
4693 unsigned ResNo = 0; // ResNo - The result number of the next output.
4694 for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) {
4695 ConstraintOperands.push_back(SDISelAsmOperandInfo(ConstraintInfos[i]));
4696 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
4697
4698 MVT OpVT = MVT::Other;
4699
4700 // Compute the value type for each operand.
4701 switch (OpInfo.Type) {
4702 case InlineAsm::isOutput:
4703 // Indirect outputs just consume an argument.
4704 if (OpInfo.isIndirect) {
4705 OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
4706 break;
4707 }
Chris Lattner2a0b96c2008-10-18 18:49:30 +00004708
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004709 // The return value of the call is this value. As such, there is no
4710 // corresponding argument.
4711 assert(CS.getType() != Type::VoidTy && "Bad inline asm!");
4712 if (const StructType *STy = dyn_cast<StructType>(CS.getType())) {
4713 OpVT = TLI.getValueType(STy->getElementType(ResNo));
4714 } else {
4715 assert(ResNo == 0 && "Asm only has one result!");
4716 OpVT = TLI.getValueType(CS.getType());
4717 }
4718 ++ResNo;
4719 break;
4720 case InlineAsm::isInput:
4721 OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
4722 break;
4723 case InlineAsm::isClobber:
4724 // Nothing to do.
4725 break;
4726 }
4727
4728 // If this is an input or an indirect output, process the call argument.
4729 // BasicBlocks are labels, currently appearing only in asm's.
4730 if (OpInfo.CallOperandVal) {
Chris Lattner81249c92008-10-17 17:05:25 +00004731 if (BasicBlock *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004732 OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
Chris Lattner81249c92008-10-17 17:05:25 +00004733 } else {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004734 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004735 }
Chris Lattner81249c92008-10-17 17:05:25 +00004736
4737 OpVT = OpInfo.getCallOperandValMVT(TLI, TD);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004738 }
4739
4740 OpInfo.ConstraintVT = OpVT;
Chris Lattner2a0b96c2008-10-18 18:49:30 +00004741 }
4742
4743 // Second pass over the constraints: compute which constraint option to use
4744 // and assign registers to constraints that want a specific physreg.
4745 for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) {
4746 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
4747
4748 // If this is an output operand with a matching input operand, look up the
4749 // matching input. It might have a different type (e.g. the output might be
4750 // i32 and the input i64) and we need to pick the larger width to ensure we
4751 // reserve the right number of registers.
4752 if (OpInfo.hasMatchingInput()) {
4753 SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
4754 if (OpInfo.ConstraintVT != Input.ConstraintVT) {
4755 assert(OpInfo.ConstraintVT.isInteger() &&
4756 Input.ConstraintVT.isInteger() &&
4757 "Asm constraints must be the same or different sized integers");
4758 if (OpInfo.ConstraintVT.getSizeInBits() <
4759 Input.ConstraintVT.getSizeInBits())
4760 OpInfo.ConstraintVT = Input.ConstraintVT;
4761 else
4762 Input.ConstraintVT = OpInfo.ConstraintVT;
4763 }
4764 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004765
4766 // Compute the constraint code and ConstraintType to use.
Evan Chengda43bcf2008-09-24 00:05:32 +00004767 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, hasMemory, &DAG);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004768
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004769 // If this is a memory input, and if the operand is not indirect, do what we
4770 // need to to provide an address for the memory input.
4771 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
4772 !OpInfo.isIndirect) {
4773 assert(OpInfo.Type == InlineAsm::isInput &&
4774 "Can only indirectify direct input operands!");
4775
4776 // Memory operands really want the address of the value. If we don't have
4777 // an indirect input, put it in the constpool if we can, otherwise spill
4778 // it to a stack slot.
4779
4780 // If the operand is a float, integer, or vector constant, spill to a
4781 // constant pool entry to get its address.
4782 Value *OpVal = OpInfo.CallOperandVal;
4783 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
4784 isa<ConstantVector>(OpVal)) {
4785 OpInfo.CallOperand = DAG.getConstantPool(cast<Constant>(OpVal),
4786 TLI.getPointerTy());
4787 } else {
4788 // Otherwise, create a stack slot and emit a store to it before the
4789 // asm.
4790 const Type *Ty = OpVal->getType();
4791 uint64_t TySize = TLI.getTargetData()->getABITypeSize(Ty);
4792 unsigned Align = TLI.getTargetData()->getPrefTypeAlignment(Ty);
4793 MachineFunction &MF = DAG.getMachineFunction();
4794 int SSFI = MF.getFrameInfo()->CreateStackObject(TySize, Align);
4795 SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getPointerTy());
4796 Chain = DAG.getStore(Chain, OpInfo.CallOperand, StackSlot, NULL, 0);
4797 OpInfo.CallOperand = StackSlot;
4798 }
4799
4800 // There is no longer a Value* corresponding to this operand.
4801 OpInfo.CallOperandVal = 0;
4802 // It is now an indirect operand.
4803 OpInfo.isIndirect = true;
4804 }
4805
4806 // If this constraint is for a specific register, allocate it before
4807 // anything else.
4808 if (OpInfo.ConstraintType == TargetLowering::C_Register)
Dale Johannesen8e3455b2008-09-24 23:13:09 +00004809 GetRegistersForValue(OpInfo, OutputRegs, InputRegs);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004810 }
4811 ConstraintInfos.clear();
4812
4813
4814 // Second pass - Loop over all of the operands, assigning virtual or physregs
Chris Lattner58f15c42008-10-17 16:21:11 +00004815 // to register class operands.
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004816 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
4817 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
4818
4819 // C_Register operands have already been allocated, Other/Memory don't need
4820 // to be.
4821 if (OpInfo.ConstraintType == TargetLowering::C_RegisterClass)
Dale Johannesen8e3455b2008-09-24 23:13:09 +00004822 GetRegistersForValue(OpInfo, OutputRegs, InputRegs);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004823 }
4824
4825 // AsmNodeOperands - The operands for the ISD::INLINEASM node.
4826 std::vector<SDValue> AsmNodeOperands;
4827 AsmNodeOperands.push_back(SDValue()); // reserve space for input chain
4828 AsmNodeOperands.push_back(
Bill Wendling056292f2008-09-16 21:48:12 +00004829 DAG.getTargetExternalSymbol(IA->getAsmString().c_str(), MVT::Other));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004830
4831
4832 // Loop over all of the inputs, copying the operand values into the
4833 // appropriate registers and processing the output regs.
4834 RegsForValue RetValRegs;
4835
4836 // IndirectStoresToEmit - The set of stores to emit after the inline asm node.
4837 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
4838
4839 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
4840 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
4841
4842 switch (OpInfo.Type) {
4843 case InlineAsm::isOutput: {
4844 if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass &&
4845 OpInfo.ConstraintType != TargetLowering::C_Register) {
4846 // Memory output, or 'other' output (e.g. 'X' constraint).
4847 assert(OpInfo.isIndirect && "Memory output must be indirect operand");
4848
4849 // Add information to the INLINEASM node to know about this output.
Dale Johannesen86b49f82008-09-24 01:07:17 +00004850 unsigned ResOpType = 4/*MEM*/ | (1<<3);
4851 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004852 TLI.getPointerTy()));
4853 AsmNodeOperands.push_back(OpInfo.CallOperand);
4854 break;
4855 }
4856
4857 // Otherwise, this is a register or register class output.
4858
4859 // Copy the output from the appropriate register. Find a register that
4860 // we can use.
4861 if (OpInfo.AssignedRegs.Regs.empty()) {
4862 cerr << "Couldn't allocate output reg for constraint '"
4863 << OpInfo.ConstraintCode << "'!\n";
4864 exit(1);
4865 }
4866
4867 // If this is an indirect operand, store through the pointer after the
4868 // asm.
4869 if (OpInfo.isIndirect) {
4870 IndirectStoresToEmit.push_back(std::make_pair(OpInfo.AssignedRegs,
4871 OpInfo.CallOperandVal));
4872 } else {
4873 // This is the result value of the call.
4874 assert(CS.getType() != Type::VoidTy && "Bad inline asm!");
4875 // Concatenate this output onto the outputs list.
4876 RetValRegs.append(OpInfo.AssignedRegs);
4877 }
4878
4879 // Add information to the INLINEASM node to know that this register is
4880 // set.
Dale Johannesen913d3df2008-09-12 17:49:03 +00004881 OpInfo.AssignedRegs.AddInlineAsmOperands(OpInfo.isEarlyClobber ?
4882 6 /* EARLYCLOBBER REGDEF */ :
4883 2 /* REGDEF */ ,
4884 DAG, AsmNodeOperands);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004885 break;
4886 }
4887 case InlineAsm::isInput: {
4888 SDValue InOperandVal = OpInfo.CallOperand;
4889
Chris Lattner6bdcda32008-10-17 16:47:46 +00004890 if (OpInfo.isMatchingInputConstraint()) { // Matching constraint?
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004891 // If this is required to match an output register we have already set,
4892 // just use its register.
Chris Lattner58f15c42008-10-17 16:21:11 +00004893 unsigned OperandNo = OpInfo.getMatchedOperand();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004894
4895 // Scan until we find the definition we already emitted of this operand.
4896 // When we find it, create a RegsForValue operand.
4897 unsigned CurOp = 2; // The first operand.
4898 for (; OperandNo; --OperandNo) {
4899 // Advance to the next operand.
4900 unsigned NumOps =
Dan Gohmanf5aeb1a2008-09-12 16:56:44 +00004901 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004902 assert(((NumOps & 7) == 2 /*REGDEF*/ ||
Dale Johannesen913d3df2008-09-12 17:49:03 +00004903 (NumOps & 7) == 6 /*EARLYCLOBBER REGDEF*/ ||
Dale Johannesen86b49f82008-09-24 01:07:17 +00004904 (NumOps & 7) == 4 /*MEM*/) &&
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004905 "Skipped past definitions?");
4906 CurOp += (NumOps>>3)+1;
4907 }
4908
4909 unsigned NumOps =
Dan Gohmanf5aeb1a2008-09-12 16:56:44 +00004910 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
Dale Johannesen913d3df2008-09-12 17:49:03 +00004911 if ((NumOps & 7) == 2 /*REGDEF*/
4912 || (NumOps & 7) == 6 /* EARLYCLOBBER REGDEF */) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004913 // Add NumOps>>3 registers to MatchedRegs.
4914 RegsForValue MatchedRegs;
4915 MatchedRegs.TLI = &TLI;
4916 MatchedRegs.ValueVTs.push_back(InOperandVal.getValueType());
4917 MatchedRegs.RegVTs.push_back(AsmNodeOperands[CurOp+1].getValueType());
4918 for (unsigned i = 0, e = NumOps>>3; i != e; ++i) {
4919 unsigned Reg =
4920 cast<RegisterSDNode>(AsmNodeOperands[++CurOp])->getReg();
4921 MatchedRegs.Regs.push_back(Reg);
4922 }
4923
4924 // Use the produced MatchedRegs object to
4925 MatchedRegs.getCopyToRegs(InOperandVal, DAG, Chain, &Flag);
Dale Johannesen86b49f82008-09-24 01:07:17 +00004926 MatchedRegs.AddInlineAsmOperands(1 /*REGUSE*/, DAG, AsmNodeOperands);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004927 break;
4928 } else {
Dale Johannesen86b49f82008-09-24 01:07:17 +00004929 assert(((NumOps & 7) == 4) && "Unknown matching constraint!");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004930 assert((NumOps >> 3) == 1 && "Unexpected number of operands");
4931 // Add information to the INLINEASM node to know about this input.
Dale Johannesen91aac102008-09-17 21:13:11 +00004932 AsmNodeOperands.push_back(DAG.getTargetConstant(NumOps,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004933 TLI.getPointerTy()));
4934 AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
4935 break;
4936 }
4937 }
4938
4939 if (OpInfo.ConstraintType == TargetLowering::C_Other) {
4940 assert(!OpInfo.isIndirect &&
4941 "Don't know how to handle indirect other inputs yet!");
4942
4943 std::vector<SDValue> Ops;
4944 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode[0],
Evan Chengda43bcf2008-09-24 00:05:32 +00004945 hasMemory, Ops, DAG);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004946 if (Ops.empty()) {
4947 cerr << "Invalid operand for inline asm constraint '"
4948 << OpInfo.ConstraintCode << "'!\n";
4949 exit(1);
4950 }
4951
4952 // Add information to the INLINEASM node to know about this input.
4953 unsigned ResOpType = 3 /*IMM*/ | (Ops.size() << 3);
4954 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
4955 TLI.getPointerTy()));
4956 AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end());
4957 break;
4958 } else if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
4959 assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
4960 assert(InOperandVal.getValueType() == TLI.getPointerTy() &&
4961 "Memory operands expect pointer values");
4962
4963 // Add information to the INLINEASM node to know about this input.
Dale Johannesen86b49f82008-09-24 01:07:17 +00004964 unsigned ResOpType = 4/*MEM*/ | (1<<3);
4965 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004966 TLI.getPointerTy()));
4967 AsmNodeOperands.push_back(InOperandVal);
4968 break;
4969 }
4970
4971 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
4972 OpInfo.ConstraintType == TargetLowering::C_Register) &&
4973 "Unknown constraint type!");
4974 assert(!OpInfo.isIndirect &&
4975 "Don't know how to handle indirect register inputs yet!");
4976
4977 // Copy the input into the appropriate registers.
Evan Chengaa765b82008-09-25 00:14:04 +00004978 if (OpInfo.AssignedRegs.Regs.empty()) {
4979 cerr << "Couldn't allocate output reg for constraint '"
4980 << OpInfo.ConstraintCode << "'!\n";
4981 exit(1);
4982 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004983
4984 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, Chain, &Flag);
4985
Dale Johannesen86b49f82008-09-24 01:07:17 +00004986 OpInfo.AssignedRegs.AddInlineAsmOperands(1/*REGUSE*/,
4987 DAG, AsmNodeOperands);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004988 break;
4989 }
4990 case InlineAsm::isClobber: {
4991 // Add the clobbered value to the operand list, so that the register
4992 // allocator is aware that the physreg got clobbered.
4993 if (!OpInfo.AssignedRegs.Regs.empty())
Dale Johannesen91aac102008-09-17 21:13:11 +00004994 OpInfo.AssignedRegs.AddInlineAsmOperands(6 /* EARLYCLOBBER REGDEF */,
4995 DAG, AsmNodeOperands);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004996 break;
4997 }
4998 }
4999 }
5000
5001 // Finish up input operands.
5002 AsmNodeOperands[0] = Chain;
5003 if (Flag.getNode()) AsmNodeOperands.push_back(Flag);
5004
5005 Chain = DAG.getNode(ISD::INLINEASM,
5006 DAG.getNodeValueTypes(MVT::Other, MVT::Flag), 2,
5007 &AsmNodeOperands[0], AsmNodeOperands.size());
5008 Flag = Chain.getValue(1);
5009
5010 // If this asm returns a register value, copy the result from that register
5011 // and set it as the value of the call.
5012 if (!RetValRegs.Regs.empty()) {
5013 SDValue Val = RetValRegs.getCopyFromRegs(DAG, Chain, &Flag);
Chris Lattner2a0b96c2008-10-18 18:49:30 +00005014
5015 // FIXME: Why don't we do this for inline asms with MRVs?
5016 if (CS.getType()->isSingleValueType() && CS.getType()->isSized()) {
5017 MVT ResultType = TLI.getValueType(CS.getType());
5018
5019 // If any of the results of the inline asm is a vector, it may have the
5020 // wrong width/num elts. This can happen for register classes that can
5021 // contain multiple different value types. The preg or vreg allocated may
5022 // not have the same VT as was expected. Convert it to the right type
5023 // with bit_convert.
5024 if (ResultType != Val.getValueType() && Val.getValueType().isVector()) {
5025 Val = DAG.getNode(ISD::BIT_CONVERT, ResultType, Val);
Dan Gohman95915732008-10-18 01:03:45 +00005026
Chris Lattner2a0b96c2008-10-18 18:49:30 +00005027 } else if (ResultType != Val.getValueType() &&
5028 ResultType.isInteger() && Val.getValueType().isInteger()) {
5029 // If a result value was tied to an input value, the computed result may
5030 // have a wider width than the expected result. Extract the relevant
5031 // portion.
5032 Val = DAG.getNode(ISD::TRUNCATE, ResultType, Val);
Dan Gohman95915732008-10-18 01:03:45 +00005033 }
Chris Lattner2a0b96c2008-10-18 18:49:30 +00005034
5035 assert(ResultType == Val.getValueType() && "Asm result value mismatch!");
Chris Lattner0c526442008-10-17 17:52:49 +00005036 }
Dan Gohman95915732008-10-18 01:03:45 +00005037
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005038 setValue(CS.getInstruction(), Val);
5039 }
5040
5041 std::vector<std::pair<SDValue, Value*> > StoresToEmit;
5042
5043 // Process indirect outputs, first output all of the flagged copies out of
5044 // physregs.
5045 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
5046 RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
5047 Value *Ptr = IndirectStoresToEmit[i].second;
5048 SDValue OutVal = OutRegs.getCopyFromRegs(DAG, Chain, &Flag);
5049 StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
5050 }
5051
5052 // Emit the non-flagged stores from the physregs.
5053 SmallVector<SDValue, 8> OutChains;
5054 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i)
5055 OutChains.push_back(DAG.getStore(Chain, StoresToEmit[i].first,
5056 getValue(StoresToEmit[i].second),
5057 StoresToEmit[i].second, 0));
5058 if (!OutChains.empty())
5059 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
5060 &OutChains[0], OutChains.size());
5061 DAG.setRoot(Chain);
5062}
5063
5064
5065void SelectionDAGLowering::visitMalloc(MallocInst &I) {
5066 SDValue Src = getValue(I.getOperand(0));
5067
5068 MVT IntPtr = TLI.getPointerTy();
5069
5070 if (IntPtr.bitsLT(Src.getValueType()))
5071 Src = DAG.getNode(ISD::TRUNCATE, IntPtr, Src);
5072 else if (IntPtr.bitsGT(Src.getValueType()))
5073 Src = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, Src);
5074
5075 // Scale the source by the type size.
5076 uint64_t ElementSize = TD->getABITypeSize(I.getType()->getElementType());
5077 Src = DAG.getNode(ISD::MUL, Src.getValueType(),
5078 Src, DAG.getIntPtrConstant(ElementSize));
5079
5080 TargetLowering::ArgListTy Args;
5081 TargetLowering::ArgListEntry Entry;
5082 Entry.Node = Src;
5083 Entry.Ty = TLI.getTargetData()->getIntPtrType();
5084 Args.push_back(Entry);
5085
5086 std::pair<SDValue,SDValue> Result =
Dale Johannesen86098bd2008-09-26 19:31:26 +00005087 TLI.LowerCallTo(getRoot(), I.getType(), false, false, false, false,
5088 CallingConv::C, PerformTailCallOpt,
5089 DAG.getExternalSymbol("malloc", IntPtr),
Dan Gohman1937e2f2008-09-16 01:42:28 +00005090 Args, DAG);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005091 setValue(&I, Result.first); // Pointers always fit in registers
5092 DAG.setRoot(Result.second);
5093}
5094
5095void SelectionDAGLowering::visitFree(FreeInst &I) {
5096 TargetLowering::ArgListTy Args;
5097 TargetLowering::ArgListEntry Entry;
5098 Entry.Node = getValue(I.getOperand(0));
5099 Entry.Ty = TLI.getTargetData()->getIntPtrType();
5100 Args.push_back(Entry);
5101 MVT IntPtr = TLI.getPointerTy();
5102 std::pair<SDValue,SDValue> Result =
Dale Johannesen86098bd2008-09-26 19:31:26 +00005103 TLI.LowerCallTo(getRoot(), Type::VoidTy, false, false, false, false,
Dan Gohman1937e2f2008-09-16 01:42:28 +00005104 CallingConv::C, PerformTailCallOpt,
Bill Wendling056292f2008-09-16 21:48:12 +00005105 DAG.getExternalSymbol("free", IntPtr), Args, DAG);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005106 DAG.setRoot(Result.second);
5107}
5108
5109void SelectionDAGLowering::visitVAStart(CallInst &I) {
5110 DAG.setRoot(DAG.getNode(ISD::VASTART, MVT::Other, getRoot(),
5111 getValue(I.getOperand(1)),
5112 DAG.getSrcValue(I.getOperand(1))));
5113}
5114
5115void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
5116 SDValue V = DAG.getVAArg(TLI.getValueType(I.getType()), getRoot(),
5117 getValue(I.getOperand(0)),
5118 DAG.getSrcValue(I.getOperand(0)));
5119 setValue(&I, V);
5120 DAG.setRoot(V.getValue(1));
5121}
5122
5123void SelectionDAGLowering::visitVAEnd(CallInst &I) {
5124 DAG.setRoot(DAG.getNode(ISD::VAEND, MVT::Other, getRoot(),
5125 getValue(I.getOperand(1)),
5126 DAG.getSrcValue(I.getOperand(1))));
5127}
5128
5129void SelectionDAGLowering::visitVACopy(CallInst &I) {
5130 DAG.setRoot(DAG.getNode(ISD::VACOPY, MVT::Other, getRoot(),
5131 getValue(I.getOperand(1)),
5132 getValue(I.getOperand(2)),
5133 DAG.getSrcValue(I.getOperand(1)),
5134 DAG.getSrcValue(I.getOperand(2))));
5135}
5136
5137/// TargetLowering::LowerArguments - This is the default LowerArguments
5138/// implementation, which just inserts a FORMAL_ARGUMENTS node. FIXME: When all
5139/// targets are migrated to using FORMAL_ARGUMENTS, this hook should be
5140/// integrated into SDISel.
5141void TargetLowering::LowerArguments(Function &F, SelectionDAG &DAG,
5142 SmallVectorImpl<SDValue> &ArgValues) {
5143 // Add CC# and isVararg as operands to the FORMAL_ARGUMENTS node.
5144 SmallVector<SDValue, 3+16> Ops;
5145 Ops.push_back(DAG.getRoot());
5146 Ops.push_back(DAG.getConstant(F.getCallingConv(), getPointerTy()));
5147 Ops.push_back(DAG.getConstant(F.isVarArg(), getPointerTy()));
5148
5149 // Add one result value for each formal argument.
5150 SmallVector<MVT, 16> RetVals;
5151 unsigned j = 1;
5152 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end();
5153 I != E; ++I, ++j) {
5154 SmallVector<MVT, 4> ValueVTs;
5155 ComputeValueVTs(*this, I->getType(), ValueVTs);
5156 for (unsigned Value = 0, NumValues = ValueVTs.size();
5157 Value != NumValues; ++Value) {
5158 MVT VT = ValueVTs[Value];
5159 const Type *ArgTy = VT.getTypeForMVT();
5160 ISD::ArgFlagsTy Flags;
5161 unsigned OriginalAlignment =
5162 getTargetData()->getABITypeAlignment(ArgTy);
5163
Devang Patel05988662008-09-25 21:00:45 +00005164 if (F.paramHasAttr(j, Attribute::ZExt))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005165 Flags.setZExt();
Devang Patel05988662008-09-25 21:00:45 +00005166 if (F.paramHasAttr(j, Attribute::SExt))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005167 Flags.setSExt();
Devang Patel05988662008-09-25 21:00:45 +00005168 if (F.paramHasAttr(j, Attribute::InReg))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005169 Flags.setInReg();
Devang Patel05988662008-09-25 21:00:45 +00005170 if (F.paramHasAttr(j, Attribute::StructRet))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005171 Flags.setSRet();
Devang Patel05988662008-09-25 21:00:45 +00005172 if (F.paramHasAttr(j, Attribute::ByVal)) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005173 Flags.setByVal();
5174 const PointerType *Ty = cast<PointerType>(I->getType());
5175 const Type *ElementTy = Ty->getElementType();
5176 unsigned FrameAlign = getByValTypeAlignment(ElementTy);
5177 unsigned FrameSize = getTargetData()->getABITypeSize(ElementTy);
5178 // For ByVal, alignment should be passed from FE. BE will guess if
5179 // this info is not there but there are cases it cannot get right.
5180 if (F.getParamAlignment(j))
5181 FrameAlign = F.getParamAlignment(j);
5182 Flags.setByValAlign(FrameAlign);
5183 Flags.setByValSize(FrameSize);
5184 }
Devang Patel05988662008-09-25 21:00:45 +00005185 if (F.paramHasAttr(j, Attribute::Nest))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005186 Flags.setNest();
5187 Flags.setOrigAlign(OriginalAlignment);
5188
5189 MVT RegisterVT = getRegisterType(VT);
5190 unsigned NumRegs = getNumRegisters(VT);
5191 for (unsigned i = 0; i != NumRegs; ++i) {
5192 RetVals.push_back(RegisterVT);
5193 ISD::ArgFlagsTy MyFlags = Flags;
5194 if (NumRegs > 1 && i == 0)
5195 MyFlags.setSplit();
5196 // if it isn't first piece, alignment must be 1
5197 else if (i > 0)
5198 MyFlags.setOrigAlign(1);
5199 Ops.push_back(DAG.getArgFlags(MyFlags));
5200 }
5201 }
5202 }
5203
5204 RetVals.push_back(MVT::Other);
5205
5206 // Create the node.
5207 SDNode *Result = DAG.getNode(ISD::FORMAL_ARGUMENTS,
5208 DAG.getVTList(&RetVals[0], RetVals.size()),
5209 &Ops[0], Ops.size()).getNode();
5210
5211 // Prelower FORMAL_ARGUMENTS. This isn't required for functionality, but
5212 // allows exposing the loads that may be part of the argument access to the
5213 // first DAGCombiner pass.
5214 SDValue TmpRes = LowerOperation(SDValue(Result, 0), DAG);
5215
5216 // The number of results should match up, except that the lowered one may have
5217 // an extra flag result.
5218 assert((Result->getNumValues() == TmpRes.getNode()->getNumValues() ||
5219 (Result->getNumValues()+1 == TmpRes.getNode()->getNumValues() &&
5220 TmpRes.getValue(Result->getNumValues()).getValueType() == MVT::Flag))
5221 && "Lowering produced unexpected number of results!");
5222
5223 // The FORMAL_ARGUMENTS node itself is likely no longer needed.
5224 if (Result != TmpRes.getNode() && Result->use_empty()) {
5225 HandleSDNode Dummy(DAG.getRoot());
5226 DAG.RemoveDeadNode(Result);
5227 }
5228
5229 Result = TmpRes.getNode();
5230
5231 unsigned NumArgRegs = Result->getNumValues() - 1;
5232 DAG.setRoot(SDValue(Result, NumArgRegs));
5233
5234 // Set up the return result vector.
5235 unsigned i = 0;
5236 unsigned Idx = 1;
5237 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E;
5238 ++I, ++Idx) {
5239 SmallVector<MVT, 4> ValueVTs;
5240 ComputeValueVTs(*this, I->getType(), ValueVTs);
5241 for (unsigned Value = 0, NumValues = ValueVTs.size();
5242 Value != NumValues; ++Value) {
5243 MVT VT = ValueVTs[Value];
5244 MVT PartVT = getRegisterType(VT);
5245
5246 unsigned NumParts = getNumRegisters(VT);
5247 SmallVector<SDValue, 4> Parts(NumParts);
5248 for (unsigned j = 0; j != NumParts; ++j)
5249 Parts[j] = SDValue(Result, i++);
5250
5251 ISD::NodeType AssertOp = ISD::DELETED_NODE;
Devang Patel05988662008-09-25 21:00:45 +00005252 if (F.paramHasAttr(Idx, Attribute::SExt))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005253 AssertOp = ISD::AssertSext;
Devang Patel05988662008-09-25 21:00:45 +00005254 else if (F.paramHasAttr(Idx, Attribute::ZExt))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005255 AssertOp = ISD::AssertZext;
5256
5257 ArgValues.push_back(getCopyFromParts(DAG, &Parts[0], NumParts, PartVT, VT,
5258 AssertOp));
5259 }
5260 }
5261 assert(i == NumArgRegs && "Argument register count mismatch!");
5262}
5263
5264
5265/// TargetLowering::LowerCallTo - This is the default LowerCallTo
5266/// implementation, which just inserts an ISD::CALL node, which is later custom
5267/// lowered by the target to something concrete. FIXME: When all targets are
5268/// migrated to using ISD::CALL, this hook should be integrated into SDISel.
5269std::pair<SDValue, SDValue>
5270TargetLowering::LowerCallTo(SDValue Chain, const Type *RetTy,
5271 bool RetSExt, bool RetZExt, bool isVarArg,
Dale Johannesen86098bd2008-09-26 19:31:26 +00005272 bool isInreg,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005273 unsigned CallingConv, bool isTailCall,
5274 SDValue Callee,
5275 ArgListTy &Args, SelectionDAG &DAG) {
Dan Gohman1937e2f2008-09-16 01:42:28 +00005276 assert((!isTailCall || PerformTailCallOpt) &&
5277 "isTailCall set when tail-call optimizations are disabled!");
5278
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005279 SmallVector<SDValue, 32> Ops;
5280 Ops.push_back(Chain); // Op#0 - Chain
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005281 Ops.push_back(Callee);
5282
5283 // Handle all of the outgoing arguments.
5284 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
5285 SmallVector<MVT, 4> ValueVTs;
5286 ComputeValueVTs(*this, Args[i].Ty, ValueVTs);
5287 for (unsigned Value = 0, NumValues = ValueVTs.size();
5288 Value != NumValues; ++Value) {
5289 MVT VT = ValueVTs[Value];
5290 const Type *ArgTy = VT.getTypeForMVT();
Chris Lattner2a0b96c2008-10-18 18:49:30 +00005291 SDValue Op = SDValue(Args[i].Node.getNode(),
5292 Args[i].Node.getResNo() + Value);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005293 ISD::ArgFlagsTy Flags;
5294 unsigned OriginalAlignment =
5295 getTargetData()->getABITypeAlignment(ArgTy);
5296
5297 if (Args[i].isZExt)
5298 Flags.setZExt();
5299 if (Args[i].isSExt)
5300 Flags.setSExt();
5301 if (Args[i].isInReg)
5302 Flags.setInReg();
5303 if (Args[i].isSRet)
5304 Flags.setSRet();
5305 if (Args[i].isByVal) {
5306 Flags.setByVal();
5307 const PointerType *Ty = cast<PointerType>(Args[i].Ty);
5308 const Type *ElementTy = Ty->getElementType();
5309 unsigned FrameAlign = getByValTypeAlignment(ElementTy);
5310 unsigned FrameSize = getTargetData()->getABITypeSize(ElementTy);
5311 // For ByVal, alignment should come from FE. BE will guess if this
5312 // info is not there but there are cases it cannot get right.
5313 if (Args[i].Alignment)
5314 FrameAlign = Args[i].Alignment;
5315 Flags.setByValAlign(FrameAlign);
5316 Flags.setByValSize(FrameSize);
5317 }
5318 if (Args[i].isNest)
5319 Flags.setNest();
5320 Flags.setOrigAlign(OriginalAlignment);
5321
5322 MVT PartVT = getRegisterType(VT);
5323 unsigned NumParts = getNumRegisters(VT);
5324 SmallVector<SDValue, 4> Parts(NumParts);
5325 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
5326
5327 if (Args[i].isSExt)
5328 ExtendKind = ISD::SIGN_EXTEND;
5329 else if (Args[i].isZExt)
5330 ExtendKind = ISD::ZERO_EXTEND;
5331
5332 getCopyToParts(DAG, Op, &Parts[0], NumParts, PartVT, ExtendKind);
5333
5334 for (unsigned i = 0; i != NumParts; ++i) {
5335 // if it isn't first piece, alignment must be 1
5336 ISD::ArgFlagsTy MyFlags = Flags;
5337 if (NumParts > 1 && i == 0)
5338 MyFlags.setSplit();
5339 else if (i != 0)
5340 MyFlags.setOrigAlign(1);
5341
5342 Ops.push_back(Parts[i]);
5343 Ops.push_back(DAG.getArgFlags(MyFlags));
5344 }
5345 }
5346 }
5347
5348 // Figure out the result value types. We start by making a list of
5349 // the potentially illegal return value types.
5350 SmallVector<MVT, 4> LoweredRetTys;
5351 SmallVector<MVT, 4> RetTys;
5352 ComputeValueVTs(*this, RetTy, RetTys);
5353
5354 // Then we translate that to a list of legal types.
5355 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
5356 MVT VT = RetTys[I];
5357 MVT RegisterVT = getRegisterType(VT);
5358 unsigned NumRegs = getNumRegisters(VT);
5359 for (unsigned i = 0; i != NumRegs; ++i)
5360 LoweredRetTys.push_back(RegisterVT);
5361 }
5362
5363 LoweredRetTys.push_back(MVT::Other); // Always has a chain.
5364
5365 // Create the CALL node.
Dale Johannesen86098bd2008-09-26 19:31:26 +00005366 SDValue Res = DAG.getCall(CallingConv, isVarArg, isTailCall, isInreg,
Dan Gohman095cc292008-09-13 01:54:27 +00005367 DAG.getVTList(&LoweredRetTys[0],
5368 LoweredRetTys.size()),
Dale Johannesen86098bd2008-09-26 19:31:26 +00005369 &Ops[0], Ops.size()
5370 );
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005371 Chain = Res.getValue(LoweredRetTys.size() - 1);
5372
5373 // Gather up the call result into a single value.
Dan Gohmanb5cc34d2008-10-07 00:12:37 +00005374 if (RetTy != Type::VoidTy && !RetTys.empty()) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005375 ISD::NodeType AssertOp = ISD::DELETED_NODE;
5376
5377 if (RetSExt)
5378 AssertOp = ISD::AssertSext;
5379 else if (RetZExt)
5380 AssertOp = ISD::AssertZext;
5381
5382 SmallVector<SDValue, 4> ReturnValues;
5383 unsigned RegNo = 0;
5384 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
5385 MVT VT = RetTys[I];
5386 MVT RegisterVT = getRegisterType(VT);
5387 unsigned NumRegs = getNumRegisters(VT);
5388 unsigned RegNoEnd = NumRegs + RegNo;
5389 SmallVector<SDValue, 4> Results;
5390 for (; RegNo != RegNoEnd; ++RegNo)
5391 Results.push_back(Res.getValue(RegNo));
5392 SDValue ReturnValue =
5393 getCopyFromParts(DAG, &Results[0], NumRegs, RegisterVT, VT,
5394 AssertOp);
5395 ReturnValues.push_back(ReturnValue);
5396 }
5397 Res = DAG.getMergeValues(DAG.getVTList(&RetTys[0], RetTys.size()),
5398 &ReturnValues[0], ReturnValues.size());
5399 }
5400
5401 return std::make_pair(Res, Chain);
5402}
5403
5404SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) {
5405 assert(0 && "LowerOperation not implemented for this target!");
5406 abort();
5407 return SDValue();
5408}
5409
5410
5411void SelectionDAGLowering::CopyValueToVirtualRegister(Value *V, unsigned Reg) {
5412 SDValue Op = getValue(V);
5413 assert((Op.getOpcode() != ISD::CopyFromReg ||
5414 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
5415 "Copy from a reg to the same reg!");
5416 assert(!TargetRegisterInfo::isPhysicalRegister(Reg) && "Is a physreg");
5417
5418 RegsForValue RFV(TLI, Reg, V->getType());
5419 SDValue Chain = DAG.getEntryNode();
5420 RFV.getCopyToRegs(Op, DAG, Chain, 0);
5421 PendingExports.push_back(Chain);
5422}
5423
5424#include "llvm/CodeGen/SelectionDAGISel.h"
5425
5426void SelectionDAGISel::
5427LowerArguments(BasicBlock *LLVMBB) {
5428 // If this is the entry block, emit arguments.
5429 Function &F = *LLVMBB->getParent();
5430 SDValue OldRoot = SDL->DAG.getRoot();
5431 SmallVector<SDValue, 16> Args;
5432 TLI.LowerArguments(F, SDL->DAG, Args);
5433
5434 unsigned a = 0;
5435 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
5436 AI != E; ++AI) {
5437 SmallVector<MVT, 4> ValueVTs;
5438 ComputeValueVTs(TLI, AI->getType(), ValueVTs);
5439 unsigned NumValues = ValueVTs.size();
5440 if (!AI->use_empty()) {
5441 SDL->setValue(AI, SDL->DAG.getMergeValues(&Args[a], NumValues));
5442 // If this argument is live outside of the entry block, insert a copy from
5443 // whereever we got it to the vreg that other BB's will reference it as.
5444 DenseMap<const Value*, unsigned>::iterator VMI=FuncInfo->ValueMap.find(AI);
5445 if (VMI != FuncInfo->ValueMap.end()) {
5446 SDL->CopyValueToVirtualRegister(AI, VMI->second);
5447 }
5448 }
5449 a += NumValues;
5450 }
5451
5452 // Finally, if the target has anything special to do, allow it to do so.
5453 // FIXME: this should insert code into the DAG!
5454 EmitFunctionEntryCode(F, SDL->DAG.getMachineFunction());
5455}
5456
5457/// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
5458/// ensure constants are generated when needed. Remember the virtual registers
5459/// that need to be added to the Machine PHI nodes as input. We cannot just
5460/// directly add them, because expansion might result in multiple MBB's for one
5461/// BB. As such, the start of the BB might correspond to a different MBB than
5462/// the end.
5463///
5464void
5465SelectionDAGISel::HandlePHINodesInSuccessorBlocks(BasicBlock *LLVMBB) {
5466 TerminatorInst *TI = LLVMBB->getTerminator();
5467
5468 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
5469
5470 // Check successor nodes' PHI nodes that expect a constant to be available
5471 // from this block.
5472 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
5473 BasicBlock *SuccBB = TI->getSuccessor(succ);
5474 if (!isa<PHINode>(SuccBB->begin())) continue;
5475 MachineBasicBlock *SuccMBB = FuncInfo->MBBMap[SuccBB];
5476
5477 // If this terminator has multiple identical successors (common for
5478 // switches), only handle each succ once.
5479 if (!SuccsHandled.insert(SuccMBB)) continue;
5480
5481 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
5482 PHINode *PN;
5483
5484 // At this point we know that there is a 1-1 correspondence between LLVM PHI
5485 // nodes and Machine PHI nodes, but the incoming operands have not been
5486 // emitted yet.
5487 for (BasicBlock::iterator I = SuccBB->begin();
5488 (PN = dyn_cast<PHINode>(I)); ++I) {
5489 // Ignore dead phi's.
5490 if (PN->use_empty()) continue;
5491
5492 unsigned Reg;
5493 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
5494
5495 if (Constant *C = dyn_cast<Constant>(PHIOp)) {
5496 unsigned &RegOut = SDL->ConstantsOut[C];
5497 if (RegOut == 0) {
5498 RegOut = FuncInfo->CreateRegForValue(C);
5499 SDL->CopyValueToVirtualRegister(C, RegOut);
5500 }
5501 Reg = RegOut;
5502 } else {
5503 Reg = FuncInfo->ValueMap[PHIOp];
5504 if (Reg == 0) {
5505 assert(isa<AllocaInst>(PHIOp) &&
5506 FuncInfo->StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
5507 "Didn't codegen value into a register!??");
5508 Reg = FuncInfo->CreateRegForValue(PHIOp);
5509 SDL->CopyValueToVirtualRegister(PHIOp, Reg);
5510 }
5511 }
5512
5513 // Remember that this register needs to added to the machine PHI node as
5514 // the input for this MBB.
5515 SmallVector<MVT, 4> ValueVTs;
5516 ComputeValueVTs(TLI, PN->getType(), ValueVTs);
5517 for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
5518 MVT VT = ValueVTs[vti];
5519 unsigned NumRegisters = TLI.getNumRegisters(VT);
5520 for (unsigned i = 0, e = NumRegisters; i != e; ++i)
5521 SDL->PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
5522 Reg += NumRegisters;
5523 }
5524 }
5525 }
5526 SDL->ConstantsOut.clear();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005527}
5528
Dan Gohman3df24e62008-09-03 23:12:08 +00005529/// This is the Fast-ISel version of HandlePHINodesInSuccessorBlocks. It only
5530/// supports legal types, and it emits MachineInstrs directly instead of
5531/// creating SelectionDAG nodes.
5532///
5533bool
5534SelectionDAGISel::HandlePHINodesInSuccessorBlocksFast(BasicBlock *LLVMBB,
5535 FastISel *F) {
5536 TerminatorInst *TI = LLVMBB->getTerminator();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005537
Dan Gohman3df24e62008-09-03 23:12:08 +00005538 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
5539 unsigned OrigNumPHINodesToUpdate = SDL->PHINodesToUpdate.size();
5540
5541 // Check successor nodes' PHI nodes that expect a constant to be available
5542 // from this block.
5543 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
5544 BasicBlock *SuccBB = TI->getSuccessor(succ);
5545 if (!isa<PHINode>(SuccBB->begin())) continue;
5546 MachineBasicBlock *SuccMBB = FuncInfo->MBBMap[SuccBB];
5547
5548 // If this terminator has multiple identical successors (common for
5549 // switches), only handle each succ once.
5550 if (!SuccsHandled.insert(SuccMBB)) continue;
5551
5552 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
5553 PHINode *PN;
5554
5555 // At this point we know that there is a 1-1 correspondence between LLVM PHI
5556 // nodes and Machine PHI nodes, but the incoming operands have not been
5557 // emitted yet.
5558 for (BasicBlock::iterator I = SuccBB->begin();
5559 (PN = dyn_cast<PHINode>(I)); ++I) {
5560 // Ignore dead phi's.
5561 if (PN->use_empty()) continue;
5562
5563 // Only handle legal types. Two interesting things to note here. First,
5564 // by bailing out early, we may leave behind some dead instructions,
5565 // since SelectionDAG's HandlePHINodesInSuccessorBlocks will insert its
5566 // own moves. Second, this check is necessary becuase FastISel doesn't
5567 // use CreateRegForValue to create registers, so it always creates
5568 // exactly one register for each non-void instruction.
5569 MVT VT = TLI.getValueType(PN->getType(), /*AllowUnknown=*/true);
5570 if (VT == MVT::Other || !TLI.isTypeLegal(VT)) {
Dan Gohman74321ab2008-09-10 21:01:31 +00005571 // Promote MVT::i1.
5572 if (VT == MVT::i1)
5573 VT = TLI.getTypeToTransformTo(VT);
5574 else {
5575 SDL->PHINodesToUpdate.resize(OrigNumPHINodesToUpdate);
5576 return false;
5577 }
Dan Gohman3df24e62008-09-03 23:12:08 +00005578 }
5579
5580 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
5581
5582 unsigned Reg = F->getRegForValue(PHIOp);
5583 if (Reg == 0) {
5584 SDL->PHINodesToUpdate.resize(OrigNumPHINodesToUpdate);
5585 return false;
5586 }
5587 SDL->PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg));
5588 }
5589 }
5590
5591 return true;
5592}