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