blob: 49b7ad80a28faf3bd2b41a8852813d6fa4ebc6af [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"
Bill Wendlingb2a42982008-11-06 02:29:10 +000028#include "llvm/Module.h"
Dan Gohmanf0cbcd42008-09-03 16:12:24 +000029#include "llvm/CodeGen/FastISel.h"
30#include "llvm/CodeGen/GCStrategy.h"
31#include "llvm/CodeGen/GCMetadata.h"
32#include "llvm/CodeGen/MachineFunction.h"
33#include "llvm/CodeGen/MachineFrameInfo.h"
34#include "llvm/CodeGen/MachineInstrBuilder.h"
35#include "llvm/CodeGen/MachineJumpTableInfo.h"
36#include "llvm/CodeGen/MachineModuleInfo.h"
37#include "llvm/CodeGen/MachineRegisterInfo.h"
Bill Wendlingb2a42982008-11-06 02:29:10 +000038#include "llvm/CodeGen/PseudoSourceValue.h"
Dan Gohmanf0cbcd42008-09-03 16:12:24 +000039#include "llvm/CodeGen/SelectionDAG.h"
Devang Patel83489bb2009-01-13 00:35:13 +000040#include "llvm/CodeGen/DwarfWriter.h"
41#include "llvm/Analysis/DebugInfo.h"
Dan Gohmanf0cbcd42008-09-03 16:12:24 +000042#include "llvm/Target/TargetRegisterInfo.h"
43#include "llvm/Target/TargetData.h"
44#include "llvm/Target/TargetFrameInfo.h"
45#include "llvm/Target/TargetInstrInfo.h"
46#include "llvm/Target/TargetLowering.h"
47#include "llvm/Target/TargetMachine.h"
48#include "llvm/Target/TargetOptions.h"
49#include "llvm/Support/Compiler.h"
50#include "llvm/Support/Debug.h"
51#include "llvm/Support/MathExtras.h"
Anton Korobeynikov56d245b2008-12-23 22:26:18 +000052#include "llvm/Support/raw_ostream.h"
Dan Gohmanf0cbcd42008-09-03 16:12:24 +000053#include <algorithm>
54using namespace llvm;
55
Dale Johannesen601d3c02008-09-05 01:48:15 +000056/// LimitFloatPrecision - Generate low-precision inline sequences for
57/// some float libcalls (6, 8 or 12 bits).
58static unsigned LimitFloatPrecision;
59
60static cl::opt<unsigned, true>
61LimitFPPrecision("limit-float-precision",
62 cl::desc("Generate low-precision inline sequences "
63 "for some float libcalls"),
64 cl::location(LimitFloatPrecision),
65 cl::init(0));
66
Dan Gohmanf0cbcd42008-09-03 16:12:24 +000067/// ComputeLinearIndex - Given an LLVM IR aggregate type and a sequence
Dan Gohman2c91d102009-01-06 22:53:52 +000068/// of insertvalue or extractvalue indices that identify a member, return
Dan Gohmanf0cbcd42008-09-03 16:12:24 +000069/// the linearized index of the start of the member.
70///
71static unsigned ComputeLinearIndex(const TargetLowering &TLI, const Type *Ty,
72 const unsigned *Indices,
73 const unsigned *IndicesEnd,
74 unsigned CurIndex = 0) {
75 // Base case: We're done.
76 if (Indices && Indices == IndicesEnd)
77 return CurIndex;
78
79 // Given a struct type, recursively traverse the elements.
80 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
81 for (StructType::element_iterator EB = STy->element_begin(),
82 EI = EB,
83 EE = STy->element_end();
84 EI != EE; ++EI) {
85 if (Indices && *Indices == unsigned(EI - EB))
86 return ComputeLinearIndex(TLI, *EI, Indices+1, IndicesEnd, CurIndex);
87 CurIndex = ComputeLinearIndex(TLI, *EI, 0, 0, CurIndex);
88 }
Dan Gohman2c91d102009-01-06 22:53:52 +000089 return CurIndex;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +000090 }
91 // Given an array type, recursively traverse the elements.
92 else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
93 const Type *EltTy = ATy->getElementType();
94 for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i) {
95 if (Indices && *Indices == i)
96 return ComputeLinearIndex(TLI, EltTy, Indices+1, IndicesEnd, CurIndex);
97 CurIndex = ComputeLinearIndex(TLI, EltTy, 0, 0, CurIndex);
98 }
Dan Gohman2c91d102009-01-06 22:53:52 +000099 return CurIndex;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000100 }
101 // We haven't found the type we're looking for, so keep searching.
102 return CurIndex + 1;
103}
104
105/// ComputeValueVTs - Given an LLVM IR type, compute a sequence of
106/// MVTs that represent all the individual underlying
107/// non-aggregate types that comprise it.
108///
109/// If Offsets is non-null, it points to a vector to be filled in
110/// with the in-memory offsets of each of the individual values.
111///
112static void ComputeValueVTs(const TargetLowering &TLI, const Type *Ty,
113 SmallVectorImpl<MVT> &ValueVTs,
114 SmallVectorImpl<uint64_t> *Offsets = 0,
115 uint64_t StartingOffset = 0) {
116 // Given a struct type, recursively traverse the elements.
117 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
118 const StructLayout *SL = TLI.getTargetData()->getStructLayout(STy);
119 for (StructType::element_iterator EB = STy->element_begin(),
120 EI = EB,
121 EE = STy->element_end();
122 EI != EE; ++EI)
123 ComputeValueVTs(TLI, *EI, ValueVTs, Offsets,
124 StartingOffset + SL->getElementOffset(EI - EB));
125 return;
126 }
127 // Given an array type, recursively traverse the elements.
128 if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
129 const Type *EltTy = ATy->getElementType();
Duncan Sandsceb4d1a2009-01-12 20:38:59 +0000130 uint64_t EltSize = TLI.getTargetData()->getTypePaddedSize(EltTy);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000131 for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i)
132 ComputeValueVTs(TLI, EltTy, ValueVTs, Offsets,
133 StartingOffset + i * EltSize);
134 return;
135 }
136 // Base case: we can get an MVT for this LLVM IR type.
137 ValueVTs.push_back(TLI.getValueType(Ty));
138 if (Offsets)
139 Offsets->push_back(StartingOffset);
140}
141
Dan Gohman2a7c6712008-09-03 23:18:39 +0000142namespace llvm {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000143 /// RegsForValue - This struct represents the registers (physical or virtual)
144 /// that a particular set of values is assigned, and the type information about
145 /// the value. The most common situation is to represent one value at a time,
146 /// but struct or array values are handled element-wise as multiple values.
147 /// The splitting of aggregates is performed recursively, so that we never
148 /// have aggregate-typed registers. The values at this point do not necessarily
149 /// have legal types, so each value may require one or more registers of some
150 /// legal type.
151 ///
152 struct VISIBILITY_HIDDEN RegsForValue {
153 /// TLI - The TargetLowering object.
154 ///
155 const TargetLowering *TLI;
156
157 /// ValueVTs - The value types of the values, which may not be legal, and
158 /// may need be promoted or synthesized from one or more registers.
159 ///
160 SmallVector<MVT, 4> ValueVTs;
161
162 /// RegVTs - The value types of the registers. This is the same size as
163 /// ValueVTs and it records, for each value, what the type of the assigned
164 /// register or registers are. (Individual values are never synthesized
165 /// from more than one type of register.)
166 ///
167 /// With virtual registers, the contents of RegVTs is redundant with TLI's
168 /// getRegisterType member function, however when with physical registers
169 /// it is necessary to have a separate record of the types.
170 ///
171 SmallVector<MVT, 4> RegVTs;
172
173 /// Regs - This list holds the registers assigned to the values.
174 /// Each legal or promoted value requires one register, and each
175 /// expanded value requires multiple registers.
176 ///
177 SmallVector<unsigned, 4> Regs;
178
179 RegsForValue() : TLI(0) {}
180
181 RegsForValue(const TargetLowering &tli,
182 const SmallVector<unsigned, 4> &regs,
183 MVT regvt, MVT valuevt)
184 : TLI(&tli), ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs) {}
185 RegsForValue(const TargetLowering &tli,
186 const SmallVector<unsigned, 4> &regs,
187 const SmallVector<MVT, 4> &regvts,
188 const SmallVector<MVT, 4> &valuevts)
189 : TLI(&tli), ValueVTs(valuevts), RegVTs(regvts), Regs(regs) {}
190 RegsForValue(const TargetLowering &tli,
191 unsigned Reg, const Type *Ty) : TLI(&tli) {
192 ComputeValueVTs(tli, Ty, ValueVTs);
193
194 for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
195 MVT ValueVT = ValueVTs[Value];
196 unsigned NumRegs = TLI->getNumRegisters(ValueVT);
197 MVT RegisterVT = TLI->getRegisterType(ValueVT);
198 for (unsigned i = 0; i != NumRegs; ++i)
199 Regs.push_back(Reg + i);
200 RegVTs.push_back(RegisterVT);
201 Reg += NumRegs;
202 }
203 }
204
205 /// append - Add the specified values to this one.
206 void append(const RegsForValue &RHS) {
207 TLI = RHS.TLI;
208 ValueVTs.append(RHS.ValueVTs.begin(), RHS.ValueVTs.end());
209 RegVTs.append(RHS.RegVTs.begin(), RHS.RegVTs.end());
210 Regs.append(RHS.Regs.begin(), RHS.Regs.end());
211 }
212
213
214 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
215 /// this value and returns the result as a ValueVTs value. 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 SDValue getCopyFromRegs(SelectionDAG &DAG,
219 SDValue &Chain, SDValue *Flag) const;
220
221 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
222 /// specified value into the registers specified by this object. This uses
223 /// Chain/Flag as the input and updates them for the output Chain/Flag.
224 /// If the Flag pointer is NULL, no flag is used.
225 void getCopyToRegs(SDValue Val, SelectionDAG &DAG,
226 SDValue &Chain, SDValue *Flag) const;
227
228 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
229 /// operand list. This adds the code marker and includes the number of
230 /// values added into it.
231 void AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
232 std::vector<SDValue> &Ops) const;
233 };
234}
235
236/// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by
237/// PHI nodes or outside of the basic block that defines it, or used by a
238/// switch or atomic instruction, which may expand to multiple basic blocks.
239static bool isUsedOutsideOfDefiningBlock(Instruction *I) {
240 if (isa<PHINode>(I)) return true;
241 BasicBlock *BB = I->getParent();
242 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; ++UI)
243 if (cast<Instruction>(*UI)->getParent() != BB || isa<PHINode>(*UI) ||
244 // FIXME: Remove switchinst special case.
245 isa<SwitchInst>(*UI))
246 return true;
247 return false;
248}
249
250/// isOnlyUsedInEntryBlock - If the specified argument is only used in the
251/// entry block, return true. This includes arguments used by switches, since
252/// the switch may expand into multiple basic blocks.
253static bool isOnlyUsedInEntryBlock(Argument *A, bool EnableFastISel) {
254 // With FastISel active, we may be splitting blocks, so force creation
255 // of virtual registers for all non-dead arguments.
Dan Gohman33134c42008-09-25 17:05:24 +0000256 // Don't force virtual registers for byval arguments though, because
257 // fast-isel can't handle those in all cases.
258 if (EnableFastISel && !A->hasByValAttr())
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000259 return A->use_empty();
260
261 BasicBlock *Entry = A->getParent()->begin();
262 for (Value::use_iterator UI = A->use_begin(), E = A->use_end(); UI != E; ++UI)
263 if (cast<Instruction>(*UI)->getParent() != Entry || isa<SwitchInst>(*UI))
264 return false; // Use not in entry block.
265 return true;
266}
267
268FunctionLoweringInfo::FunctionLoweringInfo(TargetLowering &tli)
269 : TLI(tli) {
270}
271
272void FunctionLoweringInfo::set(Function &fn, MachineFunction &mf,
273 bool EnableFastISel) {
274 Fn = &fn;
275 MF = &mf;
276 RegInfo = &MF->getRegInfo();
277
278 // Create a vreg for each argument register that is not dead and is used
279 // outside of the entry block for the function.
280 for (Function::arg_iterator AI = Fn->arg_begin(), E = Fn->arg_end();
281 AI != E; ++AI)
282 if (!isOnlyUsedInEntryBlock(AI, EnableFastISel))
283 InitializeRegForValue(AI);
284
285 // Initialize the mapping of values to registers. This is only set up for
286 // instruction values that are used outside of the block that defines
287 // them.
288 Function::iterator BB = Fn->begin(), EB = Fn->end();
289 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
290 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
291 if (ConstantInt *CUI = dyn_cast<ConstantInt>(AI->getArraySize())) {
292 const Type *Ty = AI->getAllocatedType();
Duncan Sandsceb4d1a2009-01-12 20:38:59 +0000293 uint64_t TySize = TLI.getTargetData()->getTypePaddedSize(Ty);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000294 unsigned Align =
295 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
296 AI->getAlignment());
297
298 TySize *= CUI->getZExtValue(); // Get total allocated size.
299 if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
300 StaticAllocaMap[AI] =
301 MF->getFrameInfo()->CreateStackObject(TySize, Align);
302 }
303
304 for (; BB != EB; ++BB)
305 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
306 if (!I->use_empty() && isUsedOutsideOfDefiningBlock(I))
307 if (!isa<AllocaInst>(I) ||
308 !StaticAllocaMap.count(cast<AllocaInst>(I)))
309 InitializeRegForValue(I);
310
311 // Create an initial MachineBasicBlock for each LLVM BasicBlock in F. This
312 // also creates the initial PHI MachineInstrs, though none of the input
313 // operands are populated.
314 for (BB = Fn->begin(), EB = Fn->end(); BB != EB; ++BB) {
315 MachineBasicBlock *MBB = mf.CreateMachineBasicBlock(BB);
316 MBBMap[BB] = MBB;
317 MF->push_back(MBB);
318
319 // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
320 // appropriate.
321 PHINode *PN;
322 for (BasicBlock::iterator I = BB->begin();(PN = dyn_cast<PHINode>(I)); ++I){
323 if (PN->use_empty()) continue;
324
325 unsigned PHIReg = ValueMap[PN];
326 assert(PHIReg && "PHI node does not have an assigned virtual register!");
327
328 SmallVector<MVT, 4> ValueVTs;
329 ComputeValueVTs(TLI, PN->getType(), ValueVTs);
330 for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
331 MVT VT = ValueVTs[vti];
332 unsigned NumRegisters = TLI.getNumRegisters(VT);
Dan Gohman6448d912008-09-04 15:39:15 +0000333 const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000334 for (unsigned i = 0; i != NumRegisters; ++i)
335 BuildMI(MBB, TII->get(TargetInstrInfo::PHI), PHIReg+i);
336 PHIReg += NumRegisters;
337 }
338 }
339 }
340}
341
342unsigned FunctionLoweringInfo::MakeReg(MVT VT) {
343 return RegInfo->createVirtualRegister(TLI.getRegClassFor(VT));
344}
345
346/// CreateRegForValue - Allocate the appropriate number of virtual registers of
347/// the correctly promoted or expanded types. Assign these registers
348/// consecutive vreg numbers and return the first assigned number.
349///
350/// In the case that the given value has struct or array type, this function
351/// will assign registers for each member or element.
352///
353unsigned FunctionLoweringInfo::CreateRegForValue(const Value *V) {
354 SmallVector<MVT, 4> ValueVTs;
355 ComputeValueVTs(TLI, V->getType(), ValueVTs);
356
357 unsigned FirstReg = 0;
358 for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
359 MVT ValueVT = ValueVTs[Value];
360 MVT RegisterVT = TLI.getRegisterType(ValueVT);
361
362 unsigned NumRegs = TLI.getNumRegisters(ValueVT);
363 for (unsigned i = 0; i != NumRegs; ++i) {
364 unsigned R = MakeReg(RegisterVT);
365 if (!FirstReg) FirstReg = R;
366 }
367 }
368 return FirstReg;
369}
370
371/// getCopyFromParts - Create a value that contains the specified legal parts
372/// combined into the value they represent. If the parts combine to a type
373/// larger then ValueVT then AssertOp can be used to specify whether the extra
374/// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
375/// (ISD::AssertSext).
376static SDValue getCopyFromParts(SelectionDAG &DAG,
377 const SDValue *Parts,
378 unsigned NumParts,
379 MVT PartVT,
380 MVT ValueVT,
381 ISD::NodeType AssertOp = ISD::DELETED_NODE) {
382 assert(NumParts > 0 && "No parts to assemble!");
Dan Gohmane9530ec2009-01-15 16:58:17 +0000383 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000384 SDValue Val = Parts[0];
385
386 if (NumParts > 1) {
387 // Assemble the value from multiple parts.
388 if (!ValueVT.isVector()) {
389 unsigned PartBits = PartVT.getSizeInBits();
390 unsigned ValueBits = ValueVT.getSizeInBits();
391
392 // Assemble the power of 2 part.
393 unsigned RoundParts = NumParts & (NumParts - 1) ?
394 1 << Log2_32(NumParts) : NumParts;
395 unsigned RoundBits = PartBits * RoundParts;
396 MVT RoundVT = RoundBits == ValueBits ?
397 ValueVT : MVT::getIntegerVT(RoundBits);
398 SDValue Lo, Hi;
399
Duncan Sandsd22ec5f2008-10-29 14:22:20 +0000400 MVT HalfVT = ValueVT.isInteger() ?
401 MVT::getIntegerVT(RoundBits/2) :
402 MVT::getFloatingPointVT(RoundBits/2);
403
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000404 if (RoundParts > 2) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000405 Lo = getCopyFromParts(DAG, Parts, RoundParts/2, PartVT, HalfVT);
406 Hi = getCopyFromParts(DAG, Parts+RoundParts/2, RoundParts/2,
407 PartVT, HalfVT);
408 } else {
Duncan Sandsd22ec5f2008-10-29 14:22:20 +0000409 Lo = DAG.getNode(ISD::BIT_CONVERT, HalfVT, Parts[0]);
410 Hi = DAG.getNode(ISD::BIT_CONVERT, HalfVT, Parts[1]);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000411 }
412 if (TLI.isBigEndian())
413 std::swap(Lo, Hi);
414 Val = DAG.getNode(ISD::BUILD_PAIR, RoundVT, Lo, Hi);
415
416 if (RoundParts < NumParts) {
417 // Assemble the trailing non-power-of-2 part.
418 unsigned OddParts = NumParts - RoundParts;
419 MVT OddVT = MVT::getIntegerVT(OddParts * PartBits);
420 Hi = getCopyFromParts(DAG, Parts+RoundParts, OddParts, PartVT, OddVT);
421
422 // Combine the round and odd parts.
423 Lo = Val;
424 if (TLI.isBigEndian())
425 std::swap(Lo, Hi);
426 MVT TotalVT = MVT::getIntegerVT(NumParts * PartBits);
427 Hi = DAG.getNode(ISD::ANY_EXTEND, TotalVT, Hi);
428 Hi = DAG.getNode(ISD::SHL, TotalVT, Hi,
429 DAG.getConstant(Lo.getValueType().getSizeInBits(),
430 TLI.getShiftAmountTy()));
431 Lo = DAG.getNode(ISD::ZERO_EXTEND, TotalVT, Lo);
432 Val = DAG.getNode(ISD::OR, TotalVT, Lo, Hi);
433 }
434 } else {
435 // Handle a multi-element vector.
436 MVT IntermediateVT, RegisterVT;
437 unsigned NumIntermediates;
438 unsigned NumRegs =
439 TLI.getVectorTypeBreakdown(ValueVT, IntermediateVT, NumIntermediates,
440 RegisterVT);
441 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
442 NumParts = NumRegs; // Silence a compiler warning.
443 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
444 assert(RegisterVT == Parts[0].getValueType() &&
445 "Part type doesn't match part!");
446
447 // Assemble the parts into intermediate operands.
448 SmallVector<SDValue, 8> Ops(NumIntermediates);
449 if (NumIntermediates == NumParts) {
450 // If the register was not expanded, truncate or copy the value,
451 // as appropriate.
452 for (unsigned i = 0; i != NumParts; ++i)
453 Ops[i] = getCopyFromParts(DAG, &Parts[i], 1,
454 PartVT, IntermediateVT);
455 } else if (NumParts > 0) {
456 // If the intermediate type was expanded, build the intermediate operands
457 // from the parts.
458 assert(NumParts % NumIntermediates == 0 &&
459 "Must expand into a divisible number of parts!");
460 unsigned Factor = NumParts / NumIntermediates;
461 for (unsigned i = 0; i != NumIntermediates; ++i)
462 Ops[i] = getCopyFromParts(DAG, &Parts[i * Factor], Factor,
463 PartVT, IntermediateVT);
464 }
465
466 // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the intermediate
467 // operands.
468 Val = DAG.getNode(IntermediateVT.isVector() ?
469 ISD::CONCAT_VECTORS : ISD::BUILD_VECTOR,
470 ValueVT, &Ops[0], NumIntermediates);
471 }
472 }
473
474 // There is now one part, held in Val. Correct it to match ValueVT.
475 PartVT = Val.getValueType();
476
477 if (PartVT == ValueVT)
478 return Val;
479
480 if (PartVT.isVector()) {
481 assert(ValueVT.isVector() && "Unknown vector conversion!");
482 return DAG.getNode(ISD::BIT_CONVERT, ValueVT, Val);
483 }
484
485 if (ValueVT.isVector()) {
486 assert(ValueVT.getVectorElementType() == PartVT &&
487 ValueVT.getVectorNumElements() == 1 &&
488 "Only trivial scalar-to-vector conversions should get here!");
489 return DAG.getNode(ISD::BUILD_VECTOR, ValueVT, Val);
490 }
491
492 if (PartVT.isInteger() &&
493 ValueVT.isInteger()) {
494 if (ValueVT.bitsLT(PartVT)) {
495 // For a truncate, see if we have any information to
496 // indicate whether the truncated bits will always be
497 // zero or sign-extension.
498 if (AssertOp != ISD::DELETED_NODE)
499 Val = DAG.getNode(AssertOp, PartVT, Val,
500 DAG.getValueType(ValueVT));
501 return DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
502 } else {
503 return DAG.getNode(ISD::ANY_EXTEND, ValueVT, Val);
504 }
505 }
506
507 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
508 if (ValueVT.bitsLT(Val.getValueType()))
509 // FP_ROUND's are always exact here.
510 return DAG.getNode(ISD::FP_ROUND, ValueVT, Val,
511 DAG.getIntPtrConstant(1));
512 return DAG.getNode(ISD::FP_EXTEND, ValueVT, Val);
513 }
514
515 if (PartVT.getSizeInBits() == ValueVT.getSizeInBits())
516 return DAG.getNode(ISD::BIT_CONVERT, ValueVT, Val);
517
518 assert(0 && "Unknown mismatch!");
519 return SDValue();
520}
521
522/// getCopyToParts - Create a series of nodes that contain the specified value
523/// split into legal parts. If the parts contain more bits than Val, then, for
524/// integers, ExtendKind can be used to specify how to generate the extra bits.
Chris Lattner01426e12008-10-21 00:45:36 +0000525static void getCopyToParts(SelectionDAG &DAG, SDValue Val,
526 SDValue *Parts, unsigned NumParts, MVT PartVT,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000527 ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
Dan Gohmane9530ec2009-01-15 16:58:17 +0000528 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000529 MVT PtrVT = TLI.getPointerTy();
530 MVT ValueVT = Val.getValueType();
531 unsigned PartBits = PartVT.getSizeInBits();
532 assert(TLI.isTypeLegal(PartVT) && "Copying to an illegal type!");
533
534 if (!NumParts)
535 return;
536
537 if (!ValueVT.isVector()) {
538 if (PartVT == ValueVT) {
539 assert(NumParts == 1 && "No-op copy with multiple parts!");
540 Parts[0] = Val;
541 return;
542 }
543
544 if (NumParts * PartBits > ValueVT.getSizeInBits()) {
545 // If the parts cover more bits than the value has, promote the value.
546 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
547 assert(NumParts == 1 && "Do not know what to promote to!");
548 Val = DAG.getNode(ISD::FP_EXTEND, PartVT, Val);
549 } else if (PartVT.isInteger() && ValueVT.isInteger()) {
550 ValueVT = MVT::getIntegerVT(NumParts * PartBits);
551 Val = DAG.getNode(ExtendKind, ValueVT, Val);
552 } else {
553 assert(0 && "Unknown mismatch!");
554 }
555 } else if (PartBits == ValueVT.getSizeInBits()) {
556 // Different types of the same size.
557 assert(NumParts == 1 && PartVT != ValueVT);
558 Val = DAG.getNode(ISD::BIT_CONVERT, PartVT, Val);
559 } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
560 // If the parts cover less bits than value has, truncate the value.
561 if (PartVT.isInteger() && ValueVT.isInteger()) {
562 ValueVT = MVT::getIntegerVT(NumParts * PartBits);
563 Val = DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
564 } else {
565 assert(0 && "Unknown mismatch!");
566 }
567 }
568
569 // The value may have changed - recompute ValueVT.
570 ValueVT = Val.getValueType();
571 assert(NumParts * PartBits == ValueVT.getSizeInBits() &&
572 "Failed to tile the value with PartVT!");
573
574 if (NumParts == 1) {
575 assert(PartVT == ValueVT && "Type conversion failed!");
576 Parts[0] = Val;
577 return;
578 }
579
580 // Expand the value into multiple parts.
581 if (NumParts & (NumParts - 1)) {
582 // The number of parts is not a power of 2. Split off and copy the tail.
583 assert(PartVT.isInteger() && ValueVT.isInteger() &&
584 "Do not know what to expand to!");
585 unsigned RoundParts = 1 << Log2_32(NumParts);
586 unsigned RoundBits = RoundParts * PartBits;
587 unsigned OddParts = NumParts - RoundParts;
588 SDValue OddVal = DAG.getNode(ISD::SRL, ValueVT, Val,
589 DAG.getConstant(RoundBits,
590 TLI.getShiftAmountTy()));
591 getCopyToParts(DAG, OddVal, Parts + RoundParts, OddParts, PartVT);
592 if (TLI.isBigEndian())
593 // The odd parts were reversed by getCopyToParts - unreverse them.
594 std::reverse(Parts + RoundParts, Parts + NumParts);
595 NumParts = RoundParts;
596 ValueVT = MVT::getIntegerVT(NumParts * PartBits);
597 Val = DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
598 }
599
600 // The number of parts is a power of 2. Repeatedly bisect the value using
601 // EXTRACT_ELEMENT.
602 Parts[0] = DAG.getNode(ISD::BIT_CONVERT,
603 MVT::getIntegerVT(ValueVT.getSizeInBits()),
604 Val);
605 for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
606 for (unsigned i = 0; i < NumParts; i += StepSize) {
607 unsigned ThisBits = StepSize * PartBits / 2;
608 MVT ThisVT = MVT::getIntegerVT (ThisBits);
609 SDValue &Part0 = Parts[i];
610 SDValue &Part1 = Parts[i+StepSize/2];
611
612 Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, ThisVT, Part0,
613 DAG.getConstant(1, PtrVT));
614 Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, ThisVT, Part0,
615 DAG.getConstant(0, PtrVT));
616
617 if (ThisBits == PartBits && ThisVT != PartVT) {
618 Part0 = DAG.getNode(ISD::BIT_CONVERT, PartVT, Part0);
619 Part1 = DAG.getNode(ISD::BIT_CONVERT, PartVT, Part1);
620 }
621 }
622 }
623
624 if (TLI.isBigEndian())
625 std::reverse(Parts, Parts + NumParts);
626
627 return;
628 }
629
630 // Vector ValueVT.
631 if (NumParts == 1) {
632 if (PartVT != ValueVT) {
633 if (PartVT.isVector()) {
634 Val = DAG.getNode(ISD::BIT_CONVERT, PartVT, Val);
635 } else {
636 assert(ValueVT.getVectorElementType() == PartVT &&
637 ValueVT.getVectorNumElements() == 1 &&
638 "Only trivial vector-to-scalar conversions should get here!");
639 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, PartVT, Val,
640 DAG.getConstant(0, PtrVT));
641 }
642 }
643
644 Parts[0] = Val;
645 return;
646 }
647
648 // Handle a multi-element vector.
649 MVT IntermediateVT, RegisterVT;
650 unsigned NumIntermediates;
Dan Gohmane9530ec2009-01-15 16:58:17 +0000651 unsigned NumRegs = TLI
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000652 .getVectorTypeBreakdown(ValueVT, IntermediateVT, NumIntermediates,
653 RegisterVT);
654 unsigned NumElements = ValueVT.getVectorNumElements();
655
656 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
657 NumParts = NumRegs; // Silence a compiler warning.
658 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
659
660 // Split the vector into intermediate operands.
661 SmallVector<SDValue, 8> Ops(NumIntermediates);
662 for (unsigned i = 0; i != NumIntermediates; ++i)
663 if (IntermediateVT.isVector())
664 Ops[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR,
665 IntermediateVT, Val,
666 DAG.getConstant(i * (NumElements / NumIntermediates),
667 PtrVT));
668 else
669 Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
670 IntermediateVT, Val,
671 DAG.getConstant(i, PtrVT));
672
673 // Split the intermediate operands into legal parts.
674 if (NumParts == NumIntermediates) {
675 // If the register was not expanded, promote or copy the value,
676 // as appropriate.
677 for (unsigned i = 0; i != NumParts; ++i)
678 getCopyToParts(DAG, Ops[i], &Parts[i], 1, PartVT);
679 } else if (NumParts > 0) {
680 // If the intermediate type was expanded, split each the value into
681 // legal parts.
682 assert(NumParts % NumIntermediates == 0 &&
683 "Must expand into a divisible number of parts!");
684 unsigned Factor = NumParts / NumIntermediates;
685 for (unsigned i = 0; i != NumIntermediates; ++i)
686 getCopyToParts(DAG, Ops[i], &Parts[i * Factor], Factor, PartVT);
687 }
688}
689
690
691void SelectionDAGLowering::init(GCFunctionInfo *gfi, AliasAnalysis &aa) {
692 AA = &aa;
693 GFI = gfi;
694 TD = DAG.getTarget().getTargetData();
695}
696
697/// clear - Clear out the curret SelectionDAG and the associated
698/// state and prepare this SelectionDAGLowering object to be used
699/// for a new block. This doesn't clear out information about
700/// additional blocks that are needed to complete switch lowering
701/// or PHI node updating; that information is cleared out as it is
702/// consumed.
703void SelectionDAGLowering::clear() {
704 NodeMap.clear();
705 PendingLoads.clear();
706 PendingExports.clear();
707 DAG.clear();
708}
709
710/// getRoot - Return the current virtual root of the Selection DAG,
711/// flushing any PendingLoad items. This must be done before emitting
712/// a store or any other node that may need to be ordered after any
713/// prior load instructions.
714///
715SDValue SelectionDAGLowering::getRoot() {
716 if (PendingLoads.empty())
717 return DAG.getRoot();
718
719 if (PendingLoads.size() == 1) {
720 SDValue Root = PendingLoads[0];
721 DAG.setRoot(Root);
722 PendingLoads.clear();
723 return Root;
724 }
725
726 // Otherwise, we have to make a token factor node.
727 SDValue Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
728 &PendingLoads[0], PendingLoads.size());
729 PendingLoads.clear();
730 DAG.setRoot(Root);
731 return Root;
732}
733
734/// getControlRoot - Similar to getRoot, but instead of flushing all the
735/// PendingLoad items, flush all the PendingExports items. It is necessary
736/// to do this before emitting a terminator instruction.
737///
738SDValue SelectionDAGLowering::getControlRoot() {
739 SDValue Root = DAG.getRoot();
740
741 if (PendingExports.empty())
742 return Root;
743
744 // Turn all of the CopyToReg chains into one factored node.
745 if (Root.getOpcode() != ISD::EntryToken) {
746 unsigned i = 0, e = PendingExports.size();
747 for (; i != e; ++i) {
748 assert(PendingExports[i].getNode()->getNumOperands() > 1);
749 if (PendingExports[i].getNode()->getOperand(0) == Root)
750 break; // Don't add the root if we already indirectly depend on it.
751 }
752
753 if (i == e)
754 PendingExports.push_back(Root);
755 }
756
757 Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
758 &PendingExports[0],
759 PendingExports.size());
760 PendingExports.clear();
761 DAG.setRoot(Root);
762 return Root;
763}
764
765void SelectionDAGLowering::visit(Instruction &I) {
766 visit(I.getOpcode(), I);
767}
768
769void SelectionDAGLowering::visit(unsigned Opcode, User &I) {
770 // Note: this doesn't use InstVisitor, because it has to work with
771 // ConstantExpr's in addition to instructions.
772 switch (Opcode) {
773 default: assert(0 && "Unknown instruction type encountered!");
774 abort();
775 // Build the switch statement using the Instruction.def file.
776#define HANDLE_INST(NUM, OPCODE, CLASS) \
777 case Instruction::OPCODE:return visit##OPCODE((CLASS&)I);
778#include "llvm/Instruction.def"
779 }
780}
781
782void SelectionDAGLowering::visitAdd(User &I) {
783 if (I.getType()->isFPOrFPVector())
784 visitBinary(I, ISD::FADD);
785 else
786 visitBinary(I, ISD::ADD);
787}
788
789void SelectionDAGLowering::visitMul(User &I) {
790 if (I.getType()->isFPOrFPVector())
791 visitBinary(I, ISD::FMUL);
792 else
793 visitBinary(I, ISD::MUL);
794}
795
796SDValue SelectionDAGLowering::getValue(const Value *V) {
797 SDValue &N = NodeMap[V];
798 if (N.getNode()) return N;
799
800 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V))) {
801 MVT VT = TLI.getValueType(V->getType(), true);
802
803 if (ConstantInt *CI = dyn_cast<ConstantInt>(C))
Dan Gohman4fbd7962008-09-12 18:08:03 +0000804 return N = DAG.getConstant(*CI, VT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000805
806 if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
807 return N = DAG.getGlobalAddress(GV, VT);
808
809 if (isa<ConstantPointerNull>(C))
810 return N = DAG.getConstant(0, TLI.getPointerTy());
811
812 if (ConstantFP *CFP = dyn_cast<ConstantFP>(C))
Dan Gohman4fbd7962008-09-12 18:08:03 +0000813 return N = DAG.getConstantFP(*CFP, VT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000814
815 if (isa<UndefValue>(C) && !isa<VectorType>(V->getType()) &&
816 !V->getType()->isAggregateType())
817 return N = DAG.getNode(ISD::UNDEF, VT);
818
819 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
820 visit(CE->getOpcode(), *CE);
821 SDValue N1 = NodeMap[V];
822 assert(N1.getNode() && "visit didn't populate the ValueMap!");
823 return N1;
824 }
825
826 if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
827 SmallVector<SDValue, 4> Constants;
828 for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end();
829 OI != OE; ++OI) {
830 SDNode *Val = getValue(*OI).getNode();
831 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
832 Constants.push_back(SDValue(Val, i));
833 }
834 return DAG.getMergeValues(&Constants[0], Constants.size());
835 }
836
837 if (isa<StructType>(C->getType()) || isa<ArrayType>(C->getType())) {
838 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
839 "Unknown struct or array constant!");
840
841 SmallVector<MVT, 4> ValueVTs;
842 ComputeValueVTs(TLI, C->getType(), ValueVTs);
843 unsigned NumElts = ValueVTs.size();
844 if (NumElts == 0)
845 return SDValue(); // empty struct
846 SmallVector<SDValue, 4> Constants(NumElts);
847 for (unsigned i = 0; i != NumElts; ++i) {
848 MVT EltVT = ValueVTs[i];
849 if (isa<UndefValue>(C))
850 Constants[i] = DAG.getNode(ISD::UNDEF, EltVT);
851 else if (EltVT.isFloatingPoint())
852 Constants[i] = DAG.getConstantFP(0, EltVT);
853 else
854 Constants[i] = DAG.getConstant(0, EltVT);
855 }
856 return DAG.getMergeValues(&Constants[0], NumElts);
857 }
858
859 const VectorType *VecTy = cast<VectorType>(V->getType());
860 unsigned NumElements = VecTy->getNumElements();
861
862 // Now that we know the number and type of the elements, get that number of
863 // elements into the Ops array based on what kind of constant it is.
864 SmallVector<SDValue, 16> Ops;
865 if (ConstantVector *CP = dyn_cast<ConstantVector>(C)) {
866 for (unsigned i = 0; i != NumElements; ++i)
867 Ops.push_back(getValue(CP->getOperand(i)));
868 } else {
869 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
870 "Unknown vector constant!");
871 MVT EltVT = TLI.getValueType(VecTy->getElementType());
872
873 SDValue Op;
874 if (isa<UndefValue>(C))
875 Op = DAG.getNode(ISD::UNDEF, EltVT);
876 else if (EltVT.isFloatingPoint())
877 Op = DAG.getConstantFP(0, EltVT);
878 else
879 Op = DAG.getConstant(0, EltVT);
880 Ops.assign(NumElements, Op);
881 }
882
883 // Create a BUILD_VECTOR node.
884 return NodeMap[V] = DAG.getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
885 }
886
887 // If this is a static alloca, generate it as the frameindex instead of
888 // computation.
889 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
890 DenseMap<const AllocaInst*, int>::iterator SI =
891 FuncInfo.StaticAllocaMap.find(AI);
892 if (SI != FuncInfo.StaticAllocaMap.end())
893 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
894 }
895
896 unsigned InReg = FuncInfo.ValueMap[V];
897 assert(InReg && "Value not in map!");
898
899 RegsForValue RFV(TLI, InReg, V->getType());
900 SDValue Chain = DAG.getEntryNode();
901 return RFV.getCopyFromRegs(DAG, Chain, NULL);
902}
903
904
905void SelectionDAGLowering::visitRet(ReturnInst &I) {
906 if (I.getNumOperands() == 0) {
907 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getControlRoot()));
908 return;
909 }
910
911 SmallVector<SDValue, 8> NewValues;
912 NewValues.push_back(getControlRoot());
913 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000914 SmallVector<MVT, 4> ValueVTs;
915 ComputeValueVTs(TLI, I.getOperand(i)->getType(), ValueVTs);
Dan Gohman7ea1ca62008-10-21 20:00:42 +0000916 unsigned NumValues = ValueVTs.size();
917 if (NumValues == 0) continue;
918
919 SDValue RetOp = getValue(I.getOperand(i));
920 for (unsigned j = 0, f = NumValues; j != f; ++j) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000921 MVT VT = ValueVTs[j];
922
923 // FIXME: C calling convention requires the return type to be promoted to
Dale Johannesenc9c6da62008-09-25 20:47:45 +0000924 // at least 32-bit. But this is not necessary for non-C calling
925 // conventions.
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000926 if (VT.isInteger()) {
927 MVT MinVT = TLI.getRegisterType(MVT::i32);
928 if (VT.bitsLT(MinVT))
929 VT = MinVT;
930 }
931
932 unsigned NumParts = TLI.getNumRegisters(VT);
933 MVT PartVT = TLI.getRegisterType(VT);
934 SmallVector<SDValue, 4> Parts(NumParts);
935 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
936
937 const Function *F = I.getParent()->getParent();
Devang Patel05988662008-09-25 21:00:45 +0000938 if (F->paramHasAttr(0, Attribute::SExt))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000939 ExtendKind = ISD::SIGN_EXTEND;
Devang Patel05988662008-09-25 21:00:45 +0000940 else if (F->paramHasAttr(0, Attribute::ZExt))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000941 ExtendKind = ISD::ZERO_EXTEND;
942
943 getCopyToParts(DAG, SDValue(RetOp.getNode(), RetOp.getResNo() + j),
944 &Parts[0], NumParts, PartVT, ExtendKind);
945
Dale Johannesenc9c6da62008-09-25 20:47:45 +0000946 // 'inreg' on function refers to return value
947 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
Devang Patel05988662008-09-25 21:00:45 +0000948 if (F->paramHasAttr(0, Attribute::InReg))
Dale Johannesenc9c6da62008-09-25 20:47:45 +0000949 Flags.setInReg();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000950 for (unsigned i = 0; i < NumParts; ++i) {
951 NewValues.push_back(Parts[i]);
Dale Johannesenc9c6da62008-09-25 20:47:45 +0000952 NewValues.push_back(DAG.getArgFlags(Flags));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000953 }
954 }
955 }
956 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other,
957 &NewValues[0], NewValues.size()));
958}
959
960/// ExportFromCurrentBlock - If this condition isn't known to be exported from
961/// the current basic block, add it to ValueMap now so that we'll get a
962/// CopyTo/FromReg.
963void SelectionDAGLowering::ExportFromCurrentBlock(Value *V) {
964 // No need to export constants.
965 if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
966
967 // Already exported?
968 if (FuncInfo.isExportedInst(V)) return;
969
970 unsigned Reg = FuncInfo.InitializeRegForValue(V);
971 CopyValueToVirtualRegister(V, Reg);
972}
973
974bool SelectionDAGLowering::isExportableFromCurrentBlock(Value *V,
975 const BasicBlock *FromBB) {
976 // The operands of the setcc have to be in this block. We don't know
977 // how to export them from some other block.
978 if (Instruction *VI = dyn_cast<Instruction>(V)) {
979 // Can export from current BB.
980 if (VI->getParent() == FromBB)
981 return true;
982
983 // Is already exported, noop.
984 return FuncInfo.isExportedInst(V);
985 }
986
987 // If this is an argument, we can export it if the BB is the entry block or
988 // if it is already exported.
989 if (isa<Argument>(V)) {
990 if (FromBB == &FromBB->getParent()->getEntryBlock())
991 return true;
992
993 // Otherwise, can only export this if it is already exported.
994 return FuncInfo.isExportedInst(V);
995 }
996
997 // Otherwise, constants can always be exported.
998 return true;
999}
1000
1001static bool InBlock(const Value *V, const BasicBlock *BB) {
1002 if (const Instruction *I = dyn_cast<Instruction>(V))
1003 return I->getParent() == BB;
1004 return true;
1005}
1006
Dan Gohman8c1a6ca2008-10-17 18:18:45 +00001007/// getFCmpCondCode - Return the ISD condition code corresponding to
1008/// the given LLVM IR floating-point condition code. This includes
1009/// consideration of global floating-point math flags.
1010///
1011static ISD::CondCode getFCmpCondCode(FCmpInst::Predicate Pred) {
1012 ISD::CondCode FPC, FOC;
1013 switch (Pred) {
1014 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
1015 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
1016 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
1017 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
1018 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
1019 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
1020 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
1021 case FCmpInst::FCMP_ORD: FOC = FPC = ISD::SETO; break;
1022 case FCmpInst::FCMP_UNO: FOC = FPC = ISD::SETUO; break;
1023 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
1024 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
1025 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
1026 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
1027 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
1028 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
1029 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
1030 default:
1031 assert(0 && "Invalid FCmp predicate opcode!");
1032 FOC = FPC = ISD::SETFALSE;
1033 break;
1034 }
1035 if (FiniteOnlyFPMath())
1036 return FOC;
1037 else
1038 return FPC;
1039}
1040
1041/// getICmpCondCode - Return the ISD condition code corresponding to
1042/// the given LLVM IR integer condition code.
1043///
1044static ISD::CondCode getICmpCondCode(ICmpInst::Predicate Pred) {
1045 switch (Pred) {
1046 case ICmpInst::ICMP_EQ: return ISD::SETEQ;
1047 case ICmpInst::ICMP_NE: return ISD::SETNE;
1048 case ICmpInst::ICMP_SLE: return ISD::SETLE;
1049 case ICmpInst::ICMP_ULE: return ISD::SETULE;
1050 case ICmpInst::ICMP_SGE: return ISD::SETGE;
1051 case ICmpInst::ICMP_UGE: return ISD::SETUGE;
1052 case ICmpInst::ICMP_SLT: return ISD::SETLT;
1053 case ICmpInst::ICMP_ULT: return ISD::SETULT;
1054 case ICmpInst::ICMP_SGT: return ISD::SETGT;
1055 case ICmpInst::ICMP_UGT: return ISD::SETUGT;
1056 default:
1057 assert(0 && "Invalid ICmp predicate opcode!");
1058 return ISD::SETNE;
1059 }
1060}
1061
Dan Gohmanc2277342008-10-17 21:16:08 +00001062/// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
1063/// This function emits a branch and is used at the leaves of an OR or an
1064/// AND operator tree.
1065///
1066void
1067SelectionDAGLowering::EmitBranchForMergedCondition(Value *Cond,
1068 MachineBasicBlock *TBB,
1069 MachineBasicBlock *FBB,
1070 MachineBasicBlock *CurBB) {
1071 const BasicBlock *BB = CurBB->getBasicBlock();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001072
Dan Gohmanc2277342008-10-17 21:16:08 +00001073 // If the leaf of the tree is a comparison, merge the condition into
1074 // the caseblock.
1075 if (CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
1076 // The operands of the cmp have to be in this block. We don't know
1077 // how to export them from some other block. If this is the first block
1078 // of the sequence, no exporting is needed.
1079 if (CurBB == CurMBB ||
1080 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
1081 isExportableFromCurrentBlock(BOp->getOperand(1), BB))) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001082 ISD::CondCode Condition;
1083 if (ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
Dan Gohman8c1a6ca2008-10-17 18:18:45 +00001084 Condition = getICmpCondCode(IC->getPredicate());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001085 } else if (FCmpInst *FC = dyn_cast<FCmpInst>(Cond)) {
Dan Gohman8c1a6ca2008-10-17 18:18:45 +00001086 Condition = getFCmpCondCode(FC->getPredicate());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001087 } else {
1088 Condition = ISD::SETEQ; // silence warning.
1089 assert(0 && "Unknown compare instruction");
1090 }
Dan Gohmanc2277342008-10-17 21:16:08 +00001091
1092 CaseBlock CB(Condition, BOp->getOperand(0),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001093 BOp->getOperand(1), NULL, TBB, FBB, CurBB);
1094 SwitchCases.push_back(CB);
1095 return;
1096 }
Dan Gohmanc2277342008-10-17 21:16:08 +00001097 }
1098
1099 // Create a CaseBlock record representing this branch.
1100 CaseBlock CB(ISD::SETEQ, Cond, ConstantInt::getTrue(),
1101 NULL, TBB, FBB, CurBB);
1102 SwitchCases.push_back(CB);
1103}
1104
1105/// FindMergedConditions - If Cond is an expression like
1106void SelectionDAGLowering::FindMergedConditions(Value *Cond,
1107 MachineBasicBlock *TBB,
1108 MachineBasicBlock *FBB,
1109 MachineBasicBlock *CurBB,
1110 unsigned Opc) {
1111 // If this node is not part of the or/and tree, emit it as a branch.
1112 Instruction *BOp = dyn_cast<Instruction>(Cond);
1113 if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
1114 (unsigned)BOp->getOpcode() != Opc || !BOp->hasOneUse() ||
1115 BOp->getParent() != CurBB->getBasicBlock() ||
1116 !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
1117 !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
1118 EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001119 return;
1120 }
1121
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001122 // Create TmpBB after CurBB.
1123 MachineFunction::iterator BBI = CurBB;
1124 MachineFunction &MF = DAG.getMachineFunction();
1125 MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
1126 CurBB->getParent()->insert(++BBI, TmpBB);
1127
1128 if (Opc == Instruction::Or) {
1129 // Codegen X | Y as:
1130 // jmp_if_X TBB
1131 // jmp TmpBB
1132 // TmpBB:
1133 // jmp_if_Y TBB
1134 // jmp FBB
1135 //
1136
1137 // Emit the LHS condition.
1138 FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, Opc);
1139
1140 // Emit the RHS condition into TmpBB.
1141 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
1142 } else {
1143 assert(Opc == Instruction::And && "Unknown merge op!");
1144 // Codegen X & Y as:
1145 // jmp_if_X TmpBB
1146 // jmp FBB
1147 // TmpBB:
1148 // jmp_if_Y TBB
1149 // jmp FBB
1150 //
1151 // This requires creation of TmpBB after CurBB.
1152
1153 // Emit the LHS condition.
1154 FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, Opc);
1155
1156 // Emit the RHS condition into TmpBB.
1157 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
1158 }
1159}
1160
1161/// If the set of cases should be emitted as a series of branches, return true.
1162/// If we should emit this as a bunch of and/or'd together conditions, return
1163/// false.
1164bool
1165SelectionDAGLowering::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases){
1166 if (Cases.size() != 2) return true;
1167
1168 // If this is two comparisons of the same values or'd or and'd together, they
1169 // will get folded into a single comparison, so don't emit two blocks.
1170 if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
1171 Cases[0].CmpRHS == Cases[1].CmpRHS) ||
1172 (Cases[0].CmpRHS == Cases[1].CmpLHS &&
1173 Cases[0].CmpLHS == Cases[1].CmpRHS)) {
1174 return false;
1175 }
1176
1177 return true;
1178}
1179
1180void SelectionDAGLowering::visitBr(BranchInst &I) {
1181 // Update machine-CFG edges.
1182 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
1183
1184 // Figure out which block is immediately after the current one.
1185 MachineBasicBlock *NextBlock = 0;
1186 MachineFunction::iterator BBI = CurMBB;
1187 if (++BBI != CurMBB->getParent()->end())
1188 NextBlock = BBI;
1189
1190 if (I.isUnconditional()) {
1191 // Update machine-CFG edges.
1192 CurMBB->addSuccessor(Succ0MBB);
1193
1194 // If this is not a fall-through branch, emit the branch.
1195 if (Succ0MBB != NextBlock)
1196 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getControlRoot(),
1197 DAG.getBasicBlock(Succ0MBB)));
1198 return;
1199 }
1200
1201 // If this condition is one of the special cases we handle, do special stuff
1202 // now.
1203 Value *CondVal = I.getCondition();
1204 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
1205
1206 // If this is a series of conditions that are or'd or and'd together, emit
1207 // this as a sequence of branches instead of setcc's with and/or operations.
1208 // For example, instead of something like:
1209 // cmp A, B
1210 // C = seteq
1211 // cmp D, E
1212 // F = setle
1213 // or C, F
1214 // jnz foo
1215 // Emit:
1216 // cmp A, B
1217 // je foo
1218 // cmp D, E
1219 // jle foo
1220 //
1221 if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
1222 if (BOp->hasOneUse() &&
1223 (BOp->getOpcode() == Instruction::And ||
1224 BOp->getOpcode() == Instruction::Or)) {
1225 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, CurMBB, BOp->getOpcode());
1226 // If the compares in later blocks need to use values not currently
1227 // exported from this block, export them now. This block should always
1228 // be the first entry.
1229 assert(SwitchCases[0].ThisBB == CurMBB && "Unexpected lowering!");
1230
1231 // Allow some cases to be rejected.
1232 if (ShouldEmitAsBranches(SwitchCases)) {
1233 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
1234 ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
1235 ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
1236 }
1237
1238 // Emit the branch for this block.
1239 visitSwitchCase(SwitchCases[0]);
1240 SwitchCases.erase(SwitchCases.begin());
1241 return;
1242 }
1243
1244 // Okay, we decided not to do this, remove any inserted MBB's and clear
1245 // SwitchCases.
1246 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
1247 CurMBB->getParent()->erase(SwitchCases[i].ThisBB);
1248
1249 SwitchCases.clear();
1250 }
1251 }
1252
1253 // Create a CaseBlock record representing this branch.
1254 CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(),
1255 NULL, Succ0MBB, Succ1MBB, CurMBB);
1256 // Use visitSwitchCase to actually insert the fast branch sequence for this
1257 // cond branch.
1258 visitSwitchCase(CB);
1259}
1260
1261/// visitSwitchCase - Emits the necessary code to represent a single node in
1262/// the binary search tree resulting from lowering a switch instruction.
1263void SelectionDAGLowering::visitSwitchCase(CaseBlock &CB) {
1264 SDValue Cond;
1265 SDValue CondLHS = getValue(CB.CmpLHS);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001266
1267 // Build the setcc now.
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001268 if (CB.CmpMHS == NULL) {
1269 // Fold "(X == true)" to X and "(X == false)" to !X to
1270 // handle common cases produced by branch lowering.
1271 if (CB.CmpRHS == ConstantInt::getTrue() && CB.CC == ISD::SETEQ)
1272 Cond = CondLHS;
1273 else if (CB.CmpRHS == ConstantInt::getFalse() && CB.CC == ISD::SETEQ) {
1274 SDValue True = DAG.getConstant(1, CondLHS.getValueType());
1275 Cond = DAG.getNode(ISD::XOR, CondLHS.getValueType(), CondLHS, True);
1276 } else
1277 Cond = DAG.getSetCC(MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
1278 } else {
1279 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
1280
Anton Korobeynikov23218582008-12-23 22:25:27 +00001281 const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
1282 const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001283
1284 SDValue CmpOp = getValue(CB.CmpMHS);
1285 MVT VT = CmpOp.getValueType();
1286
1287 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
1288 Cond = DAG.getSetCC(MVT::i1, CmpOp, DAG.getConstant(High, VT), ISD::SETLE);
1289 } else {
1290 SDValue SUB = DAG.getNode(ISD::SUB, VT, CmpOp, DAG.getConstant(Low, VT));
1291 Cond = DAG.getSetCC(MVT::i1, SUB,
1292 DAG.getConstant(High-Low, VT), ISD::SETULE);
1293 }
1294 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00001295
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001296 // Update successor info
1297 CurMBB->addSuccessor(CB.TrueBB);
1298 CurMBB->addSuccessor(CB.FalseBB);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001299
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001300 // Set NextBlock to be the MBB immediately after the current one, if any.
1301 // This is used to avoid emitting unnecessary branches to the next block.
1302 MachineBasicBlock *NextBlock = 0;
1303 MachineFunction::iterator BBI = CurMBB;
1304 if (++BBI != CurMBB->getParent()->end())
1305 NextBlock = BBI;
Anton Korobeynikov23218582008-12-23 22:25:27 +00001306
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001307 // If the lhs block is the next block, invert the condition so that we can
1308 // fall through to the lhs instead of the rhs block.
1309 if (CB.TrueBB == NextBlock) {
1310 std::swap(CB.TrueBB, CB.FalseBB);
1311 SDValue True = DAG.getConstant(1, Cond.getValueType());
1312 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
1313 }
1314 SDValue BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, getControlRoot(), Cond,
1315 DAG.getBasicBlock(CB.TrueBB));
Anton Korobeynikov23218582008-12-23 22:25:27 +00001316
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001317 // If the branch was constant folded, fix up the CFG.
1318 if (BrCond.getOpcode() == ISD::BR) {
1319 CurMBB->removeSuccessor(CB.FalseBB);
1320 DAG.setRoot(BrCond);
1321 } else {
1322 // Otherwise, go ahead and insert the false branch.
Anton Korobeynikov23218582008-12-23 22:25:27 +00001323 if (BrCond == getControlRoot())
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001324 CurMBB->removeSuccessor(CB.TrueBB);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001325
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001326 if (CB.FalseBB == NextBlock)
1327 DAG.setRoot(BrCond);
1328 else
Anton Korobeynikov23218582008-12-23 22:25:27 +00001329 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001330 DAG.getBasicBlock(CB.FalseBB)));
1331 }
1332}
1333
1334/// visitJumpTable - Emit JumpTable node in the current MBB
1335void SelectionDAGLowering::visitJumpTable(JumpTable &JT) {
1336 // Emit the code for the jump table
1337 assert(JT.Reg != -1U && "Should lower JT Header first!");
1338 MVT PTy = TLI.getPointerTy();
1339 SDValue Index = DAG.getCopyFromReg(getControlRoot(), JT.Reg, PTy);
1340 SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
1341 DAG.setRoot(DAG.getNode(ISD::BR_JT, MVT::Other, Index.getValue(1),
1342 Table, Index));
1343 return;
1344}
1345
1346/// visitJumpTableHeader - This function emits necessary code to produce index
1347/// in the JumpTable from switch case.
1348void SelectionDAGLowering::visitJumpTableHeader(JumpTable &JT,
1349 JumpTableHeader &JTH) {
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001350 // Subtract the lowest switch case value from the value being switched on and
1351 // conditional branch to default mbb if the result is greater than the
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001352 // difference between smallest and largest cases.
1353 SDValue SwitchOp = getValue(JTH.SValue);
1354 MVT VT = SwitchOp.getValueType();
1355 SDValue SUB = DAG.getNode(ISD::SUB, VT, SwitchOp,
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001356 DAG.getConstant(JTH.First, VT));
Anton Korobeynikov23218582008-12-23 22:25:27 +00001357
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001358 // The SDNode we just created, which holds the value being switched on minus
1359 // the the smallest case value, needs to be copied to a virtual register so it
1360 // can be used as an index into the jump table in a subsequent basic block.
1361 // This value may be smaller or larger than the target's pointer type, and
1362 // therefore require extension or truncating.
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001363 if (VT.bitsGT(TLI.getPointerTy()))
1364 SwitchOp = DAG.getNode(ISD::TRUNCATE, TLI.getPointerTy(), SUB);
1365 else
1366 SwitchOp = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(), SUB);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001367
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001368 unsigned JumpTableReg = FuncInfo.MakeReg(TLI.getPointerTy());
1369 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), JumpTableReg, SwitchOp);
1370 JT.Reg = JumpTableReg;
1371
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001372 // Emit the range check for the jump table, and branch to the default block
1373 // for the switch statement if the value being switched on exceeds the largest
1374 // case in the switch.
Duncan Sands5480c042009-01-01 15:52:00 +00001375 SDValue CMP = DAG.getSetCC(TLI.getSetCCResultType(SUB.getValueType()), SUB,
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001376 DAG.getConstant(JTH.Last-JTH.First,VT),
1377 ISD::SETUGT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001378
1379 // Set NextBlock to be the MBB immediately after the current one, if any.
1380 // This is used to avoid emitting unnecessary branches to the next block.
1381 MachineBasicBlock *NextBlock = 0;
1382 MachineFunction::iterator BBI = CurMBB;
1383 if (++BBI != CurMBB->getParent()->end())
1384 NextBlock = BBI;
1385
1386 SDValue BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, CopyTo, CMP,
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001387 DAG.getBasicBlock(JT.Default));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001388
1389 if (JT.MBB == NextBlock)
1390 DAG.setRoot(BrCond);
1391 else
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001392 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001393 DAG.getBasicBlock(JT.MBB)));
1394
1395 return;
1396}
1397
1398/// visitBitTestHeader - This function emits necessary code to produce value
1399/// suitable for "bit tests"
1400void SelectionDAGLowering::visitBitTestHeader(BitTestBlock &B) {
1401 // Subtract the minimum value
1402 SDValue SwitchOp = getValue(B.SValue);
1403 MVT VT = SwitchOp.getValueType();
1404 SDValue SUB = DAG.getNode(ISD::SUB, VT, SwitchOp,
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001405 DAG.getConstant(B.First, VT));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001406
1407 // Check range
Duncan Sands5480c042009-01-01 15:52:00 +00001408 SDValue RangeCmp = DAG.getSetCC(TLI.getSetCCResultType(SUB.getValueType()), SUB,
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001409 DAG.getConstant(B.Range, VT),
1410 ISD::SETUGT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001411
1412 SDValue ShiftOp;
1413 if (VT.bitsGT(TLI.getShiftAmountTy()))
1414 ShiftOp = DAG.getNode(ISD::TRUNCATE, TLI.getShiftAmountTy(), SUB);
1415 else
1416 ShiftOp = DAG.getNode(ISD::ZERO_EXTEND, TLI.getShiftAmountTy(), SUB);
1417
1418 // Make desired shift
1419 SDValue SwitchVal = DAG.getNode(ISD::SHL, TLI.getPointerTy(),
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001420 DAG.getConstant(1, TLI.getPointerTy()),
1421 ShiftOp);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001422
1423 unsigned SwitchReg = FuncInfo.MakeReg(TLI.getPointerTy());
1424 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), SwitchReg, SwitchVal);
1425 B.Reg = SwitchReg;
1426
1427 // Set NextBlock to be the MBB immediately after the current one, if any.
1428 // This is used to avoid emitting unnecessary branches to the next block.
1429 MachineBasicBlock *NextBlock = 0;
1430 MachineFunction::iterator BBI = CurMBB;
1431 if (++BBI != CurMBB->getParent()->end())
1432 NextBlock = BBI;
1433
1434 MachineBasicBlock* MBB = B.Cases[0].ThisBB;
1435
1436 CurMBB->addSuccessor(B.Default);
1437 CurMBB->addSuccessor(MBB);
1438
1439 SDValue BrRange = DAG.getNode(ISD::BRCOND, MVT::Other, CopyTo, RangeCmp,
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001440 DAG.getBasicBlock(B.Default));
Anton Korobeynikov23218582008-12-23 22:25:27 +00001441
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001442 if (MBB == NextBlock)
1443 DAG.setRoot(BrRange);
1444 else
1445 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, CopyTo,
1446 DAG.getBasicBlock(MBB)));
1447
1448 return;
1449}
1450
1451/// visitBitTestCase - this function produces one "bit test"
1452void SelectionDAGLowering::visitBitTestCase(MachineBasicBlock* NextMBB,
1453 unsigned Reg,
1454 BitTestCase &B) {
1455 // Emit bit tests and jumps
Anton Korobeynikov23218582008-12-23 22:25:27 +00001456 SDValue SwitchVal = DAG.getCopyFromReg(getControlRoot(), Reg,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001457 TLI.getPointerTy());
Anton Korobeynikov23218582008-12-23 22:25:27 +00001458
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001459 SDValue AndOp = DAG.getNode(ISD::AND, TLI.getPointerTy(), SwitchVal,
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001460 DAG.getConstant(B.Mask, TLI.getPointerTy()));
Duncan Sands5480c042009-01-01 15:52:00 +00001461 SDValue AndCmp = DAG.getSetCC(TLI.getSetCCResultType(AndOp.getValueType()),
1462 AndOp, DAG.getConstant(0, TLI.getPointerTy()),
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001463 ISD::SETNE);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001464
1465 CurMBB->addSuccessor(B.TargetBB);
1466 CurMBB->addSuccessor(NextMBB);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001467
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001468 SDValue BrAnd = DAG.getNode(ISD::BRCOND, MVT::Other, getControlRoot(),
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001469 AndCmp, DAG.getBasicBlock(B.TargetBB));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001470
1471 // Set NextBlock to be the MBB immediately after the current one, if any.
1472 // This is used to avoid emitting unnecessary branches to the next block.
1473 MachineBasicBlock *NextBlock = 0;
1474 MachineFunction::iterator BBI = CurMBB;
1475 if (++BBI != CurMBB->getParent()->end())
1476 NextBlock = BBI;
1477
1478 if (NextMBB == NextBlock)
1479 DAG.setRoot(BrAnd);
1480 else
1481 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrAnd,
1482 DAG.getBasicBlock(NextMBB)));
1483
1484 return;
1485}
1486
1487void SelectionDAGLowering::visitInvoke(InvokeInst &I) {
1488 // Retrieve successors.
1489 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
1490 MachineBasicBlock *LandingPad = FuncInfo.MBBMap[I.getSuccessor(1)];
1491
Gabor Greifb67e6b32009-01-15 11:10:44 +00001492 const Value *Callee(I.getCalledValue());
1493 if (isa<InlineAsm>(Callee))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001494 visitInlineAsm(&I);
1495 else
Gabor Greifb67e6b32009-01-15 11:10:44 +00001496 LowerCallTo(&I, getValue(Callee), false, LandingPad);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001497
1498 // If the value of the invoke is used outside of its defining block, make it
1499 // available as a virtual register.
1500 if (!I.use_empty()) {
1501 DenseMap<const Value*, unsigned>::iterator VMI = FuncInfo.ValueMap.find(&I);
1502 if (VMI != FuncInfo.ValueMap.end())
1503 CopyValueToVirtualRegister(&I, VMI->second);
1504 }
1505
1506 // Update successor info
1507 CurMBB->addSuccessor(Return);
1508 CurMBB->addSuccessor(LandingPad);
1509
1510 // Drop into normal successor.
1511 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getControlRoot(),
1512 DAG.getBasicBlock(Return)));
1513}
1514
1515void SelectionDAGLowering::visitUnwind(UnwindInst &I) {
1516}
1517
1518/// handleSmallSwitchCaseRange - Emit a series of specific tests (suitable for
1519/// small case ranges).
1520bool SelectionDAGLowering::handleSmallSwitchRange(CaseRec& CR,
1521 CaseRecVector& WorkList,
1522 Value* SV,
1523 MachineBasicBlock* Default) {
1524 Case& BackCase = *(CR.Range.second-1);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001525
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001526 // Size is the number of Cases represented by this range.
Anton Korobeynikov23218582008-12-23 22:25:27 +00001527 size_t Size = CR.Range.second - CR.Range.first;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001528 if (Size > 3)
Anton Korobeynikov23218582008-12-23 22:25:27 +00001529 return false;
1530
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001531 // Get the MachineFunction which holds the current MBB. This is used when
1532 // inserting any additional MBBs necessary to represent the switch.
Anton Korobeynikov23218582008-12-23 22:25:27 +00001533 MachineFunction *CurMF = CurMBB->getParent();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001534
1535 // Figure out which block is immediately after the current one.
1536 MachineBasicBlock *NextBlock = 0;
1537 MachineFunction::iterator BBI = CR.CaseBB;
1538
1539 if (++BBI != CurMBB->getParent()->end())
1540 NextBlock = BBI;
1541
1542 // TODO: If any two of the cases has the same destination, and if one value
1543 // is the same as the other, but has one bit unset that the other has set,
1544 // use bit manipulation to do two compares at once. For example:
1545 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
Anton Korobeynikov23218582008-12-23 22:25:27 +00001546
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001547 // Rearrange the case blocks so that the last one falls through if possible.
1548 if (NextBlock && Default != NextBlock && BackCase.BB != NextBlock) {
1549 // The last case block won't fall through into 'NextBlock' if we emit the
1550 // branches in this order. See if rearranging a case value would help.
1551 for (CaseItr I = CR.Range.first, E = CR.Range.second-1; I != E; ++I) {
1552 if (I->BB == NextBlock) {
1553 std::swap(*I, BackCase);
1554 break;
1555 }
1556 }
1557 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00001558
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001559 // Create a CaseBlock record representing a conditional branch to
1560 // the Case's target mbb if the value being switched on SV is equal
1561 // to C.
1562 MachineBasicBlock *CurBlock = CR.CaseBB;
1563 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I) {
1564 MachineBasicBlock *FallThrough;
1565 if (I != E-1) {
1566 FallThrough = CurMF->CreateMachineBasicBlock(CurBlock->getBasicBlock());
1567 CurMF->insert(BBI, FallThrough);
1568 } else {
1569 // If the last case doesn't match, go to the default block.
1570 FallThrough = Default;
1571 }
1572
1573 Value *RHS, *LHS, *MHS;
1574 ISD::CondCode CC;
1575 if (I->High == I->Low) {
1576 // This is just small small case range :) containing exactly 1 case
1577 CC = ISD::SETEQ;
1578 LHS = SV; RHS = I->High; MHS = NULL;
1579 } else {
1580 CC = ISD::SETLE;
1581 LHS = I->Low; MHS = SV; RHS = I->High;
1582 }
1583 CaseBlock CB(CC, LHS, RHS, MHS, I->BB, FallThrough, CurBlock);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001584
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001585 // If emitting the first comparison, just call visitSwitchCase to emit the
1586 // code into the current block. Otherwise, push the CaseBlock onto the
1587 // vector to be later processed by SDISel, and insert the node's MBB
1588 // before the next MBB.
1589 if (CurBlock == CurMBB)
1590 visitSwitchCase(CB);
1591 else
1592 SwitchCases.push_back(CB);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001593
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001594 CurBlock = FallThrough;
1595 }
1596
1597 return true;
1598}
1599
1600static inline bool areJTsAllowed(const TargetLowering &TLI) {
1601 return !DisableJumpTables &&
1602 (TLI.isOperationLegal(ISD::BR_JT, MVT::Other) ||
1603 TLI.isOperationLegal(ISD::BRIND, MVT::Other));
1604}
Anton Korobeynikov23218582008-12-23 22:25:27 +00001605
Anton Korobeynikove2f95e92008-12-23 22:26:01 +00001606static APInt ComputeRange(const APInt &First, const APInt &Last) {
1607 APInt LastExt(Last), FirstExt(First);
1608 uint32_t BitWidth = std::max(Last.getBitWidth(), First.getBitWidth()) + 1;
1609 LastExt.sext(BitWidth); FirstExt.sext(BitWidth);
1610 return (LastExt - FirstExt + 1ULL);
1611}
1612
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001613/// handleJTSwitchCase - Emit jumptable for current switch case range
1614bool SelectionDAGLowering::handleJTSwitchCase(CaseRec& CR,
1615 CaseRecVector& WorkList,
1616 Value* SV,
1617 MachineBasicBlock* Default) {
1618 Case& FrontCase = *CR.Range.first;
1619 Case& BackCase = *(CR.Range.second-1);
1620
Anton Korobeynikov23218582008-12-23 22:25:27 +00001621 const APInt& First = cast<ConstantInt>(FrontCase.Low)->getValue();
1622 const APInt& Last = cast<ConstantInt>(BackCase.High)->getValue();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001623
Anton Korobeynikov23218582008-12-23 22:25:27 +00001624 size_t TSize = 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001625 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1626 I!=E; ++I)
1627 TSize += I->size();
1628
1629 if (!areJTsAllowed(TLI) || TSize <= 3)
1630 return false;
Anton Korobeynikov23218582008-12-23 22:25:27 +00001631
Anton Korobeynikove2f95e92008-12-23 22:26:01 +00001632 APInt Range = ComputeRange(First, Last);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001633 double Density = (double)TSize / Range.roundToDouble();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001634 if (Density < 0.4)
1635 return false;
1636
Anton Korobeynikov56d245b2008-12-23 22:26:18 +00001637 DEBUG(errs() << "Lowering jump table\n"
1638 << "First entry: " << First << ". Last entry: " << Last << '\n'
1639 << "Range: " << Range
1640 << "Size: " << TSize << ". Density: " << Density << "\n\n");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001641
1642 // Get the MachineFunction which holds the current MBB. This is used when
1643 // inserting any additional MBBs necessary to represent the switch.
1644 MachineFunction *CurMF = CurMBB->getParent();
1645
1646 // Figure out which block is immediately after the current one.
1647 MachineBasicBlock *NextBlock = 0;
1648 MachineFunction::iterator BBI = CR.CaseBB;
1649
1650 if (++BBI != CurMBB->getParent()->end())
1651 NextBlock = BBI;
1652
1653 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1654
1655 // Create a new basic block to hold the code for loading the address
1656 // of the jump table, and jumping to it. Update successor information;
1657 // we will either branch to the default case for the switch, or the jump
1658 // table.
1659 MachineBasicBlock *JumpTableBB = CurMF->CreateMachineBasicBlock(LLVMBB);
1660 CurMF->insert(BBI, JumpTableBB);
1661 CR.CaseBB->addSuccessor(Default);
1662 CR.CaseBB->addSuccessor(JumpTableBB);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001663
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001664 // Build a vector of destination BBs, corresponding to each target
1665 // of the jump table. If the value of the jump table slot corresponds to
1666 // a case statement, push the case's BB onto the vector, otherwise, push
1667 // the default BB.
1668 std::vector<MachineBasicBlock*> DestBBs;
Anton Korobeynikov23218582008-12-23 22:25:27 +00001669 APInt TEI = First;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001670 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++TEI) {
Anton Korobeynikov23218582008-12-23 22:25:27 +00001671 const APInt& Low = cast<ConstantInt>(I->Low)->getValue();
1672 const APInt& High = cast<ConstantInt>(I->High)->getValue();
1673
1674 if (Low.sle(TEI) && TEI.sle(High)) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001675 DestBBs.push_back(I->BB);
1676 if (TEI==High)
1677 ++I;
1678 } else {
1679 DestBBs.push_back(Default);
1680 }
1681 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00001682
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001683 // Update successor info. Add one edge to each unique successor.
Anton Korobeynikov23218582008-12-23 22:25:27 +00001684 BitVector SuccsHandled(CR.CaseBB->getParent()->getNumBlockIDs());
1685 for (std::vector<MachineBasicBlock*>::iterator I = DestBBs.begin(),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001686 E = DestBBs.end(); I != E; ++I) {
1687 if (!SuccsHandled[(*I)->getNumber()]) {
1688 SuccsHandled[(*I)->getNumber()] = true;
1689 JumpTableBB->addSuccessor(*I);
1690 }
1691 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00001692
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001693 // Create a jump table index for this jump table, or return an existing
1694 // one.
1695 unsigned JTI = CurMF->getJumpTableInfo()->getJumpTableIndex(DestBBs);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001696
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001697 // Set the jump table information so that we can codegen it as a second
1698 // MachineBasicBlock
1699 JumpTable JT(-1U, JTI, JumpTableBB, Default);
1700 JumpTableHeader JTH(First, Last, SV, CR.CaseBB, (CR.CaseBB == CurMBB));
1701 if (CR.CaseBB == CurMBB)
1702 visitJumpTableHeader(JT, JTH);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001703
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001704 JTCases.push_back(JumpTableBlock(JTH, JT));
1705
1706 return true;
1707}
1708
1709/// handleBTSplitSwitchCase - emit comparison and split binary search tree into
1710/// 2 subtrees.
1711bool SelectionDAGLowering::handleBTSplitSwitchCase(CaseRec& CR,
1712 CaseRecVector& WorkList,
1713 Value* SV,
1714 MachineBasicBlock* Default) {
1715 // Get the MachineFunction which holds the current MBB. This is used when
1716 // inserting any additional MBBs necessary to represent the switch.
Anton Korobeynikov23218582008-12-23 22:25:27 +00001717 MachineFunction *CurMF = CurMBB->getParent();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001718
1719 // Figure out which block is immediately after the current one.
1720 MachineBasicBlock *NextBlock = 0;
1721 MachineFunction::iterator BBI = CR.CaseBB;
1722
1723 if (++BBI != CurMBB->getParent()->end())
1724 NextBlock = BBI;
1725
1726 Case& FrontCase = *CR.Range.first;
1727 Case& BackCase = *(CR.Range.second-1);
1728 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1729
1730 // Size is the number of Cases represented by this range.
1731 unsigned Size = CR.Range.second - CR.Range.first;
1732
Anton Korobeynikov23218582008-12-23 22:25:27 +00001733 const APInt& First = cast<ConstantInt>(FrontCase.Low)->getValue();
1734 const APInt& Last = cast<ConstantInt>(BackCase.High)->getValue();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001735 double FMetric = 0;
1736 CaseItr Pivot = CR.Range.first + Size/2;
1737
1738 // Select optimal pivot, maximizing sum density of LHS and RHS. This will
1739 // (heuristically) allow us to emit JumpTable's later.
Anton Korobeynikov23218582008-12-23 22:25:27 +00001740 size_t TSize = 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001741 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1742 I!=E; ++I)
1743 TSize += I->size();
1744
Anton Korobeynikov23218582008-12-23 22:25:27 +00001745 size_t LSize = FrontCase.size();
1746 size_t RSize = TSize-LSize;
Anton Korobeynikov56d245b2008-12-23 22:26:18 +00001747 DEBUG(errs() << "Selecting best pivot: \n"
1748 << "First: " << First << ", Last: " << Last <<'\n'
1749 << "LSize: " << LSize << ", RSize: " << RSize << '\n');
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001750 for (CaseItr I = CR.Range.first, J=I+1, E = CR.Range.second;
1751 J!=E; ++I, ++J) {
Anton Korobeynikov23218582008-12-23 22:25:27 +00001752 const APInt& LEnd = cast<ConstantInt>(I->High)->getValue();
1753 const APInt& RBegin = cast<ConstantInt>(J->Low)->getValue();
Anton Korobeynikove2f95e92008-12-23 22:26:01 +00001754 APInt Range = ComputeRange(LEnd, RBegin);
1755 assert((Range - 2ULL).isNonNegative() &&
1756 "Invalid case distance");
Anton Korobeynikov23218582008-12-23 22:25:27 +00001757 double LDensity = (double)LSize / (LEnd - First + 1ULL).roundToDouble();
1758 double RDensity = (double)RSize / (Last - RBegin + 1ULL).roundToDouble();
Anton Korobeynikove2f95e92008-12-23 22:26:01 +00001759 double Metric = Range.logBase2()*(LDensity+RDensity);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001760 // Should always split in some non-trivial place
Anton Korobeynikov56d245b2008-12-23 22:26:18 +00001761 DEBUG(errs() <<"=>Step\n"
1762 << "LEnd: " << LEnd << ", RBegin: " << RBegin << '\n'
1763 << "LDensity: " << LDensity
1764 << ", RDensity: " << RDensity << '\n'
1765 << "Metric: " << Metric << '\n');
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001766 if (FMetric < Metric) {
1767 Pivot = J;
1768 FMetric = Metric;
Anton Korobeynikov56d245b2008-12-23 22:26:18 +00001769 DEBUG(errs() << "Current metric set to: " << FMetric << '\n');
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001770 }
1771
1772 LSize += J->size();
1773 RSize -= J->size();
1774 }
1775 if (areJTsAllowed(TLI)) {
1776 // If our case is dense we *really* should handle it earlier!
1777 assert((FMetric > 0) && "Should handle dense range earlier!");
1778 } else {
1779 Pivot = CR.Range.first + Size/2;
1780 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00001781
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001782 CaseRange LHSR(CR.Range.first, Pivot);
1783 CaseRange RHSR(Pivot, CR.Range.second);
1784 Constant *C = Pivot->Low;
1785 MachineBasicBlock *FalseBB = 0, *TrueBB = 0;
Anton Korobeynikov23218582008-12-23 22:25:27 +00001786
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001787 // We know that we branch to the LHS if the Value being switched on is
1788 // less than the Pivot value, C. We use this to optimize our binary
1789 // tree a bit, by recognizing that if SV is greater than or equal to the
1790 // LHS's Case Value, and that Case Value is exactly one less than the
1791 // Pivot's Value, then we can branch directly to the LHS's Target,
1792 // rather than creating a leaf node for it.
1793 if ((LHSR.second - LHSR.first) == 1 &&
1794 LHSR.first->High == CR.GE &&
Anton Korobeynikov23218582008-12-23 22:25:27 +00001795 cast<ConstantInt>(C)->getValue() ==
1796 (cast<ConstantInt>(CR.GE)->getValue() + 1LL)) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001797 TrueBB = LHSR.first->BB;
1798 } else {
1799 TrueBB = CurMF->CreateMachineBasicBlock(LLVMBB);
1800 CurMF->insert(BBI, TrueBB);
1801 WorkList.push_back(CaseRec(TrueBB, C, CR.GE, LHSR));
1802 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00001803
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001804 // Similar to the optimization above, if the Value being switched on is
1805 // known to be less than the Constant CR.LT, and the current Case Value
1806 // is CR.LT - 1, then we can branch directly to the target block for
1807 // the current Case Value, rather than emitting a RHS leaf node for it.
1808 if ((RHSR.second - RHSR.first) == 1 && CR.LT &&
Anton Korobeynikov23218582008-12-23 22:25:27 +00001809 cast<ConstantInt>(RHSR.first->Low)->getValue() ==
1810 (cast<ConstantInt>(CR.LT)->getValue() - 1LL)) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001811 FalseBB = RHSR.first->BB;
1812 } else {
1813 FalseBB = CurMF->CreateMachineBasicBlock(LLVMBB);
1814 CurMF->insert(BBI, FalseBB);
1815 WorkList.push_back(CaseRec(FalseBB,CR.LT,C,RHSR));
1816 }
1817
1818 // Create a CaseBlock record representing a conditional branch to
1819 // the LHS node if the value being switched on SV is less than C.
1820 // Otherwise, branch to LHS.
1821 CaseBlock CB(ISD::SETLT, SV, C, NULL, TrueBB, FalseBB, CR.CaseBB);
1822
1823 if (CR.CaseBB == CurMBB)
1824 visitSwitchCase(CB);
1825 else
1826 SwitchCases.push_back(CB);
1827
1828 return true;
1829}
1830
1831/// handleBitTestsSwitchCase - if current case range has few destination and
1832/// range span less, than machine word bitwidth, encode case range into series
1833/// of masks and emit bit tests with these masks.
1834bool SelectionDAGLowering::handleBitTestsSwitchCase(CaseRec& CR,
1835 CaseRecVector& WorkList,
1836 Value* SV,
1837 MachineBasicBlock* Default){
1838 unsigned IntPtrBits = TLI.getPointerTy().getSizeInBits();
1839
1840 Case& FrontCase = *CR.Range.first;
1841 Case& BackCase = *(CR.Range.second-1);
1842
1843 // Get the MachineFunction which holds the current MBB. This is used when
1844 // inserting any additional MBBs necessary to represent the switch.
Anton Korobeynikov23218582008-12-23 22:25:27 +00001845 MachineFunction *CurMF = CurMBB->getParent();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001846
Anton Korobeynikov23218582008-12-23 22:25:27 +00001847 size_t numCmps = 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001848 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1849 I!=E; ++I) {
1850 // Single case counts one, case range - two.
Anton Korobeynikov23218582008-12-23 22:25:27 +00001851 numCmps += (I->Low == I->High ? 1 : 2);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001852 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00001853
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001854 // Count unique destinations
1855 SmallSet<MachineBasicBlock*, 4> Dests;
1856 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
1857 Dests.insert(I->BB);
1858 if (Dests.size() > 3)
1859 // Don't bother the code below, if there are too much unique destinations
1860 return false;
1861 }
Anton Korobeynikov56d245b2008-12-23 22:26:18 +00001862 DEBUG(errs() << "Total number of unique destinations: " << Dests.size() << '\n'
1863 << "Total number of comparisons: " << numCmps << '\n');
Anton Korobeynikov23218582008-12-23 22:25:27 +00001864
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001865 // Compute span of values.
Anton Korobeynikov23218582008-12-23 22:25:27 +00001866 const APInt& minValue = cast<ConstantInt>(FrontCase.Low)->getValue();
1867 const APInt& maxValue = cast<ConstantInt>(BackCase.High)->getValue();
Anton Korobeynikove2f95e92008-12-23 22:26:01 +00001868 APInt cmpRange = maxValue - minValue;
1869
Anton Korobeynikov56d245b2008-12-23 22:26:18 +00001870 DEBUG(errs() << "Compare range: " << cmpRange << '\n'
1871 << "Low bound: " << minValue << '\n'
1872 << "High bound: " << maxValue << '\n');
Anton Korobeynikov23218582008-12-23 22:25:27 +00001873
1874 if (cmpRange.uge(APInt(cmpRange.getBitWidth(), IntPtrBits)) ||
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001875 (!(Dests.size() == 1 && numCmps >= 3) &&
1876 !(Dests.size() == 2 && numCmps >= 5) &&
1877 !(Dests.size() >= 3 && numCmps >= 6)))
1878 return false;
Anton Korobeynikov23218582008-12-23 22:25:27 +00001879
Anton Korobeynikov56d245b2008-12-23 22:26:18 +00001880 DEBUG(errs() << "Emitting bit tests\n");
Anton Korobeynikov23218582008-12-23 22:25:27 +00001881 APInt lowBound = APInt::getNullValue(cmpRange.getBitWidth());
1882
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001883 // Optimize the case where all the case values fit in a
1884 // word without having to subtract minValue. In this case,
1885 // we can optimize away the subtraction.
Anton Korobeynikov23218582008-12-23 22:25:27 +00001886 if (minValue.isNonNegative() &&
1887 maxValue.slt(APInt(maxValue.getBitWidth(), IntPtrBits))) {
1888 cmpRange = maxValue;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001889 } else {
Anton Korobeynikov23218582008-12-23 22:25:27 +00001890 lowBound = minValue;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001891 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00001892
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001893 CaseBitsVector CasesBits;
1894 unsigned i, count = 0;
1895
1896 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
1897 MachineBasicBlock* Dest = I->BB;
1898 for (i = 0; i < count; ++i)
1899 if (Dest == CasesBits[i].BB)
1900 break;
Anton Korobeynikov23218582008-12-23 22:25:27 +00001901
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001902 if (i == count) {
1903 assert((count < 3) && "Too much destinations to test!");
1904 CasesBits.push_back(CaseBits(0, Dest, 0));
1905 count++;
1906 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00001907
1908 const APInt& lowValue = cast<ConstantInt>(I->Low)->getValue();
1909 const APInt& highValue = cast<ConstantInt>(I->High)->getValue();
1910
1911 uint64_t lo = (lowValue - lowBound).getZExtValue();
1912 uint64_t hi = (highValue - lowBound).getZExtValue();
1913
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001914 for (uint64_t j = lo; j <= hi; j++) {
1915 CasesBits[i].Mask |= 1ULL << j;
1916 CasesBits[i].Bits++;
1917 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00001918
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001919 }
1920 std::sort(CasesBits.begin(), CasesBits.end(), CaseBitsCmp());
Anton Korobeynikov23218582008-12-23 22:25:27 +00001921
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001922 BitTestInfo BTC;
1923
1924 // Figure out which block is immediately after the current one.
1925 MachineFunction::iterator BBI = CR.CaseBB;
1926 ++BBI;
1927
1928 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1929
Anton Korobeynikov56d245b2008-12-23 22:26:18 +00001930 DEBUG(errs() << "Cases:\n");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001931 for (unsigned i = 0, e = CasesBits.size(); i!=e; ++i) {
Anton Korobeynikov56d245b2008-12-23 22:26:18 +00001932 DEBUG(errs() << "Mask: " << CasesBits[i].Mask
1933 << ", Bits: " << CasesBits[i].Bits
1934 << ", BB: " << CasesBits[i].BB << '\n');
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001935
1936 MachineBasicBlock *CaseBB = CurMF->CreateMachineBasicBlock(LLVMBB);
1937 CurMF->insert(BBI, CaseBB);
1938 BTC.push_back(BitTestCase(CasesBits[i].Mask,
1939 CaseBB,
1940 CasesBits[i].BB));
1941 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00001942
1943 BitTestBlock BTB(lowBound, cmpRange, SV,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001944 -1U, (CR.CaseBB == CurMBB),
1945 CR.CaseBB, Default, BTC);
1946
1947 if (CR.CaseBB == CurMBB)
1948 visitBitTestHeader(BTB);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001949
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001950 BitTestCases.push_back(BTB);
1951
1952 return true;
1953}
1954
1955
1956/// Clusterify - Transform simple list of Cases into list of CaseRange's
Anton Korobeynikov23218582008-12-23 22:25:27 +00001957size_t SelectionDAGLowering::Clusterify(CaseVector& Cases,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001958 const SwitchInst& SI) {
Anton Korobeynikov23218582008-12-23 22:25:27 +00001959 size_t numCmps = 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001960
1961 // Start with "simple" cases
Anton Korobeynikov23218582008-12-23 22:25:27 +00001962 for (size_t i = 1; i < SI.getNumSuccessors(); ++i) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001963 MachineBasicBlock *SMBB = FuncInfo.MBBMap[SI.getSuccessor(i)];
1964 Cases.push_back(Case(SI.getSuccessorValue(i),
1965 SI.getSuccessorValue(i),
1966 SMBB));
1967 }
1968 std::sort(Cases.begin(), Cases.end(), CaseCmp());
1969
1970 // Merge case into clusters
Anton Korobeynikov23218582008-12-23 22:25:27 +00001971 if (Cases.size() >= 2)
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001972 // Must recompute end() each iteration because it may be
1973 // invalidated by erase if we hold on to it
Anton Korobeynikov23218582008-12-23 22:25:27 +00001974 for (CaseItr I = Cases.begin(), J = ++(Cases.begin()); J != Cases.end(); ) {
1975 const APInt& nextValue = cast<ConstantInt>(J->Low)->getValue();
1976 const APInt& currentValue = cast<ConstantInt>(I->High)->getValue();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001977 MachineBasicBlock* nextBB = J->BB;
1978 MachineBasicBlock* currentBB = I->BB;
1979
1980 // If the two neighboring cases go to the same destination, merge them
1981 // into a single case.
Anton Korobeynikov23218582008-12-23 22:25:27 +00001982 if ((nextValue - currentValue == 1) && (currentBB == nextBB)) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001983 I->High = J->High;
1984 J = Cases.erase(J);
1985 } else {
1986 I = J++;
1987 }
1988 }
1989
1990 for (CaseItr I=Cases.begin(), E=Cases.end(); I!=E; ++I, ++numCmps) {
1991 if (I->Low != I->High)
1992 // A range counts double, since it requires two compares.
1993 ++numCmps;
1994 }
1995
1996 return numCmps;
1997}
1998
Anton Korobeynikov23218582008-12-23 22:25:27 +00001999void SelectionDAGLowering::visitSwitch(SwitchInst &SI) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002000 // Figure out which block is immediately after the current one.
2001 MachineBasicBlock *NextBlock = 0;
2002 MachineFunction::iterator BBI = CurMBB;
2003
2004 MachineBasicBlock *Default = FuncInfo.MBBMap[SI.getDefaultDest()];
2005
2006 // If there is only the default destination, branch to it if it is not the
2007 // next basic block. Otherwise, just fall through.
2008 if (SI.getNumOperands() == 2) {
2009 // Update machine-CFG edges.
2010
2011 // If this is not a fall-through branch, emit the branch.
2012 CurMBB->addSuccessor(Default);
2013 if (Default != NextBlock)
2014 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getControlRoot(),
2015 DAG.getBasicBlock(Default)));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002016 return;
2017 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00002018
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002019 // If there are any non-default case statements, create a vector of Cases
2020 // representing each one, and sort the vector so that we can efficiently
2021 // create a binary search tree from them.
2022 CaseVector Cases;
Anton Korobeynikov23218582008-12-23 22:25:27 +00002023 size_t numCmps = Clusterify(Cases, SI);
Anton Korobeynikov56d245b2008-12-23 22:26:18 +00002024 DEBUG(errs() << "Clusterify finished. Total clusters: " << Cases.size()
2025 << ". Total compares: " << numCmps << '\n');
Devang Patel8a84e442009-01-05 17:31:22 +00002026 numCmps = 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002027
2028 // Get the Value to be switched on and default basic blocks, which will be
2029 // inserted into CaseBlock records, representing basic blocks in the binary
2030 // search tree.
2031 Value *SV = SI.getOperand(0);
2032
2033 // Push the initial CaseRec onto the worklist
2034 CaseRecVector WorkList;
2035 WorkList.push_back(CaseRec(CurMBB,0,0,CaseRange(Cases.begin(),Cases.end())));
2036
2037 while (!WorkList.empty()) {
2038 // Grab a record representing a case range to process off the worklist
2039 CaseRec CR = WorkList.back();
2040 WorkList.pop_back();
2041
2042 if (handleBitTestsSwitchCase(CR, WorkList, SV, Default))
2043 continue;
Anton Korobeynikov23218582008-12-23 22:25:27 +00002044
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002045 // If the range has few cases (two or less) emit a series of specific
2046 // tests.
2047 if (handleSmallSwitchRange(CR, WorkList, SV, Default))
2048 continue;
Anton Korobeynikov23218582008-12-23 22:25:27 +00002049
Anton Korobeynikove2f95e92008-12-23 22:26:01 +00002050 // If the switch has more than 5 blocks, and at least 40% dense, and the
2051 // target supports indirect branches, then emit a jump table rather than
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002052 // lowering the switch to a binary tree of conditional branches.
2053 if (handleJTSwitchCase(CR, WorkList, SV, Default))
2054 continue;
Anton Korobeynikov23218582008-12-23 22:25:27 +00002055
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002056 // Emit binary tree. We need to pick a pivot, and push left and right ranges
2057 // onto the worklist. Leafs are handled via handleSmallSwitchRange() call.
2058 handleBTSplitSwitchCase(CR, WorkList, SV, Default);
2059 }
2060}
2061
2062
2063void SelectionDAGLowering::visitSub(User &I) {
2064 // -0.0 - X --> fneg
2065 const Type *Ty = I.getType();
2066 if (isa<VectorType>(Ty)) {
2067 if (ConstantVector *CV = dyn_cast<ConstantVector>(I.getOperand(0))) {
2068 const VectorType *DestTy = cast<VectorType>(I.getType());
2069 const Type *ElTy = DestTy->getElementType();
2070 if (ElTy->isFloatingPoint()) {
2071 unsigned VL = DestTy->getNumElements();
2072 std::vector<Constant*> NZ(VL, ConstantFP::getNegativeZero(ElTy));
2073 Constant *CNZ = ConstantVector::get(&NZ[0], NZ.size());
2074 if (CV == CNZ) {
2075 SDValue Op2 = getValue(I.getOperand(1));
2076 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
2077 return;
2078 }
2079 }
2080 }
2081 }
2082 if (Ty->isFloatingPoint()) {
2083 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
2084 if (CFP->isExactlyValue(ConstantFP::getNegativeZero(Ty)->getValueAPF())) {
2085 SDValue Op2 = getValue(I.getOperand(1));
2086 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
2087 return;
2088 }
2089 }
2090
2091 visitBinary(I, Ty->isFPOrFPVector() ? ISD::FSUB : ISD::SUB);
2092}
2093
2094void SelectionDAGLowering::visitBinary(User &I, unsigned OpCode) {
2095 SDValue Op1 = getValue(I.getOperand(0));
2096 SDValue Op2 = getValue(I.getOperand(1));
2097
2098 setValue(&I, DAG.getNode(OpCode, Op1.getValueType(), Op1, Op2));
2099}
2100
2101void SelectionDAGLowering::visitShift(User &I, unsigned Opcode) {
2102 SDValue Op1 = getValue(I.getOperand(0));
2103 SDValue Op2 = getValue(I.getOperand(1));
2104 if (!isa<VectorType>(I.getType())) {
2105 if (TLI.getShiftAmountTy().bitsLT(Op2.getValueType()))
2106 Op2 = DAG.getNode(ISD::TRUNCATE, TLI.getShiftAmountTy(), Op2);
2107 else if (TLI.getShiftAmountTy().bitsGT(Op2.getValueType()))
2108 Op2 = DAG.getNode(ISD::ANY_EXTEND, TLI.getShiftAmountTy(), Op2);
2109 }
2110
2111 setValue(&I, DAG.getNode(Opcode, Op1.getValueType(), Op1, Op2));
2112}
2113
2114void SelectionDAGLowering::visitICmp(User &I) {
2115 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
2116 if (ICmpInst *IC = dyn_cast<ICmpInst>(&I))
2117 predicate = IC->getPredicate();
2118 else if (ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
2119 predicate = ICmpInst::Predicate(IC->getPredicate());
2120 SDValue Op1 = getValue(I.getOperand(0));
2121 SDValue Op2 = getValue(I.getOperand(1));
Dan Gohman8c1a6ca2008-10-17 18:18:45 +00002122 ISD::CondCode Opcode = getICmpCondCode(predicate);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002123 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Opcode));
2124}
2125
2126void SelectionDAGLowering::visitFCmp(User &I) {
2127 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
2128 if (FCmpInst *FC = dyn_cast<FCmpInst>(&I))
2129 predicate = FC->getPredicate();
2130 else if (ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
2131 predicate = FCmpInst::Predicate(FC->getPredicate());
2132 SDValue Op1 = getValue(I.getOperand(0));
2133 SDValue Op2 = getValue(I.getOperand(1));
Dan Gohman8c1a6ca2008-10-17 18:18:45 +00002134 ISD::CondCode Condition = getFCmpCondCode(predicate);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002135 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Condition));
2136}
2137
2138void SelectionDAGLowering::visitVICmp(User &I) {
2139 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
2140 if (VICmpInst *IC = dyn_cast<VICmpInst>(&I))
2141 predicate = IC->getPredicate();
2142 else if (ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
2143 predicate = ICmpInst::Predicate(IC->getPredicate());
2144 SDValue Op1 = getValue(I.getOperand(0));
2145 SDValue Op2 = getValue(I.getOperand(1));
Dan Gohman8c1a6ca2008-10-17 18:18:45 +00002146 ISD::CondCode Opcode = getICmpCondCode(predicate);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002147 setValue(&I, DAG.getVSetCC(Op1.getValueType(), Op1, Op2, Opcode));
2148}
2149
2150void SelectionDAGLowering::visitVFCmp(User &I) {
2151 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
2152 if (VFCmpInst *FC = dyn_cast<VFCmpInst>(&I))
2153 predicate = FC->getPredicate();
2154 else if (ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
2155 predicate = FCmpInst::Predicate(FC->getPredicate());
2156 SDValue Op1 = getValue(I.getOperand(0));
2157 SDValue Op2 = getValue(I.getOperand(1));
Dan Gohman8c1a6ca2008-10-17 18:18:45 +00002158 ISD::CondCode Condition = getFCmpCondCode(predicate);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002159 MVT DestVT = TLI.getValueType(I.getType());
2160
2161 setValue(&I, DAG.getVSetCC(DestVT, Op1, Op2, Condition));
2162}
2163
2164void SelectionDAGLowering::visitSelect(User &I) {
Dan Gohman7ea1ca62008-10-21 20:00:42 +00002165 SmallVector<MVT, 4> ValueVTs;
2166 ComputeValueVTs(TLI, I.getType(), ValueVTs);
2167 unsigned NumValues = ValueVTs.size();
2168 if (NumValues != 0) {
2169 SmallVector<SDValue, 4> Values(NumValues);
2170 SDValue Cond = getValue(I.getOperand(0));
2171 SDValue TrueVal = getValue(I.getOperand(1));
2172 SDValue FalseVal = getValue(I.getOperand(2));
2173
2174 for (unsigned i = 0; i != NumValues; ++i)
2175 Values[i] = DAG.getNode(ISD::SELECT, TrueVal.getValueType(), Cond,
2176 SDValue(TrueVal.getNode(), TrueVal.getResNo() + i),
2177 SDValue(FalseVal.getNode(), FalseVal.getResNo() + i));
2178
Duncan Sandsaaffa052008-12-01 11:41:29 +00002179 setValue(&I, DAG.getNode(ISD::MERGE_VALUES,
2180 DAG.getVTList(&ValueVTs[0], NumValues),
2181 &Values[0], NumValues));
Dan Gohman7ea1ca62008-10-21 20:00:42 +00002182 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002183}
2184
2185
2186void SelectionDAGLowering::visitTrunc(User &I) {
2187 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
2188 SDValue N = getValue(I.getOperand(0));
2189 MVT DestVT = TLI.getValueType(I.getType());
2190 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
2191}
2192
2193void SelectionDAGLowering::visitZExt(User &I) {
2194 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2195 // ZExt also can't be a cast to bool for same reason. So, nothing much to do
2196 SDValue N = getValue(I.getOperand(0));
2197 MVT DestVT = TLI.getValueType(I.getType());
2198 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
2199}
2200
2201void SelectionDAGLowering::visitSExt(User &I) {
2202 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2203 // SExt also can't be a cast to bool for same reason. So, nothing much to do
2204 SDValue N = getValue(I.getOperand(0));
2205 MVT DestVT = TLI.getValueType(I.getType());
2206 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, DestVT, N));
2207}
2208
2209void SelectionDAGLowering::visitFPTrunc(User &I) {
2210 // FPTrunc 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_ROUND, DestVT, N, DAG.getIntPtrConstant(0)));
2214}
2215
2216void SelectionDAGLowering::visitFPExt(User &I){
2217 // FPTrunc 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::FP_EXTEND, DestVT, N));
2221}
2222
2223void SelectionDAGLowering::visitFPToUI(User &I) {
2224 // FPToUI is never a no-op cast, no need to check
2225 SDValue N = getValue(I.getOperand(0));
2226 MVT DestVT = TLI.getValueType(I.getType());
2227 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, DestVT, N));
2228}
2229
2230void SelectionDAGLowering::visitFPToSI(User &I) {
2231 // FPToSI is never a no-op cast, no need to check
2232 SDValue N = getValue(I.getOperand(0));
2233 MVT DestVT = TLI.getValueType(I.getType());
2234 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, DestVT, N));
2235}
2236
2237void SelectionDAGLowering::visitUIToFP(User &I) {
2238 // UIToFP is never a no-op cast, no need to check
2239 SDValue N = getValue(I.getOperand(0));
2240 MVT DestVT = TLI.getValueType(I.getType());
2241 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, DestVT, N));
2242}
2243
2244void SelectionDAGLowering::visitSIToFP(User &I){
Bill Wendling181b6272008-10-19 20:34:04 +00002245 // SIToFP is never a no-op cast, no need to check
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002246 SDValue N = getValue(I.getOperand(0));
2247 MVT DestVT = TLI.getValueType(I.getType());
2248 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, DestVT, N));
2249}
2250
2251void SelectionDAGLowering::visitPtrToInt(User &I) {
2252 // What to do depends on the size of the integer and the size of the pointer.
2253 // We can either truncate, zero extend, or no-op, accordingly.
2254 SDValue N = getValue(I.getOperand(0));
2255 MVT SrcVT = N.getValueType();
2256 MVT DestVT = TLI.getValueType(I.getType());
2257 SDValue Result;
2258 if (DestVT.bitsLT(SrcVT))
2259 Result = DAG.getNode(ISD::TRUNCATE, DestVT, N);
2260 else
2261 // Note: ZERO_EXTEND can handle cases where the sizes are equal too
2262 Result = DAG.getNode(ISD::ZERO_EXTEND, DestVT, N);
2263 setValue(&I, Result);
2264}
2265
2266void SelectionDAGLowering::visitIntToPtr(User &I) {
2267 // What to do depends on the size of the integer and the size of the pointer.
2268 // We can either truncate, zero extend, or no-op, accordingly.
2269 SDValue N = getValue(I.getOperand(0));
2270 MVT SrcVT = N.getValueType();
2271 MVT DestVT = TLI.getValueType(I.getType());
2272 if (DestVT.bitsLT(SrcVT))
2273 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
2274 else
2275 // Note: ZERO_EXTEND can handle cases where the sizes are equal too
2276 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
2277}
2278
2279void SelectionDAGLowering::visitBitCast(User &I) {
2280 SDValue N = getValue(I.getOperand(0));
2281 MVT DestVT = TLI.getValueType(I.getType());
2282
2283 // BitCast assures us that source and destination are the same size so this
2284 // is either a BIT_CONVERT or a no-op.
2285 if (DestVT != N.getValueType())
2286 setValue(&I, DAG.getNode(ISD::BIT_CONVERT, DestVT, N)); // convert types
2287 else
2288 setValue(&I, N); // noop cast.
2289}
2290
2291void SelectionDAGLowering::visitInsertElement(User &I) {
2292 SDValue InVec = getValue(I.getOperand(0));
2293 SDValue InVal = getValue(I.getOperand(1));
2294 SDValue InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
2295 getValue(I.getOperand(2)));
2296
2297 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT,
2298 TLI.getValueType(I.getType()),
2299 InVec, InVal, InIdx));
2300}
2301
2302void SelectionDAGLowering::visitExtractElement(User &I) {
2303 SDValue InVec = getValue(I.getOperand(0));
2304 SDValue InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
2305 getValue(I.getOperand(1)));
2306 setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
2307 TLI.getValueType(I.getType()), InVec, InIdx));
2308}
2309
Mon P Wangaeb06d22008-11-10 04:46:22 +00002310
2311// Utility for visitShuffleVector - Returns true if the mask is mask starting
2312// from SIndx and increasing to the element length (undefs are allowed).
2313static bool SequentialMask(SDValue Mask, unsigned SIndx) {
Mon P Wangc7849c22008-11-16 05:06:27 +00002314 unsigned MaskNumElts = Mask.getNumOperands();
2315 for (unsigned i = 0; i != MaskNumElts; ++i) {
Mon P Wangaeb06d22008-11-10 04:46:22 +00002316 if (Mask.getOperand(i).getOpcode() != ISD::UNDEF) {
2317 unsigned Idx = cast<ConstantSDNode>(Mask.getOperand(i))->getZExtValue();
2318 if (Idx != i + SIndx)
2319 return false;
2320 }
2321 }
2322 return true;
2323}
2324
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002325void SelectionDAGLowering::visitShuffleVector(User &I) {
Mon P Wang230e4fa2008-11-21 04:25:21 +00002326 SDValue Src1 = getValue(I.getOperand(0));
2327 SDValue Src2 = getValue(I.getOperand(1));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002328 SDValue Mask = getValue(I.getOperand(2));
2329
Mon P Wangaeb06d22008-11-10 04:46:22 +00002330 MVT VT = TLI.getValueType(I.getType());
Mon P Wang230e4fa2008-11-21 04:25:21 +00002331 MVT SrcVT = Src1.getValueType();
Mon P Wangc7849c22008-11-16 05:06:27 +00002332 int MaskNumElts = Mask.getNumOperands();
2333 int SrcNumElts = SrcVT.getVectorNumElements();
Mon P Wangaeb06d22008-11-10 04:46:22 +00002334
Mon P Wangc7849c22008-11-16 05:06:27 +00002335 if (SrcNumElts == MaskNumElts) {
Mon P Wang230e4fa2008-11-21 04:25:21 +00002336 setValue(&I, DAG.getNode(ISD::VECTOR_SHUFFLE, VT, Src1, Src2, Mask));
Mon P Wangaeb06d22008-11-10 04:46:22 +00002337 return;
2338 }
2339
2340 // Normalize the shuffle vector since mask and vector length don't match.
Mon P Wangc7849c22008-11-16 05:06:27 +00002341 MVT MaskEltVT = Mask.getValueType().getVectorElementType();
2342
2343 if (SrcNumElts < MaskNumElts && MaskNumElts % SrcNumElts == 0) {
2344 // Mask is longer than the source vectors and is a multiple of the source
2345 // vectors. We can use concatenate vector to make the mask and vectors
Mon P Wang230e4fa2008-11-21 04:25:21 +00002346 // lengths match.
Mon P Wangc7849c22008-11-16 05:06:27 +00002347 if (SrcNumElts*2 == MaskNumElts && SequentialMask(Mask, 0)) {
2348 // The shuffle is concatenating two vectors together.
Mon P Wang230e4fa2008-11-21 04:25:21 +00002349 setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, VT, Src1, Src2));
Mon P Wangaeb06d22008-11-10 04:46:22 +00002350 return;
2351 }
2352
Mon P Wangc7849c22008-11-16 05:06:27 +00002353 // Pad both vectors with undefs to make them the same length as the mask.
2354 unsigned NumConcat = MaskNumElts / SrcNumElts;
2355 SDValue UndefVal = DAG.getNode(ISD::UNDEF, SrcVT);
Mon P Wangaeb06d22008-11-10 04:46:22 +00002356
Mon P Wang230e4fa2008-11-21 04:25:21 +00002357 SDValue* MOps1 = new SDValue[NumConcat];
2358 SDValue* MOps2 = new SDValue[NumConcat];
2359 MOps1[0] = Src1;
2360 MOps2[0] = Src2;
Mon P Wangaeb06d22008-11-10 04:46:22 +00002361 for (unsigned i = 1; i != NumConcat; ++i) {
Mon P Wang230e4fa2008-11-21 04:25:21 +00002362 MOps1[i] = UndefVal;
2363 MOps2[i] = UndefVal;
Mon P Wangaeb06d22008-11-10 04:46:22 +00002364 }
Mon P Wang230e4fa2008-11-21 04:25:21 +00002365 Src1 = DAG.getNode(ISD::CONCAT_VECTORS, VT, MOps1, NumConcat);
2366 Src2 = DAG.getNode(ISD::CONCAT_VECTORS, VT, MOps2, NumConcat);
2367
2368 delete [] MOps1;
2369 delete [] MOps2;
2370
Mon P Wangaeb06d22008-11-10 04:46:22 +00002371 // Readjust mask for new input vector length.
2372 SmallVector<SDValue, 8> MappedOps;
Mon P Wangc7849c22008-11-16 05:06:27 +00002373 for (int i = 0; i != MaskNumElts; ++i) {
Mon P Wangaeb06d22008-11-10 04:46:22 +00002374 if (Mask.getOperand(i).getOpcode() == ISD::UNDEF) {
2375 MappedOps.push_back(Mask.getOperand(i));
2376 } else {
Mon P Wangc7849c22008-11-16 05:06:27 +00002377 int Idx = cast<ConstantSDNode>(Mask.getOperand(i))->getZExtValue();
2378 if (Idx < SrcNumElts)
2379 MappedOps.push_back(DAG.getConstant(Idx, MaskEltVT));
2380 else
2381 MappedOps.push_back(DAG.getConstant(Idx + MaskNumElts - SrcNumElts,
2382 MaskEltVT));
Mon P Wangaeb06d22008-11-10 04:46:22 +00002383 }
2384 }
2385 Mask = DAG.getNode(ISD::BUILD_VECTOR, Mask.getValueType(),
2386 &MappedOps[0], MappedOps.size());
2387
Mon P Wang230e4fa2008-11-21 04:25:21 +00002388 setValue(&I, DAG.getNode(ISD::VECTOR_SHUFFLE, VT, Src1, Src2, Mask));
Mon P Wangaeb06d22008-11-10 04:46:22 +00002389 return;
2390 }
2391
Mon P Wangc7849c22008-11-16 05:06:27 +00002392 if (SrcNumElts > MaskNumElts) {
Mon P Wangaeb06d22008-11-10 04:46:22 +00002393 // Resulting vector is shorter than the incoming vector.
Mon P Wangc7849c22008-11-16 05:06:27 +00002394 if (SrcNumElts == MaskNumElts && SequentialMask(Mask,0)) {
Mon P Wangaeb06d22008-11-10 04:46:22 +00002395 // Shuffle extracts 1st vector.
Mon P Wang230e4fa2008-11-21 04:25:21 +00002396 setValue(&I, Src1);
Mon P Wangaeb06d22008-11-10 04:46:22 +00002397 return;
2398 }
2399
Mon P Wangc7849c22008-11-16 05:06:27 +00002400 if (SrcNumElts == MaskNumElts && SequentialMask(Mask,MaskNumElts)) {
Mon P Wangaeb06d22008-11-10 04:46:22 +00002401 // Shuffle extracts 2nd vector.
Mon P Wang230e4fa2008-11-21 04:25:21 +00002402 setValue(&I, Src2);
Mon P Wangaeb06d22008-11-10 04:46:22 +00002403 return;
2404 }
2405
Mon P Wangc7849c22008-11-16 05:06:27 +00002406 // Analyze the access pattern of the vector to see if we can extract
2407 // two subvectors and do the shuffle. The analysis is done by calculating
2408 // the range of elements the mask access on both vectors.
2409 int MinRange[2] = { SrcNumElts+1, SrcNumElts+1};
2410 int MaxRange[2] = {-1, -1};
2411
2412 for (int i = 0; i != MaskNumElts; ++i) {
Mon P Wangaeb06d22008-11-10 04:46:22 +00002413 SDValue Arg = Mask.getOperand(i);
2414 if (Arg.getOpcode() != ISD::UNDEF) {
2415 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
Mon P Wangc7849c22008-11-16 05:06:27 +00002416 int Idx = cast<ConstantSDNode>(Arg)->getZExtValue();
2417 int Input = 0;
2418 if (Idx >= SrcNumElts) {
2419 Input = 1;
2420 Idx -= SrcNumElts;
2421 }
2422 if (Idx > MaxRange[Input])
2423 MaxRange[Input] = Idx;
2424 if (Idx < MinRange[Input])
2425 MinRange[Input] = Idx;
Mon P Wangaeb06d22008-11-10 04:46:22 +00002426 }
2427 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00002428
Mon P Wangc7849c22008-11-16 05:06:27 +00002429 // Check if the access is smaller than the vector size and can we find
2430 // a reasonable extract index.
Mon P Wang230e4fa2008-11-21 04:25:21 +00002431 int RangeUse[2] = { 2, 2 }; // 0 = Unused, 1 = Extract, 2 = Can not Extract.
Mon P Wangc7849c22008-11-16 05:06:27 +00002432 int StartIdx[2]; // StartIdx to extract from
2433 for (int Input=0; Input < 2; ++Input) {
2434 if (MinRange[Input] == SrcNumElts+1 && MaxRange[Input] == -1) {
2435 RangeUse[Input] = 0; // Unused
2436 StartIdx[Input] = 0;
2437 } else if (MaxRange[Input] - MinRange[Input] < MaskNumElts) {
2438 // Fits within range but we should see if we can find a good
Mon P Wang230e4fa2008-11-21 04:25:21 +00002439 // start index that is a multiple of the mask length.
Mon P Wangc7849c22008-11-16 05:06:27 +00002440 if (MaxRange[Input] < MaskNumElts) {
2441 RangeUse[Input] = 1; // Extract from beginning of the vector
2442 StartIdx[Input] = 0;
2443 } else {
2444 StartIdx[Input] = (MinRange[Input]/MaskNumElts)*MaskNumElts;
Mon P Wang6cce3da2008-11-23 04:35:05 +00002445 if (MaxRange[Input] - StartIdx[Input] < MaskNumElts &&
2446 StartIdx[Input] + MaskNumElts < SrcNumElts)
Mon P Wangc7849c22008-11-16 05:06:27 +00002447 RangeUse[Input] = 1; // Extract from a multiple of the mask length.
Mon P Wangc7849c22008-11-16 05:06:27 +00002448 }
Mon P Wang230e4fa2008-11-21 04:25:21 +00002449 }
Mon P Wangc7849c22008-11-16 05:06:27 +00002450 }
2451
2452 if (RangeUse[0] == 0 && RangeUse[0] == 0) {
2453 setValue(&I, DAG.getNode(ISD::UNDEF, VT)); // Vectors are not used.
2454 return;
2455 }
2456 else if (RangeUse[0] < 2 && RangeUse[1] < 2) {
2457 // Extract appropriate subvector and generate a vector shuffle
2458 for (int Input=0; Input < 2; ++Input) {
Mon P Wang230e4fa2008-11-21 04:25:21 +00002459 SDValue& Src = Input == 0 ? Src1 : Src2;
Mon P Wangc7849c22008-11-16 05:06:27 +00002460 if (RangeUse[Input] == 0) {
Mon P Wang230e4fa2008-11-21 04:25:21 +00002461 Src = DAG.getNode(ISD::UNDEF, VT);
Mon P Wangc7849c22008-11-16 05:06:27 +00002462 } else {
Mon P Wang230e4fa2008-11-21 04:25:21 +00002463 Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, VT, Src,
2464 DAG.getIntPtrConstant(StartIdx[Input]));
Mon P Wangc7849c22008-11-16 05:06:27 +00002465 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00002466 }
Mon P Wangc7849c22008-11-16 05:06:27 +00002467 // Calculate new mask.
2468 SmallVector<SDValue, 8> MappedOps;
2469 for (int i = 0; i != MaskNumElts; ++i) {
2470 SDValue Arg = Mask.getOperand(i);
2471 if (Arg.getOpcode() == ISD::UNDEF) {
2472 MappedOps.push_back(Arg);
2473 } else {
2474 int Idx = cast<ConstantSDNode>(Arg)->getZExtValue();
2475 if (Idx < SrcNumElts)
2476 MappedOps.push_back(DAG.getConstant(Idx - StartIdx[0], MaskEltVT));
2477 else {
2478 Idx = Idx - SrcNumElts - StartIdx[1] + MaskNumElts;
2479 MappedOps.push_back(DAG.getConstant(Idx, MaskEltVT));
2480 }
2481 }
2482 }
2483 Mask = DAG.getNode(ISD::BUILD_VECTOR, Mask.getValueType(),
2484 &MappedOps[0], MappedOps.size());
Mon P Wang230e4fa2008-11-21 04:25:21 +00002485 setValue(&I, DAG.getNode(ISD::VECTOR_SHUFFLE, VT, Src1, Src2, Mask));
Mon P Wangc7849c22008-11-16 05:06:27 +00002486 return;
Mon P Wangaeb06d22008-11-10 04:46:22 +00002487 }
2488 }
2489
Mon P Wangc7849c22008-11-16 05:06:27 +00002490 // We can't use either concat vectors or extract subvectors so fall back to
2491 // replacing the shuffle with extract and build vector.
2492 // to insert and build vector.
Mon P Wangaeb06d22008-11-10 04:46:22 +00002493 MVT EltVT = VT.getVectorElementType();
2494 MVT PtrVT = TLI.getPointerTy();
2495 SmallVector<SDValue,8> Ops;
Mon P Wangc7849c22008-11-16 05:06:27 +00002496 for (int i = 0; i != MaskNumElts; ++i) {
Mon P Wangaeb06d22008-11-10 04:46:22 +00002497 SDValue Arg = Mask.getOperand(i);
2498 if (Arg.getOpcode() == ISD::UNDEF) {
2499 Ops.push_back(DAG.getNode(ISD::UNDEF, EltVT));
2500 } else {
2501 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
Mon P Wangc7849c22008-11-16 05:06:27 +00002502 int Idx = cast<ConstantSDNode>(Arg)->getZExtValue();
2503 if (Idx < SrcNumElts)
Mon P Wang230e4fa2008-11-21 04:25:21 +00002504 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, EltVT, Src1,
Mon P Wangaeb06d22008-11-10 04:46:22 +00002505 DAG.getConstant(Idx, PtrVT)));
2506 else
Mon P Wang230e4fa2008-11-21 04:25:21 +00002507 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, EltVT, Src2,
Mon P Wangc7849c22008-11-16 05:06:27 +00002508 DAG.getConstant(Idx - SrcNumElts, PtrVT)));
Mon P Wangaeb06d22008-11-10 04:46:22 +00002509 }
2510 }
2511 setValue(&I, DAG.getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size()));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002512}
2513
2514void SelectionDAGLowering::visitInsertValue(InsertValueInst &I) {
2515 const Value *Op0 = I.getOperand(0);
2516 const Value *Op1 = I.getOperand(1);
2517 const Type *AggTy = I.getType();
2518 const Type *ValTy = Op1->getType();
2519 bool IntoUndef = isa<UndefValue>(Op0);
2520 bool FromUndef = isa<UndefValue>(Op1);
2521
2522 unsigned LinearIndex = ComputeLinearIndex(TLI, AggTy,
2523 I.idx_begin(), I.idx_end());
2524
2525 SmallVector<MVT, 4> AggValueVTs;
2526 ComputeValueVTs(TLI, AggTy, AggValueVTs);
2527 SmallVector<MVT, 4> ValValueVTs;
2528 ComputeValueVTs(TLI, ValTy, ValValueVTs);
2529
2530 unsigned NumAggValues = AggValueVTs.size();
2531 unsigned NumValValues = ValValueVTs.size();
2532 SmallVector<SDValue, 4> Values(NumAggValues);
2533
2534 SDValue Agg = getValue(Op0);
2535 SDValue Val = getValue(Op1);
2536 unsigned i = 0;
2537 // Copy the beginning value(s) from the original aggregate.
2538 for (; i != LinearIndex; ++i)
2539 Values[i] = IntoUndef ? DAG.getNode(ISD::UNDEF, AggValueVTs[i]) :
2540 SDValue(Agg.getNode(), Agg.getResNo() + i);
2541 // Copy values from the inserted value(s).
2542 for (; i != LinearIndex + NumValValues; ++i)
2543 Values[i] = FromUndef ? DAG.getNode(ISD::UNDEF, AggValueVTs[i]) :
2544 SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
2545 // Copy remaining value(s) from the original aggregate.
2546 for (; i != NumAggValues; ++i)
2547 Values[i] = IntoUndef ? DAG.getNode(ISD::UNDEF, AggValueVTs[i]) :
2548 SDValue(Agg.getNode(), Agg.getResNo() + i);
2549
Duncan Sandsaaffa052008-12-01 11:41:29 +00002550 setValue(&I, DAG.getNode(ISD::MERGE_VALUES,
2551 DAG.getVTList(&AggValueVTs[0], NumAggValues),
2552 &Values[0], NumAggValues));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002553}
2554
2555void SelectionDAGLowering::visitExtractValue(ExtractValueInst &I) {
2556 const Value *Op0 = I.getOperand(0);
2557 const Type *AggTy = Op0->getType();
2558 const Type *ValTy = I.getType();
2559 bool OutOfUndef = isa<UndefValue>(Op0);
2560
2561 unsigned LinearIndex = ComputeLinearIndex(TLI, AggTy,
2562 I.idx_begin(), I.idx_end());
2563
2564 SmallVector<MVT, 4> ValValueVTs;
2565 ComputeValueVTs(TLI, ValTy, ValValueVTs);
2566
2567 unsigned NumValValues = ValValueVTs.size();
2568 SmallVector<SDValue, 4> Values(NumValValues);
2569
2570 SDValue Agg = getValue(Op0);
2571 // Copy out the selected value(s).
2572 for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
2573 Values[i - LinearIndex] =
Bill Wendlingf0a2d0c2008-11-20 07:24:30 +00002574 OutOfUndef ?
2575 DAG.getNode(ISD::UNDEF,
2576 Agg.getNode()->getValueType(Agg.getResNo() + i)) :
2577 SDValue(Agg.getNode(), Agg.getResNo() + i);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002578
Duncan Sandsaaffa052008-12-01 11:41:29 +00002579 setValue(&I, DAG.getNode(ISD::MERGE_VALUES,
2580 DAG.getVTList(&ValValueVTs[0], NumValValues),
2581 &Values[0], NumValValues));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002582}
2583
2584
2585void SelectionDAGLowering::visitGetElementPtr(User &I) {
2586 SDValue N = getValue(I.getOperand(0));
2587 const Type *Ty = I.getOperand(0)->getType();
2588
2589 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
2590 OI != E; ++OI) {
2591 Value *Idx = *OI;
2592 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
2593 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
2594 if (Field) {
2595 // N = N + Offset
2596 uint64_t Offset = TD->getStructLayout(StTy)->getElementOffset(Field);
2597 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
2598 DAG.getIntPtrConstant(Offset));
2599 }
2600 Ty = StTy->getElementType(Field);
2601 } else {
2602 Ty = cast<SequentialType>(Ty)->getElementType();
2603
2604 // If this is a constant subscript, handle it quickly.
2605 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
2606 if (CI->getZExtValue() == 0) continue;
2607 uint64_t Offs =
Duncan Sandsceb4d1a2009-01-12 20:38:59 +00002608 TD->getTypePaddedSize(Ty)*cast<ConstantInt>(CI)->getSExtValue();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002609 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
2610 DAG.getIntPtrConstant(Offs));
2611 continue;
2612 }
2613
2614 // N = N + Idx * ElementSize;
Duncan Sandsceb4d1a2009-01-12 20:38:59 +00002615 uint64_t ElementSize = TD->getTypePaddedSize(Ty);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002616 SDValue IdxN = getValue(Idx);
2617
2618 // If the index is smaller or larger than intptr_t, truncate or extend
2619 // it.
2620 if (IdxN.getValueType().bitsLT(N.getValueType()))
2621 IdxN = DAG.getNode(ISD::SIGN_EXTEND, N.getValueType(), IdxN);
2622 else if (IdxN.getValueType().bitsGT(N.getValueType()))
2623 IdxN = DAG.getNode(ISD::TRUNCATE, N.getValueType(), IdxN);
2624
2625 // If this is a multiply by a power of two, turn it into a shl
2626 // immediately. This is a very common case.
2627 if (ElementSize != 1) {
2628 if (isPowerOf2_64(ElementSize)) {
2629 unsigned Amt = Log2_64(ElementSize);
2630 IdxN = DAG.getNode(ISD::SHL, N.getValueType(), IdxN,
2631 DAG.getConstant(Amt, TLI.getShiftAmountTy()));
2632 } else {
2633 SDValue Scale = DAG.getIntPtrConstant(ElementSize);
2634 IdxN = DAG.getNode(ISD::MUL, N.getValueType(), IdxN, Scale);
2635 }
2636 }
2637
2638 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
2639 }
2640 }
2641 setValue(&I, N);
2642}
2643
2644void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
2645 // If this is a fixed sized alloca in the entry block of the function,
2646 // allocate it statically on the stack.
2647 if (FuncInfo.StaticAllocaMap.count(&I))
2648 return; // getValue will auto-populate this.
2649
2650 const Type *Ty = I.getAllocatedType();
Duncan Sandsceb4d1a2009-01-12 20:38:59 +00002651 uint64_t TySize = TLI.getTargetData()->getTypePaddedSize(Ty);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002652 unsigned Align =
2653 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
2654 I.getAlignment());
2655
2656 SDValue AllocSize = getValue(I.getArraySize());
2657 MVT IntPtr = TLI.getPointerTy();
2658 if (IntPtr.bitsLT(AllocSize.getValueType()))
2659 AllocSize = DAG.getNode(ISD::TRUNCATE, IntPtr, AllocSize);
2660 else if (IntPtr.bitsGT(AllocSize.getValueType()))
2661 AllocSize = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, AllocSize);
2662
2663 AllocSize = DAG.getNode(ISD::MUL, IntPtr, AllocSize,
2664 DAG.getIntPtrConstant(TySize));
2665
2666 // Handle alignment. If the requested alignment is less than or equal to
2667 // the stack alignment, ignore it. If the size is greater than or equal to
2668 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
2669 unsigned StackAlign =
2670 TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
2671 if (Align <= StackAlign)
2672 Align = 0;
2673
2674 // Round the size of the allocation up to the stack alignment size
2675 // by add SA-1 to the size.
2676 AllocSize = DAG.getNode(ISD::ADD, AllocSize.getValueType(), AllocSize,
2677 DAG.getIntPtrConstant(StackAlign-1));
2678 // Mask out the low bits for alignment purposes.
2679 AllocSize = DAG.getNode(ISD::AND, AllocSize.getValueType(), AllocSize,
2680 DAG.getIntPtrConstant(~(uint64_t)(StackAlign-1)));
2681
2682 SDValue Ops[] = { getRoot(), AllocSize, DAG.getIntPtrConstant(Align) };
2683 const MVT *VTs = DAG.getNodeValueTypes(AllocSize.getValueType(),
2684 MVT::Other);
2685 SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, VTs, 2, Ops, 3);
2686 setValue(&I, DSA);
2687 DAG.setRoot(DSA.getValue(1));
2688
2689 // Inform the Frame Information that we have just allocated a variable-sized
2690 // object.
2691 CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
2692}
2693
2694void SelectionDAGLowering::visitLoad(LoadInst &I) {
2695 const Value *SV = I.getOperand(0);
2696 SDValue Ptr = getValue(SV);
2697
2698 const Type *Ty = I.getType();
2699 bool isVolatile = I.isVolatile();
2700 unsigned Alignment = I.getAlignment();
2701
2702 SmallVector<MVT, 4> ValueVTs;
2703 SmallVector<uint64_t, 4> Offsets;
2704 ComputeValueVTs(TLI, Ty, ValueVTs, &Offsets);
2705 unsigned NumValues = ValueVTs.size();
2706 if (NumValues == 0)
2707 return;
2708
2709 SDValue Root;
2710 bool ConstantMemory = false;
2711 if (I.isVolatile())
2712 // Serialize volatile loads with other side effects.
2713 Root = getRoot();
2714 else if (AA->pointsToConstantMemory(SV)) {
2715 // Do not serialize (non-volatile) loads of constant memory with anything.
2716 Root = DAG.getEntryNode();
2717 ConstantMemory = true;
2718 } else {
2719 // Do not serialize non-volatile loads against each other.
2720 Root = DAG.getRoot();
2721 }
2722
2723 SmallVector<SDValue, 4> Values(NumValues);
2724 SmallVector<SDValue, 4> Chains(NumValues);
2725 MVT PtrVT = Ptr.getValueType();
2726 for (unsigned i = 0; i != NumValues; ++i) {
2727 SDValue L = DAG.getLoad(ValueVTs[i], Root,
2728 DAG.getNode(ISD::ADD, PtrVT, Ptr,
2729 DAG.getConstant(Offsets[i], PtrVT)),
2730 SV, Offsets[i],
2731 isVolatile, Alignment);
2732 Values[i] = L;
2733 Chains[i] = L.getValue(1);
2734 }
2735
2736 if (!ConstantMemory) {
2737 SDValue Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
2738 &Chains[0], NumValues);
2739 if (isVolatile)
2740 DAG.setRoot(Chain);
2741 else
2742 PendingLoads.push_back(Chain);
2743 }
2744
Duncan Sandsaaffa052008-12-01 11:41:29 +00002745 setValue(&I, DAG.getNode(ISD::MERGE_VALUES,
2746 DAG.getVTList(&ValueVTs[0], NumValues),
2747 &Values[0], NumValues));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002748}
2749
2750
2751void SelectionDAGLowering::visitStore(StoreInst &I) {
2752 Value *SrcV = I.getOperand(0);
2753 Value *PtrV = I.getOperand(1);
2754
2755 SmallVector<MVT, 4> ValueVTs;
2756 SmallVector<uint64_t, 4> Offsets;
2757 ComputeValueVTs(TLI, SrcV->getType(), ValueVTs, &Offsets);
2758 unsigned NumValues = ValueVTs.size();
2759 if (NumValues == 0)
2760 return;
2761
2762 // Get the lowered operands. Note that we do this after
2763 // checking if NumResults is zero, because with zero results
2764 // the operands won't have values in the map.
2765 SDValue Src = getValue(SrcV);
2766 SDValue Ptr = getValue(PtrV);
2767
2768 SDValue Root = getRoot();
2769 SmallVector<SDValue, 4> Chains(NumValues);
2770 MVT PtrVT = Ptr.getValueType();
2771 bool isVolatile = I.isVolatile();
2772 unsigned Alignment = I.getAlignment();
2773 for (unsigned i = 0; i != NumValues; ++i)
2774 Chains[i] = DAG.getStore(Root, SDValue(Src.getNode(), Src.getResNo() + i),
2775 DAG.getNode(ISD::ADD, PtrVT, Ptr,
2776 DAG.getConstant(Offsets[i], PtrVT)),
2777 PtrV, Offsets[i],
2778 isVolatile, Alignment);
2779
2780 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other, &Chains[0], NumValues));
2781}
2782
2783/// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
2784/// node.
2785void SelectionDAGLowering::visitTargetIntrinsic(CallInst &I,
2786 unsigned Intrinsic) {
2787 bool HasChain = !I.doesNotAccessMemory();
2788 bool OnlyLoad = HasChain && I.onlyReadsMemory();
2789
2790 // Build the operand list.
2791 SmallVector<SDValue, 8> Ops;
2792 if (HasChain) { // If this intrinsic has side-effects, chainify it.
2793 if (OnlyLoad) {
2794 // We don't need to serialize loads against other loads.
2795 Ops.push_back(DAG.getRoot());
2796 } else {
2797 Ops.push_back(getRoot());
2798 }
2799 }
Mon P Wang3efcd4a2008-11-01 20:24:53 +00002800
2801 // Info is set by getTgtMemInstrinsic
2802 TargetLowering::IntrinsicInfo Info;
2803 bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I, Intrinsic);
2804
2805 // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
2806 if (!IsTgtIntrinsic)
2807 Ops.push_back(DAG.getConstant(Intrinsic, TLI.getPointerTy()));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002808
2809 // Add all operands of the call to the operand list.
2810 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
2811 SDValue Op = getValue(I.getOperand(i));
2812 assert(TLI.isTypeLegal(Op.getValueType()) &&
2813 "Intrinsic uses a non-legal type?");
2814 Ops.push_back(Op);
2815 }
2816
2817 std::vector<MVT> VTs;
2818 if (I.getType() != Type::VoidTy) {
2819 MVT VT = TLI.getValueType(I.getType());
2820 if (VT.isVector()) {
2821 const VectorType *DestTy = cast<VectorType>(I.getType());
2822 MVT EltVT = TLI.getValueType(DestTy->getElementType());
2823
2824 VT = MVT::getVectorVT(EltVT, DestTy->getNumElements());
2825 assert(VT != MVT::Other && "Intrinsic uses a non-legal type?");
2826 }
2827
2828 assert(TLI.isTypeLegal(VT) && "Intrinsic uses a non-legal type?");
2829 VTs.push_back(VT);
2830 }
2831 if (HasChain)
2832 VTs.push_back(MVT::Other);
2833
2834 const MVT *VTList = DAG.getNodeValueTypes(VTs);
2835
2836 // Create the node.
2837 SDValue Result;
Mon P Wang3efcd4a2008-11-01 20:24:53 +00002838 if (IsTgtIntrinsic) {
2839 // This is target intrinsic that touches memory
2840 Result = DAG.getMemIntrinsicNode(Info.opc, VTList, VTs.size(),
2841 &Ops[0], Ops.size(),
2842 Info.memVT, Info.ptrVal, Info.offset,
2843 Info.align, Info.vol,
2844 Info.readMem, Info.writeMem);
2845 }
2846 else if (!HasChain)
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002847 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VTList, VTs.size(),
2848 &Ops[0], Ops.size());
2849 else if (I.getType() != Type::VoidTy)
2850 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, VTList, VTs.size(),
2851 &Ops[0], Ops.size());
2852 else
2853 Result = DAG.getNode(ISD::INTRINSIC_VOID, VTList, VTs.size(),
2854 &Ops[0], Ops.size());
2855
2856 if (HasChain) {
2857 SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
2858 if (OnlyLoad)
2859 PendingLoads.push_back(Chain);
2860 else
2861 DAG.setRoot(Chain);
2862 }
2863 if (I.getType() != Type::VoidTy) {
2864 if (const VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
2865 MVT VT = TLI.getValueType(PTy);
2866 Result = DAG.getNode(ISD::BIT_CONVERT, VT, Result);
2867 }
2868 setValue(&I, Result);
2869 }
2870}
2871
2872/// ExtractTypeInfo - Returns the type info, possibly bitcast, encoded in V.
2873static GlobalVariable *ExtractTypeInfo(Value *V) {
2874 V = V->stripPointerCasts();
2875 GlobalVariable *GV = dyn_cast<GlobalVariable>(V);
2876 assert ((GV || isa<ConstantPointerNull>(V)) &&
2877 "TypeInfo must be a global variable or NULL");
2878 return GV;
2879}
2880
2881namespace llvm {
2882
2883/// AddCatchInfo - Extract the personality and type infos from an eh.selector
2884/// call, and add them to the specified machine basic block.
2885void AddCatchInfo(CallInst &I, MachineModuleInfo *MMI,
2886 MachineBasicBlock *MBB) {
2887 // Inform the MachineModuleInfo of the personality for this landing pad.
2888 ConstantExpr *CE = cast<ConstantExpr>(I.getOperand(2));
2889 assert(CE->getOpcode() == Instruction::BitCast &&
2890 isa<Function>(CE->getOperand(0)) &&
2891 "Personality should be a function");
2892 MMI->addPersonality(MBB, cast<Function>(CE->getOperand(0)));
2893
2894 // Gather all the type infos for this landing pad and pass them along to
2895 // MachineModuleInfo.
2896 std::vector<GlobalVariable *> TyInfo;
2897 unsigned N = I.getNumOperands();
2898
2899 for (unsigned i = N - 1; i > 2; --i) {
2900 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(i))) {
2901 unsigned FilterLength = CI->getZExtValue();
2902 unsigned FirstCatch = i + FilterLength + !FilterLength;
2903 assert (FirstCatch <= N && "Invalid filter length");
2904
2905 if (FirstCatch < N) {
2906 TyInfo.reserve(N - FirstCatch);
2907 for (unsigned j = FirstCatch; j < N; ++j)
2908 TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
2909 MMI->addCatchTypeInfo(MBB, TyInfo);
2910 TyInfo.clear();
2911 }
2912
2913 if (!FilterLength) {
2914 // Cleanup.
2915 MMI->addCleanup(MBB);
2916 } else {
2917 // Filter.
2918 TyInfo.reserve(FilterLength - 1);
2919 for (unsigned j = i + 1; j < FirstCatch; ++j)
2920 TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
2921 MMI->addFilterTypeInfo(MBB, TyInfo);
2922 TyInfo.clear();
2923 }
2924
2925 N = i;
2926 }
2927 }
2928
2929 if (N > 3) {
2930 TyInfo.reserve(N - 3);
2931 for (unsigned j = 3; j < N; ++j)
2932 TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
2933 MMI->addCatchTypeInfo(MBB, TyInfo);
2934 }
2935}
2936
2937}
2938
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00002939/// GetSignificand - Get the significand and build it into a floating-point
2940/// number with exponent of 1:
2941///
2942/// Op = (Op & 0x007fffff) | 0x3f800000;
2943///
2944/// where Op is the hexidecimal representation of floating point value.
Bill Wendling39150252008-09-09 20:39:27 +00002945static SDValue
2946GetSignificand(SelectionDAG &DAG, SDValue Op) {
2947 SDValue t1 = DAG.getNode(ISD::AND, MVT::i32, Op,
2948 DAG.getConstant(0x007fffff, MVT::i32));
2949 SDValue t2 = DAG.getNode(ISD::OR, MVT::i32, t1,
2950 DAG.getConstant(0x3f800000, MVT::i32));
2951 return DAG.getNode(ISD::BIT_CONVERT, MVT::f32, t2);
2952}
2953
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00002954/// GetExponent - Get the exponent:
2955///
2956/// (float)((Op1 >> 23) - 127);
2957///
2958/// where Op is the hexidecimal representation of floating point value.
Bill Wendling39150252008-09-09 20:39:27 +00002959static SDValue
2960GetExponent(SelectionDAG &DAG, SDValue Op) {
Bill Wendlingfc2508e2008-09-10 06:26:10 +00002961 SDValue t1 = DAG.getNode(ISD::SRL, MVT::i32, Op,
Bill Wendling39150252008-09-09 20:39:27 +00002962 DAG.getConstant(23, MVT::i32));
Bill Wendlingfc2508e2008-09-10 06:26:10 +00002963 SDValue t2 = DAG.getNode(ISD::SUB, MVT::i32, t1,
Bill Wendling39150252008-09-09 20:39:27 +00002964 DAG.getConstant(127, MVT::i32));
Bill Wendlingfc2508e2008-09-10 06:26:10 +00002965 return DAG.getNode(ISD::UINT_TO_FP, MVT::f32, t2);
Bill Wendling39150252008-09-09 20:39:27 +00002966}
2967
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00002968/// getF32Constant - Get 32-bit floating point constant.
2969static SDValue
2970getF32Constant(SelectionDAG &DAG, unsigned Flt) {
2971 return DAG.getConstantFP(APFloat(APInt(32, Flt)), MVT::f32);
2972}
2973
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002974/// Inlined utility function to implement binary input atomic intrinsics for
2975/// visitIntrinsicCall: I is a call instruction
2976/// Op is the associated NodeType for I
2977const char *
2978SelectionDAGLowering::implVisitBinaryAtomic(CallInst& I, ISD::NodeType Op) {
2979 SDValue Root = getRoot();
Dan Gohman0b1d4a72008-12-23 21:37:04 +00002980 SDValue L =
2981 DAG.getAtomic(Op, getValue(I.getOperand(2)).getValueType().getSimpleVT(),
2982 Root,
2983 getValue(I.getOperand(1)),
2984 getValue(I.getOperand(2)),
2985 I.getOperand(1));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002986 setValue(&I, L);
2987 DAG.setRoot(L.getValue(1));
2988 return 0;
2989}
2990
Bill Wendling2ce4e5c2008-12-10 00:28:22 +00002991// implVisitAluOverflow - Lower arithmetic overflow instrinsics.
Bill Wendling74c37652008-12-09 22:08:41 +00002992const char *
2993SelectionDAGLowering::implVisitAluOverflow(CallInst &I, ISD::NodeType Op) {
Bill Wendling2ce4e5c2008-12-10 00:28:22 +00002994 SDValue Op1 = getValue(I.getOperand(1));
2995 SDValue Op2 = getValue(I.getOperand(2));
Bill Wendling74c37652008-12-09 22:08:41 +00002996
Bill Wendling2ce4e5c2008-12-10 00:28:22 +00002997 MVT ValueVTs[] = { Op1.getValueType(), MVT::i1 };
2998 SDValue Ops[] = { Op1, Op2 };
Bill Wendling74c37652008-12-09 22:08:41 +00002999
Bill Wendling2ce4e5c2008-12-10 00:28:22 +00003000 SDValue Result = DAG.getNode(Op, DAG.getVTList(&ValueVTs[0], 2), &Ops[0], 2);
Bill Wendling74c37652008-12-09 22:08:41 +00003001
Bill Wendling2ce4e5c2008-12-10 00:28:22 +00003002 setValue(&I, Result);
3003 return 0;
3004}
Bill Wendling74c37652008-12-09 22:08:41 +00003005
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003006/// visitExp - Lower an exp intrinsic. Handles the special sequences for
3007/// limited-precision mode.
Dale Johannesen59e577f2008-09-05 18:38:42 +00003008void
3009SelectionDAGLowering::visitExp(CallInst &I) {
3010 SDValue result;
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003011
3012 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
3013 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3014 SDValue Op = getValue(I.getOperand(1));
3015
3016 // Put the exponent in the right bit position for later addition to the
3017 // final result:
3018 //
3019 // #define LOG2OFe 1.4426950f
3020 // IntegerPartOfX = ((int32_t)(X * LOG2OFe));
3021 SDValue t0 = DAG.getNode(ISD::FMUL, MVT::f32, Op,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003022 getF32Constant(DAG, 0x3fb8aa3b));
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003023 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, MVT::i32, t0);
3024
3025 // FractionalPartOfX = (X * LOG2OFe) - (float)IntegerPartOfX;
3026 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, MVT::f32, IntegerPartOfX);
3027 SDValue X = DAG.getNode(ISD::FSUB, MVT::f32, t0, t1);
3028
3029 // IntegerPartOfX <<= 23;
3030 IntegerPartOfX = DAG.getNode(ISD::SHL, MVT::i32, IntegerPartOfX,
3031 DAG.getConstant(23, MVT::i32));
3032
3033 if (LimitFloatPrecision <= 6) {
3034 // For floating-point precision of 6:
3035 //
3036 // TwoToFractionalPartOfX =
3037 // 0.997535578f +
3038 // (0.735607626f + 0.252464424f * x) * x;
3039 //
3040 // error 0.0144103317, which is 6 bits
3041 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003042 getF32Constant(DAG, 0x3e814304));
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003043 SDValue t3 = DAG.getNode(ISD::FADD, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003044 getF32Constant(DAG, 0x3f3c50c8));
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003045 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3046 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003047 getF32Constant(DAG, 0x3f7f5e7e));
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003048 SDValue TwoToFracPartOfX = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, t5);
3049
3050 // Add the exponent into the result in integer domain.
3051 SDValue t6 = DAG.getNode(ISD::ADD, MVT::i32,
3052 TwoToFracPartOfX, IntegerPartOfX);
3053
3054 result = DAG.getNode(ISD::BIT_CONVERT, MVT::f32, t6);
3055 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3056 // For floating-point precision of 12:
3057 //
3058 // TwoToFractionalPartOfX =
3059 // 0.999892986f +
3060 // (0.696457318f +
3061 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
3062 //
3063 // 0.000107046256 error, which is 13 to 14 bits
3064 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003065 getF32Constant(DAG, 0x3da235e3));
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003066 SDValue t3 = DAG.getNode(ISD::FADD, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003067 getF32Constant(DAG, 0x3e65b8f3));
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003068 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3069 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003070 getF32Constant(DAG, 0x3f324b07));
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003071 SDValue t6 = DAG.getNode(ISD::FMUL, MVT::f32, t5, X);
3072 SDValue t7 = DAG.getNode(ISD::FADD, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003073 getF32Constant(DAG, 0x3f7ff8fd));
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003074 SDValue TwoToFracPartOfX = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, t7);
3075
3076 // Add the exponent into the result in integer domain.
3077 SDValue t8 = DAG.getNode(ISD::ADD, MVT::i32,
3078 TwoToFracPartOfX, IntegerPartOfX);
3079
3080 result = DAG.getNode(ISD::BIT_CONVERT, MVT::f32, t8);
3081 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3082 // For floating-point precision of 18:
3083 //
3084 // TwoToFractionalPartOfX =
3085 // 0.999999982f +
3086 // (0.693148872f +
3087 // (0.240227044f +
3088 // (0.554906021e-1f +
3089 // (0.961591928e-2f +
3090 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
3091 //
3092 // error 2.47208000*10^(-7), which is better than 18 bits
3093 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003094 getF32Constant(DAG, 0x3924b03e));
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003095 SDValue t3 = DAG.getNode(ISD::FADD, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003096 getF32Constant(DAG, 0x3ab24b87));
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003097 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3098 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003099 getF32Constant(DAG, 0x3c1d8c17));
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003100 SDValue t6 = DAG.getNode(ISD::FMUL, MVT::f32, t5, X);
3101 SDValue t7 = DAG.getNode(ISD::FADD, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003102 getF32Constant(DAG, 0x3d634a1d));
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003103 SDValue t8 = DAG.getNode(ISD::FMUL, MVT::f32, t7, X);
3104 SDValue t9 = DAG.getNode(ISD::FADD, MVT::f32, t8,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003105 getF32Constant(DAG, 0x3e75fe14));
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003106 SDValue t10 = DAG.getNode(ISD::FMUL, MVT::f32, t9, X);
3107 SDValue t11 = DAG.getNode(ISD::FADD, MVT::f32, t10,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003108 getF32Constant(DAG, 0x3f317234));
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003109 SDValue t12 = DAG.getNode(ISD::FMUL, MVT::f32, t11, X);
3110 SDValue t13 = DAG.getNode(ISD::FADD, MVT::f32, t12,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003111 getF32Constant(DAG, 0x3f800000));
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003112 SDValue TwoToFracPartOfX = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, t13);
3113
3114 // Add the exponent into the result in integer domain.
3115 SDValue t14 = DAG.getNode(ISD::ADD, MVT::i32,
3116 TwoToFracPartOfX, IntegerPartOfX);
3117
3118 result = DAG.getNode(ISD::BIT_CONVERT, MVT::f32, t14);
3119 }
3120 } else {
3121 // No special expansion.
3122 result = DAG.getNode(ISD::FEXP,
3123 getValue(I.getOperand(1)).getValueType(),
3124 getValue(I.getOperand(1)));
3125 }
3126
Dale Johannesen59e577f2008-09-05 18:38:42 +00003127 setValue(&I, result);
3128}
3129
Bill Wendling39150252008-09-09 20:39:27 +00003130/// visitLog - Lower a log intrinsic. Handles the special sequences for
3131/// limited-precision mode.
Dale Johannesen59e577f2008-09-05 18:38:42 +00003132void
3133SelectionDAGLowering::visitLog(CallInst &I) {
3134 SDValue result;
Bill Wendling39150252008-09-09 20:39:27 +00003135
3136 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
3137 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3138 SDValue Op = getValue(I.getOperand(1));
3139 SDValue Op1 = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, Op);
3140
3141 // Scale the exponent by log(2) [0.69314718f].
3142 SDValue Exp = GetExponent(DAG, Op1);
3143 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, MVT::f32, Exp,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003144 getF32Constant(DAG, 0x3f317218));
Bill Wendling39150252008-09-09 20:39:27 +00003145
3146 // Get the significand and build it into a floating-point number with
3147 // exponent of 1.
3148 SDValue X = GetSignificand(DAG, Op1);
3149
3150 if (LimitFloatPrecision <= 6) {
3151 // For floating-point precision of 6:
3152 //
3153 // LogofMantissa =
3154 // -1.1609546f +
3155 // (1.4034025f - 0.23903021f * x) * x;
3156 //
3157 // error 0.0034276066, which is better than 8 bits
3158 SDValue t0 = DAG.getNode(ISD::FMUL, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003159 getF32Constant(DAG, 0xbe74c456));
Bill Wendling39150252008-09-09 20:39:27 +00003160 SDValue t1 = DAG.getNode(ISD::FADD, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003161 getF32Constant(DAG, 0x3fb3a2b1));
Bill Wendling39150252008-09-09 20:39:27 +00003162 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, t1, X);
3163 SDValue LogOfMantissa = DAG.getNode(ISD::FSUB, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003164 getF32Constant(DAG, 0x3f949a29));
Bill Wendling39150252008-09-09 20:39:27 +00003165
3166 result = DAG.getNode(ISD::FADD, MVT::f32, LogOfExponent, LogOfMantissa);
3167 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3168 // For floating-point precision of 12:
3169 //
3170 // LogOfMantissa =
3171 // -1.7417939f +
3172 // (2.8212026f +
3173 // (-1.4699568f +
3174 // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
3175 //
3176 // error 0.000061011436, which is 14 bits
3177 SDValue t0 = DAG.getNode(ISD::FMUL, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003178 getF32Constant(DAG, 0xbd67b6d6));
Bill Wendling39150252008-09-09 20:39:27 +00003179 SDValue t1 = DAG.getNode(ISD::FADD, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003180 getF32Constant(DAG, 0x3ee4f4b8));
Bill Wendling39150252008-09-09 20:39:27 +00003181 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, t1, X);
3182 SDValue t3 = DAG.getNode(ISD::FSUB, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003183 getF32Constant(DAG, 0x3fbc278b));
Bill Wendling39150252008-09-09 20:39:27 +00003184 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3185 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003186 getF32Constant(DAG, 0x40348e95));
Bill Wendling39150252008-09-09 20:39:27 +00003187 SDValue t6 = DAG.getNode(ISD::FMUL, MVT::f32, t5, X);
3188 SDValue LogOfMantissa = DAG.getNode(ISD::FSUB, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003189 getF32Constant(DAG, 0x3fdef31a));
Bill Wendling39150252008-09-09 20:39:27 +00003190
3191 result = DAG.getNode(ISD::FADD, MVT::f32, LogOfExponent, LogOfMantissa);
3192 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3193 // For floating-point precision of 18:
3194 //
3195 // LogOfMantissa =
3196 // -2.1072184f +
3197 // (4.2372794f +
3198 // (-3.7029485f +
3199 // (2.2781945f +
3200 // (-0.87823314f +
3201 // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
3202 //
3203 // error 0.0000023660568, which is better than 18 bits
3204 SDValue t0 = DAG.getNode(ISD::FMUL, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003205 getF32Constant(DAG, 0xbc91e5ac));
Bill Wendling39150252008-09-09 20:39:27 +00003206 SDValue t1 = DAG.getNode(ISD::FADD, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003207 getF32Constant(DAG, 0x3e4350aa));
Bill Wendling39150252008-09-09 20:39:27 +00003208 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, t1, X);
3209 SDValue t3 = DAG.getNode(ISD::FSUB, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003210 getF32Constant(DAG, 0x3f60d3e3));
Bill Wendling39150252008-09-09 20:39:27 +00003211 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3212 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003213 getF32Constant(DAG, 0x4011cdf0));
Bill Wendling39150252008-09-09 20:39:27 +00003214 SDValue t6 = DAG.getNode(ISD::FMUL, MVT::f32, t5, X);
3215 SDValue t7 = DAG.getNode(ISD::FSUB, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003216 getF32Constant(DAG, 0x406cfd1c));
Bill Wendling39150252008-09-09 20:39:27 +00003217 SDValue t8 = DAG.getNode(ISD::FMUL, MVT::f32, t7, X);
3218 SDValue t9 = DAG.getNode(ISD::FADD, MVT::f32, t8,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003219 getF32Constant(DAG, 0x408797cb));
Bill Wendling39150252008-09-09 20:39:27 +00003220 SDValue t10 = DAG.getNode(ISD::FMUL, MVT::f32, t9, X);
3221 SDValue LogOfMantissa = DAG.getNode(ISD::FSUB, MVT::f32, t10,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003222 getF32Constant(DAG, 0x4006dcab));
Bill Wendling39150252008-09-09 20:39:27 +00003223
3224 result = DAG.getNode(ISD::FADD, MVT::f32, LogOfExponent, LogOfMantissa);
3225 }
3226 } else {
3227 // No special expansion.
3228 result = DAG.getNode(ISD::FLOG,
3229 getValue(I.getOperand(1)).getValueType(),
3230 getValue(I.getOperand(1)));
3231 }
3232
Dale Johannesen59e577f2008-09-05 18:38:42 +00003233 setValue(&I, result);
3234}
3235
Bill Wendling3eb59402008-09-09 00:28:24 +00003236/// visitLog2 - Lower a log2 intrinsic. Handles the special sequences for
3237/// limited-precision mode.
Dale Johannesen59e577f2008-09-05 18:38:42 +00003238void
3239SelectionDAGLowering::visitLog2(CallInst &I) {
3240 SDValue result;
Bill Wendling3eb59402008-09-09 00:28:24 +00003241
Dale Johannesen853244f2008-09-05 23:49:37 +00003242 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
Bill Wendling3eb59402008-09-09 00:28:24 +00003243 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3244 SDValue Op = getValue(I.getOperand(1));
3245 SDValue Op1 = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, Op);
3246
Bill Wendling39150252008-09-09 20:39:27 +00003247 // Get the exponent.
3248 SDValue LogOfExponent = GetExponent(DAG, Op1);
Bill Wendling3eb59402008-09-09 00:28:24 +00003249
3250 // Get the significand and build it into a floating-point number with
Bill Wendling39150252008-09-09 20:39:27 +00003251 // exponent of 1.
3252 SDValue X = GetSignificand(DAG, Op1);
Bill Wendling3eb59402008-09-09 00:28:24 +00003253
3254 // Different possible minimax approximations of significand in
3255 // floating-point for various degrees of accuracy over [1,2].
3256 if (LimitFloatPrecision <= 6) {
3257 // For floating-point precision of 6:
3258 //
3259 // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
3260 //
3261 // error 0.0049451742, which is more than 7 bits
Bill Wendling39150252008-09-09 20:39:27 +00003262 SDValue t0 = DAG.getNode(ISD::FMUL, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003263 getF32Constant(DAG, 0xbeb08fe0));
Bill Wendling39150252008-09-09 20:39:27 +00003264 SDValue t1 = DAG.getNode(ISD::FADD, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003265 getF32Constant(DAG, 0x40019463));
Bill Wendling39150252008-09-09 20:39:27 +00003266 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, t1, X);
3267 SDValue Log2ofMantissa = DAG.getNode(ISD::FSUB, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003268 getF32Constant(DAG, 0x3fd6633d));
Bill Wendling3eb59402008-09-09 00:28:24 +00003269
3270 result = DAG.getNode(ISD::FADD, MVT::f32, LogOfExponent, Log2ofMantissa);
3271 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3272 // For floating-point precision of 12:
3273 //
3274 // Log2ofMantissa =
3275 // -2.51285454f +
3276 // (4.07009056f +
3277 // (-2.12067489f +
3278 // (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
3279 //
3280 // error 0.0000876136000, which is better than 13 bits
Bill Wendling39150252008-09-09 20:39:27 +00003281 SDValue t0 = DAG.getNode(ISD::FMUL, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003282 getF32Constant(DAG, 0xbda7262e));
Bill Wendling39150252008-09-09 20:39:27 +00003283 SDValue t1 = DAG.getNode(ISD::FADD, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003284 getF32Constant(DAG, 0x3f25280b));
Bill Wendling39150252008-09-09 20:39:27 +00003285 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, t1, X);
3286 SDValue t3 = DAG.getNode(ISD::FSUB, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003287 getF32Constant(DAG, 0x4007b923));
Bill Wendling39150252008-09-09 20:39:27 +00003288 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3289 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003290 getF32Constant(DAG, 0x40823e2f));
Bill Wendling39150252008-09-09 20:39:27 +00003291 SDValue t6 = DAG.getNode(ISD::FMUL, MVT::f32, t5, X);
3292 SDValue Log2ofMantissa = DAG.getNode(ISD::FSUB, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003293 getF32Constant(DAG, 0x4020d29c));
Bill Wendling3eb59402008-09-09 00:28:24 +00003294
3295 result = DAG.getNode(ISD::FADD, MVT::f32, LogOfExponent, Log2ofMantissa);
3296 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3297 // For floating-point precision of 18:
3298 //
3299 // Log2ofMantissa =
3300 // -3.0400495f +
3301 // (6.1129976f +
3302 // (-5.3420409f +
3303 // (3.2865683f +
3304 // (-1.2669343f +
3305 // (0.27515199f -
3306 // 0.25691327e-1f * x) * x) * x) * x) * x) * x;
3307 //
3308 // error 0.0000018516, which is better than 18 bits
Bill Wendling39150252008-09-09 20:39:27 +00003309 SDValue t0 = DAG.getNode(ISD::FMUL, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003310 getF32Constant(DAG, 0xbcd2769e));
Bill Wendling39150252008-09-09 20:39:27 +00003311 SDValue t1 = DAG.getNode(ISD::FADD, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003312 getF32Constant(DAG, 0x3e8ce0b9));
Bill Wendling39150252008-09-09 20:39:27 +00003313 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, t1, X);
3314 SDValue t3 = DAG.getNode(ISD::FSUB, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003315 getF32Constant(DAG, 0x3fa22ae7));
Bill Wendling39150252008-09-09 20:39:27 +00003316 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3317 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003318 getF32Constant(DAG, 0x40525723));
Bill Wendling39150252008-09-09 20:39:27 +00003319 SDValue t6 = DAG.getNode(ISD::FMUL, MVT::f32, t5, X);
3320 SDValue t7 = DAG.getNode(ISD::FSUB, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003321 getF32Constant(DAG, 0x40aaf200));
Bill Wendling39150252008-09-09 20:39:27 +00003322 SDValue t8 = DAG.getNode(ISD::FMUL, MVT::f32, t7, X);
3323 SDValue t9 = DAG.getNode(ISD::FADD, MVT::f32, t8,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003324 getF32Constant(DAG, 0x40c39dad));
Bill Wendling3eb59402008-09-09 00:28:24 +00003325 SDValue t10 = DAG.getNode(ISD::FMUL, MVT::f32, t9, X);
Bill Wendling39150252008-09-09 20:39:27 +00003326 SDValue Log2ofMantissa = DAG.getNode(ISD::FSUB, MVT::f32, t10,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003327 getF32Constant(DAG, 0x4042902c));
Bill Wendling3eb59402008-09-09 00:28:24 +00003328
3329 result = DAG.getNode(ISD::FADD, MVT::f32, LogOfExponent, Log2ofMantissa);
3330 }
Dale Johannesen853244f2008-09-05 23:49:37 +00003331 } else {
Bill Wendling3eb59402008-09-09 00:28:24 +00003332 // No special expansion.
Dale Johannesen853244f2008-09-05 23:49:37 +00003333 result = DAG.getNode(ISD::FLOG2,
3334 getValue(I.getOperand(1)).getValueType(),
3335 getValue(I.getOperand(1)));
3336 }
Bill Wendling3eb59402008-09-09 00:28:24 +00003337
Dale Johannesen59e577f2008-09-05 18:38:42 +00003338 setValue(&I, result);
3339}
3340
Bill Wendling3eb59402008-09-09 00:28:24 +00003341/// visitLog10 - Lower a log10 intrinsic. Handles the special sequences for
3342/// limited-precision mode.
Dale Johannesen59e577f2008-09-05 18:38:42 +00003343void
3344SelectionDAGLowering::visitLog10(CallInst &I) {
3345 SDValue result;
Bill Wendling181b6272008-10-19 20:34:04 +00003346
Dale Johannesen852680a2008-09-05 21:27:19 +00003347 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
Bill Wendling3eb59402008-09-09 00:28:24 +00003348 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3349 SDValue Op = getValue(I.getOperand(1));
3350 SDValue Op1 = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, Op);
3351
Bill Wendling39150252008-09-09 20:39:27 +00003352 // Scale the exponent by log10(2) [0.30102999f].
3353 SDValue Exp = GetExponent(DAG, Op1);
3354 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, MVT::f32, Exp,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003355 getF32Constant(DAG, 0x3e9a209a));
Bill Wendling3eb59402008-09-09 00:28:24 +00003356
3357 // Get the significand and build it into a floating-point number with
Bill Wendling39150252008-09-09 20:39:27 +00003358 // exponent of 1.
3359 SDValue X = GetSignificand(DAG, Op1);
Bill Wendling3eb59402008-09-09 00:28:24 +00003360
3361 if (LimitFloatPrecision <= 6) {
Bill Wendlingbd297bc2008-09-09 18:42:23 +00003362 // For floating-point precision of 6:
3363 //
3364 // Log10ofMantissa =
3365 // -0.50419619f +
3366 // (0.60948995f - 0.10380950f * x) * x;
3367 //
3368 // error 0.0014886165, which is 6 bits
Bill Wendling39150252008-09-09 20:39:27 +00003369 SDValue t0 = DAG.getNode(ISD::FMUL, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003370 getF32Constant(DAG, 0xbdd49a13));
Bill Wendling39150252008-09-09 20:39:27 +00003371 SDValue t1 = DAG.getNode(ISD::FADD, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003372 getF32Constant(DAG, 0x3f1c0789));
Bill Wendling39150252008-09-09 20:39:27 +00003373 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, t1, X);
3374 SDValue Log10ofMantissa = DAG.getNode(ISD::FSUB, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003375 getF32Constant(DAG, 0x3f011300));
Bill Wendlingbd297bc2008-09-09 18:42:23 +00003376
3377 result = DAG.getNode(ISD::FADD, MVT::f32, LogOfExponent, Log10ofMantissa);
Bill Wendling3eb59402008-09-09 00:28:24 +00003378 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3379 // For floating-point precision of 12:
3380 //
3381 // Log10ofMantissa =
3382 // -0.64831180f +
3383 // (0.91751397f +
3384 // (-0.31664806f + 0.47637168e-1f * x) * x) * x;
3385 //
3386 // error 0.00019228036, which is better than 12 bits
Bill Wendling39150252008-09-09 20:39:27 +00003387 SDValue t0 = DAG.getNode(ISD::FMUL, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003388 getF32Constant(DAG, 0x3d431f31));
Bill Wendling39150252008-09-09 20:39:27 +00003389 SDValue t1 = DAG.getNode(ISD::FSUB, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003390 getF32Constant(DAG, 0x3ea21fb2));
Bill Wendling39150252008-09-09 20:39:27 +00003391 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, t1, X);
3392 SDValue t3 = DAG.getNode(ISD::FADD, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003393 getF32Constant(DAG, 0x3f6ae232));
Bill Wendling39150252008-09-09 20:39:27 +00003394 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3395 SDValue Log10ofMantissa = DAG.getNode(ISD::FSUB, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003396 getF32Constant(DAG, 0x3f25f7c3));
Bill Wendling3eb59402008-09-09 00:28:24 +00003397
3398 result = DAG.getNode(ISD::FADD, MVT::f32, LogOfExponent, Log10ofMantissa);
3399 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
Bill Wendlingbd297bc2008-09-09 18:42:23 +00003400 // For floating-point precision of 18:
3401 //
3402 // Log10ofMantissa =
3403 // -0.84299375f +
3404 // (1.5327582f +
3405 // (-1.0688956f +
3406 // (0.49102474f +
3407 // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
3408 //
3409 // error 0.0000037995730, which is better than 18 bits
Bill Wendling39150252008-09-09 20:39:27 +00003410 SDValue t0 = DAG.getNode(ISD::FMUL, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003411 getF32Constant(DAG, 0x3c5d51ce));
Bill Wendling39150252008-09-09 20:39:27 +00003412 SDValue t1 = DAG.getNode(ISD::FSUB, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003413 getF32Constant(DAG, 0x3e00685a));
Bill Wendling39150252008-09-09 20:39:27 +00003414 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, t1, X);
3415 SDValue t3 = DAG.getNode(ISD::FADD, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003416 getF32Constant(DAG, 0x3efb6798));
Bill Wendling39150252008-09-09 20:39:27 +00003417 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3418 SDValue t5 = DAG.getNode(ISD::FSUB, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003419 getF32Constant(DAG, 0x3f88d192));
Bill Wendling39150252008-09-09 20:39:27 +00003420 SDValue t6 = DAG.getNode(ISD::FMUL, MVT::f32, t5, X);
3421 SDValue t7 = DAG.getNode(ISD::FADD, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003422 getF32Constant(DAG, 0x3fc4316c));
Bill Wendlingbd297bc2008-09-09 18:42:23 +00003423 SDValue t8 = DAG.getNode(ISD::FMUL, MVT::f32, t7, X);
Bill Wendling39150252008-09-09 20:39:27 +00003424 SDValue Log10ofMantissa = DAG.getNode(ISD::FSUB, MVT::f32, t8,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003425 getF32Constant(DAG, 0x3f57ce70));
Bill Wendlingbd297bc2008-09-09 18:42:23 +00003426
3427 result = DAG.getNode(ISD::FADD, MVT::f32, LogOfExponent, Log10ofMantissa);
Bill Wendling3eb59402008-09-09 00:28:24 +00003428 }
Dale Johannesen852680a2008-09-05 21:27:19 +00003429 } else {
Bill Wendling3eb59402008-09-09 00:28:24 +00003430 // No special expansion.
Dale Johannesen852680a2008-09-05 21:27:19 +00003431 result = DAG.getNode(ISD::FLOG10,
3432 getValue(I.getOperand(1)).getValueType(),
3433 getValue(I.getOperand(1)));
3434 }
Bill Wendling3eb59402008-09-09 00:28:24 +00003435
Dale Johannesen59e577f2008-09-05 18:38:42 +00003436 setValue(&I, result);
3437}
3438
Bill Wendlinge10c8142008-09-09 22:39:21 +00003439/// visitExp2 - Lower an exp2 intrinsic. Handles the special sequences for
3440/// limited-precision mode.
Dale Johannesen601d3c02008-09-05 01:48:15 +00003441void
3442SelectionDAGLowering::visitExp2(CallInst &I) {
3443 SDValue result;
Bill Wendlinge10c8142008-09-09 22:39:21 +00003444
Dale Johannesen601d3c02008-09-05 01:48:15 +00003445 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
Bill Wendlinge10c8142008-09-09 22:39:21 +00003446 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3447 SDValue Op = getValue(I.getOperand(1));
3448
3449 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, MVT::i32, Op);
3450
3451 // FractionalPartOfX = x - (float)IntegerPartOfX;
3452 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, MVT::f32, IntegerPartOfX);
3453 SDValue X = DAG.getNode(ISD::FSUB, MVT::f32, Op, t1);
3454
3455 // IntegerPartOfX <<= 23;
3456 IntegerPartOfX = DAG.getNode(ISD::SHL, MVT::i32, IntegerPartOfX,
3457 DAG.getConstant(23, MVT::i32));
3458
3459 if (LimitFloatPrecision <= 6) {
3460 // For floating-point precision of 6:
3461 //
3462 // TwoToFractionalPartOfX =
3463 // 0.997535578f +
3464 // (0.735607626f + 0.252464424f * x) * x;
3465 //
3466 // error 0.0144103317, which is 6 bits
3467 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003468 getF32Constant(DAG, 0x3e814304));
Bill Wendlinge10c8142008-09-09 22:39:21 +00003469 SDValue t3 = DAG.getNode(ISD::FADD, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003470 getF32Constant(DAG, 0x3f3c50c8));
Bill Wendlinge10c8142008-09-09 22:39:21 +00003471 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3472 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003473 getF32Constant(DAG, 0x3f7f5e7e));
Bill Wendlinge10c8142008-09-09 22:39:21 +00003474 SDValue t6 = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, t5);
3475 SDValue TwoToFractionalPartOfX =
3476 DAG.getNode(ISD::ADD, MVT::i32, t6, IntegerPartOfX);
3477
3478 result = DAG.getNode(ISD::BIT_CONVERT, MVT::f32, TwoToFractionalPartOfX);
3479 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3480 // For floating-point precision of 12:
3481 //
3482 // TwoToFractionalPartOfX =
3483 // 0.999892986f +
3484 // (0.696457318f +
3485 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
3486 //
3487 // error 0.000107046256, which is 13 to 14 bits
3488 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003489 getF32Constant(DAG, 0x3da235e3));
Bill Wendlinge10c8142008-09-09 22:39:21 +00003490 SDValue t3 = DAG.getNode(ISD::FADD, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003491 getF32Constant(DAG, 0x3e65b8f3));
Bill Wendlinge10c8142008-09-09 22:39:21 +00003492 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3493 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003494 getF32Constant(DAG, 0x3f324b07));
Bill Wendlinge10c8142008-09-09 22:39:21 +00003495 SDValue t6 = DAG.getNode(ISD::FMUL, MVT::f32, t5, X);
3496 SDValue t7 = DAG.getNode(ISD::FADD, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003497 getF32Constant(DAG, 0x3f7ff8fd));
Bill Wendlinge10c8142008-09-09 22:39:21 +00003498 SDValue t8 = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, t7);
3499 SDValue TwoToFractionalPartOfX =
3500 DAG.getNode(ISD::ADD, MVT::i32, t8, IntegerPartOfX);
3501
3502 result = DAG.getNode(ISD::BIT_CONVERT, MVT::f32, TwoToFractionalPartOfX);
3503 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3504 // For floating-point precision of 18:
3505 //
3506 // TwoToFractionalPartOfX =
3507 // 0.999999982f +
3508 // (0.693148872f +
3509 // (0.240227044f +
3510 // (0.554906021e-1f +
3511 // (0.961591928e-2f +
3512 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
3513 // error 2.47208000*10^(-7), which is better than 18 bits
3514 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003515 getF32Constant(DAG, 0x3924b03e));
Bill Wendlinge10c8142008-09-09 22:39:21 +00003516 SDValue t3 = DAG.getNode(ISD::FADD, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003517 getF32Constant(DAG, 0x3ab24b87));
Bill Wendlinge10c8142008-09-09 22:39:21 +00003518 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3519 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003520 getF32Constant(DAG, 0x3c1d8c17));
Bill Wendlinge10c8142008-09-09 22:39:21 +00003521 SDValue t6 = DAG.getNode(ISD::FMUL, MVT::f32, t5, X);
3522 SDValue t7 = DAG.getNode(ISD::FADD, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003523 getF32Constant(DAG, 0x3d634a1d));
Bill Wendlinge10c8142008-09-09 22:39:21 +00003524 SDValue t8 = DAG.getNode(ISD::FMUL, MVT::f32, t7, X);
3525 SDValue t9 = DAG.getNode(ISD::FADD, MVT::f32, t8,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003526 getF32Constant(DAG, 0x3e75fe14));
Bill Wendlinge10c8142008-09-09 22:39:21 +00003527 SDValue t10 = DAG.getNode(ISD::FMUL, MVT::f32, t9, X);
3528 SDValue t11 = DAG.getNode(ISD::FADD, MVT::f32, t10,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003529 getF32Constant(DAG, 0x3f317234));
Bill Wendlinge10c8142008-09-09 22:39:21 +00003530 SDValue t12 = DAG.getNode(ISD::FMUL, MVT::f32, t11, X);
3531 SDValue t13 = DAG.getNode(ISD::FADD, MVT::f32, t12,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003532 getF32Constant(DAG, 0x3f800000));
Bill Wendlinge10c8142008-09-09 22:39:21 +00003533 SDValue t14 = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, t13);
3534 SDValue TwoToFractionalPartOfX =
3535 DAG.getNode(ISD::ADD, MVT::i32, t14, IntegerPartOfX);
3536
3537 result = DAG.getNode(ISD::BIT_CONVERT, MVT::f32, TwoToFractionalPartOfX);
3538 }
Dale Johannesen601d3c02008-09-05 01:48:15 +00003539 } else {
Bill Wendling3eb59402008-09-09 00:28:24 +00003540 // No special expansion.
Dale Johannesen601d3c02008-09-05 01:48:15 +00003541 result = DAG.getNode(ISD::FEXP2,
3542 getValue(I.getOperand(1)).getValueType(),
3543 getValue(I.getOperand(1)));
3544 }
Bill Wendlinge10c8142008-09-09 22:39:21 +00003545
Dale Johannesen601d3c02008-09-05 01:48:15 +00003546 setValue(&I, result);
3547}
3548
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003549/// visitPow - Lower a pow intrinsic. Handles the special sequences for
3550/// limited-precision mode with x == 10.0f.
3551void
3552SelectionDAGLowering::visitPow(CallInst &I) {
3553 SDValue result;
3554 Value *Val = I.getOperand(1);
3555 bool IsExp10 = false;
3556
3557 if (getValue(Val).getValueType() == MVT::f32 &&
Bill Wendling277fc242008-09-10 00:24:59 +00003558 getValue(I.getOperand(2)).getValueType() == MVT::f32 &&
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003559 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3560 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(Val))) {
3561 if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
3562 APFloat Ten(10.0f);
3563 IsExp10 = CFP->getValueAPF().bitwiseIsEqual(Ten);
3564 }
3565 }
3566 }
3567
3568 if (IsExp10 && LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3569 SDValue Op = getValue(I.getOperand(2));
3570
3571 // Put the exponent in the right bit position for later addition to the
3572 // final result:
3573 //
3574 // #define LOG2OF10 3.3219281f
3575 // IntegerPartOfX = (int32_t)(x * LOG2OF10);
3576 SDValue t0 = DAG.getNode(ISD::FMUL, MVT::f32, Op,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003577 getF32Constant(DAG, 0x40549a78));
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003578 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, MVT::i32, t0);
3579
3580 // FractionalPartOfX = x - (float)IntegerPartOfX;
3581 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, MVT::f32, IntegerPartOfX);
3582 SDValue X = DAG.getNode(ISD::FSUB, MVT::f32, t0, t1);
3583
3584 // IntegerPartOfX <<= 23;
3585 IntegerPartOfX = DAG.getNode(ISD::SHL, MVT::i32, IntegerPartOfX,
3586 DAG.getConstant(23, MVT::i32));
3587
3588 if (LimitFloatPrecision <= 6) {
3589 // For floating-point precision of 6:
3590 //
3591 // twoToFractionalPartOfX =
3592 // 0.997535578f +
3593 // (0.735607626f + 0.252464424f * x) * x;
3594 //
3595 // error 0.0144103317, which is 6 bits
3596 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003597 getF32Constant(DAG, 0x3e814304));
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003598 SDValue t3 = DAG.getNode(ISD::FADD, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003599 getF32Constant(DAG, 0x3f3c50c8));
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003600 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3601 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003602 getF32Constant(DAG, 0x3f7f5e7e));
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003603 SDValue t6 = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, t5);
3604 SDValue TwoToFractionalPartOfX =
3605 DAG.getNode(ISD::ADD, MVT::i32, t6, IntegerPartOfX);
3606
3607 result = DAG.getNode(ISD::BIT_CONVERT, MVT::f32, TwoToFractionalPartOfX);
3608 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3609 // For floating-point precision of 12:
3610 //
3611 // TwoToFractionalPartOfX =
3612 // 0.999892986f +
3613 // (0.696457318f +
3614 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
3615 //
3616 // error 0.000107046256, which is 13 to 14 bits
3617 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003618 getF32Constant(DAG, 0x3da235e3));
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003619 SDValue t3 = DAG.getNode(ISD::FADD, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003620 getF32Constant(DAG, 0x3e65b8f3));
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003621 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3622 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003623 getF32Constant(DAG, 0x3f324b07));
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003624 SDValue t6 = DAG.getNode(ISD::FMUL, MVT::f32, t5, X);
3625 SDValue t7 = DAG.getNode(ISD::FADD, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003626 getF32Constant(DAG, 0x3f7ff8fd));
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003627 SDValue t8 = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, t7);
3628 SDValue TwoToFractionalPartOfX =
3629 DAG.getNode(ISD::ADD, MVT::i32, t8, IntegerPartOfX);
3630
3631 result = DAG.getNode(ISD::BIT_CONVERT, MVT::f32, TwoToFractionalPartOfX);
3632 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3633 // For floating-point precision of 18:
3634 //
3635 // TwoToFractionalPartOfX =
3636 // 0.999999982f +
3637 // (0.693148872f +
3638 // (0.240227044f +
3639 // (0.554906021e-1f +
3640 // (0.961591928e-2f +
3641 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
3642 // error 2.47208000*10^(-7), which is better than 18 bits
3643 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003644 getF32Constant(DAG, 0x3924b03e));
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003645 SDValue t3 = DAG.getNode(ISD::FADD, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003646 getF32Constant(DAG, 0x3ab24b87));
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003647 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3648 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003649 getF32Constant(DAG, 0x3c1d8c17));
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003650 SDValue t6 = DAG.getNode(ISD::FMUL, MVT::f32, t5, X);
3651 SDValue t7 = DAG.getNode(ISD::FADD, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003652 getF32Constant(DAG, 0x3d634a1d));
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003653 SDValue t8 = DAG.getNode(ISD::FMUL, MVT::f32, t7, X);
3654 SDValue t9 = DAG.getNode(ISD::FADD, MVT::f32, t8,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003655 getF32Constant(DAG, 0x3e75fe14));
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003656 SDValue t10 = DAG.getNode(ISD::FMUL, MVT::f32, t9, X);
3657 SDValue t11 = DAG.getNode(ISD::FADD, MVT::f32, t10,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003658 getF32Constant(DAG, 0x3f317234));
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003659 SDValue t12 = DAG.getNode(ISD::FMUL, MVT::f32, t11, X);
3660 SDValue t13 = DAG.getNode(ISD::FADD, MVT::f32, t12,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003661 getF32Constant(DAG, 0x3f800000));
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003662 SDValue t14 = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, t13);
3663 SDValue TwoToFractionalPartOfX =
3664 DAG.getNode(ISD::ADD, MVT::i32, t14, IntegerPartOfX);
3665
3666 result = DAG.getNode(ISD::BIT_CONVERT, MVT::f32, TwoToFractionalPartOfX);
3667 }
3668 } else {
3669 // No special expansion.
3670 result = DAG.getNode(ISD::FPOW,
3671 getValue(I.getOperand(1)).getValueType(),
3672 getValue(I.getOperand(1)),
3673 getValue(I.getOperand(2)));
3674 }
3675
3676 setValue(&I, result);
3677}
3678
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003679/// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
3680/// we want to emit this as a call to a named external function, return the name
3681/// otherwise lower it and return null.
3682const char *
3683SelectionDAGLowering::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
3684 switch (Intrinsic) {
3685 default:
3686 // By default, turn this into a target intrinsic node.
3687 visitTargetIntrinsic(I, Intrinsic);
3688 return 0;
3689 case Intrinsic::vastart: visitVAStart(I); return 0;
3690 case Intrinsic::vaend: visitVAEnd(I); return 0;
3691 case Intrinsic::vacopy: visitVACopy(I); return 0;
3692 case Intrinsic::returnaddress:
3693 setValue(&I, DAG.getNode(ISD::RETURNADDR, TLI.getPointerTy(),
3694 getValue(I.getOperand(1))));
3695 return 0;
Bill Wendlingd5d81912008-09-26 22:10:44 +00003696 case Intrinsic::frameaddress:
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003697 setValue(&I, DAG.getNode(ISD::FRAMEADDR, TLI.getPointerTy(),
3698 getValue(I.getOperand(1))));
3699 return 0;
3700 case Intrinsic::setjmp:
3701 return "_setjmp"+!TLI.usesUnderscoreSetJmp();
3702 break;
3703 case Intrinsic::longjmp:
3704 return "_longjmp"+!TLI.usesUnderscoreLongJmp();
3705 break;
Chris Lattner824b9582008-11-21 16:42:48 +00003706 case Intrinsic::memcpy: {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003707 SDValue Op1 = getValue(I.getOperand(1));
3708 SDValue Op2 = getValue(I.getOperand(2));
3709 SDValue Op3 = getValue(I.getOperand(3));
3710 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
3711 DAG.setRoot(DAG.getMemcpy(getRoot(), Op1, Op2, Op3, Align, false,
3712 I.getOperand(1), 0, I.getOperand(2), 0));
3713 return 0;
3714 }
Chris Lattner824b9582008-11-21 16:42:48 +00003715 case Intrinsic::memset: {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003716 SDValue Op1 = getValue(I.getOperand(1));
3717 SDValue Op2 = getValue(I.getOperand(2));
3718 SDValue Op3 = getValue(I.getOperand(3));
3719 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
3720 DAG.setRoot(DAG.getMemset(getRoot(), Op1, Op2, Op3, Align,
3721 I.getOperand(1), 0));
3722 return 0;
3723 }
Chris Lattner824b9582008-11-21 16:42:48 +00003724 case Intrinsic::memmove: {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003725 SDValue Op1 = getValue(I.getOperand(1));
3726 SDValue Op2 = getValue(I.getOperand(2));
3727 SDValue Op3 = getValue(I.getOperand(3));
3728 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
3729
3730 // If the source and destination are known to not be aliases, we can
3731 // lower memmove as memcpy.
3732 uint64_t Size = -1ULL;
3733 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op3))
Dan Gohmanf5aeb1a2008-09-12 16:56:44 +00003734 Size = C->getZExtValue();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003735 if (AA->alias(I.getOperand(1), Size, I.getOperand(2), Size) ==
3736 AliasAnalysis::NoAlias) {
3737 DAG.setRoot(DAG.getMemcpy(getRoot(), Op1, Op2, Op3, Align, false,
3738 I.getOperand(1), 0, I.getOperand(2), 0));
3739 return 0;
3740 }
3741
3742 DAG.setRoot(DAG.getMemmove(getRoot(), Op1, Op2, Op3, Align,
3743 I.getOperand(1), 0, I.getOperand(2), 0));
3744 return 0;
3745 }
3746 case Intrinsic::dbg_stoppoint: {
Devang Patel83489bb2009-01-13 00:35:13 +00003747 DwarfWriter *DW = DAG.getDwarfWriter();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003748 DbgStopPointInst &SPI = cast<DbgStopPointInst>(I);
Devang Patel83489bb2009-01-13 00:35:13 +00003749 if (DW && SPI.getContext())
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003750 DAG.setRoot(DAG.getDbgStopPoint(getRoot(),
3751 SPI.getLine(),
3752 SPI.getColumn(),
Devang Patel83489bb2009-01-13 00:35:13 +00003753 SPI.getContext()));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003754 return 0;
3755 }
3756 case Intrinsic::dbg_region_start: {
Devang Patel83489bb2009-01-13 00:35:13 +00003757 DwarfWriter *DW = DAG.getDwarfWriter();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003758 DbgRegionStartInst &RSI = cast<DbgRegionStartInst>(I);
Devang Patel83489bb2009-01-13 00:35:13 +00003759 if (DW && RSI.getContext()) {
3760 unsigned LabelID =
3761 DW->RecordRegionStart(cast<GlobalVariable>(RSI.getContext()));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003762 DAG.setRoot(DAG.getLabel(ISD::DBG_LABEL, getRoot(), LabelID));
3763 }
3764
3765 return 0;
3766 }
3767 case Intrinsic::dbg_region_end: {
Devang Patel83489bb2009-01-13 00:35:13 +00003768 DwarfWriter *DW = DAG.getDwarfWriter();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003769 DbgRegionEndInst &REI = cast<DbgRegionEndInst>(I);
Devang Patel83489bb2009-01-13 00:35:13 +00003770 if (DW && REI.getContext()) {
3771 unsigned LabelID =
3772 DW->RecordRegionEnd(cast<GlobalVariable>(REI.getContext()));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003773 DAG.setRoot(DAG.getLabel(ISD::DBG_LABEL, getRoot(), LabelID));
3774 }
3775
3776 return 0;
3777 }
3778 case Intrinsic::dbg_func_start: {
Devang Patel83489bb2009-01-13 00:35:13 +00003779 DwarfWriter *DW = DAG.getDwarfWriter();
3780 if (!DW) return 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003781 DbgFuncStartInst &FSI = cast<DbgFuncStartInst>(I);
3782 Value *SP = FSI.getSubprogram();
Devang Patel83489bb2009-01-13 00:35:13 +00003783 if (SP) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003784 // llvm.dbg.func.start implicitly defines a dbg_stoppoint which is
3785 // what (most?) gdb expects.
Devang Patel83489bb2009-01-13 00:35:13 +00003786 DISubprogram Subprogram(cast<GlobalVariable>(SP));
3787 DICompileUnit CompileUnit = Subprogram.getCompileUnit();
3788 unsigned SrcFile = DW->RecordSource(CompileUnit.getDirectory(),
3789 CompileUnit.getFilename());
Devang Patel20dd0462008-11-06 00:30:09 +00003790 // Record the source line but does not create a label for the normal
3791 // function start. It will be emitted at asm emission time. However,
3792 // create a label if this is a beginning of inlined function.
Devang Patel83489bb2009-01-13 00:35:13 +00003793 unsigned LabelID =
3794 DW->RecordSourceLine(Subprogram.getLineNumber(), 0, SrcFile);
3795 if (DW->getRecordSourceLineCount() != 1)
Devang Patel20dd0462008-11-06 00:30:09 +00003796 DAG.setRoot(DAG.getLabel(ISD::DBG_LABEL, getRoot(), LabelID));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003797 }
3798
3799 return 0;
3800 }
3801 case Intrinsic::dbg_declare: {
Devang Patel83489bb2009-01-13 00:35:13 +00003802 DwarfWriter *DW = DAG.getDwarfWriter();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003803 DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
3804 Value *Variable = DI.getVariable();
Devang Patel83489bb2009-01-13 00:35:13 +00003805 if (DW && Variable)
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003806 DAG.setRoot(DAG.getNode(ISD::DECLARE, MVT::Other, getRoot(),
3807 getValue(DI.getAddress()), getValue(Variable)));
3808 return 0;
3809 }
3810
3811 case Intrinsic::eh_exception: {
3812 if (!CurMBB->isLandingPad()) {
3813 // FIXME: Mark exception register as live in. Hack for PR1508.
3814 unsigned Reg = TLI.getExceptionAddressRegister();
3815 if (Reg) CurMBB->addLiveIn(Reg);
3816 }
3817 // Insert the EXCEPTIONADDR instruction.
3818 SDVTList VTs = DAG.getVTList(TLI.getPointerTy(), MVT::Other);
3819 SDValue Ops[1];
3820 Ops[0] = DAG.getRoot();
3821 SDValue Op = DAG.getNode(ISD::EXCEPTIONADDR, VTs, Ops, 1);
3822 setValue(&I, Op);
3823 DAG.setRoot(Op.getValue(1));
3824 return 0;
3825 }
3826
3827 case Intrinsic::eh_selector_i32:
3828 case Intrinsic::eh_selector_i64: {
3829 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3830 MVT VT = (Intrinsic == Intrinsic::eh_selector_i32 ?
3831 MVT::i32 : MVT::i64);
3832
3833 if (MMI) {
3834 if (CurMBB->isLandingPad())
3835 AddCatchInfo(I, MMI, CurMBB);
3836 else {
3837#ifndef NDEBUG
3838 FuncInfo.CatchInfoLost.insert(&I);
3839#endif
3840 // FIXME: Mark exception selector register as live in. Hack for PR1508.
3841 unsigned Reg = TLI.getExceptionSelectorRegister();
3842 if (Reg) CurMBB->addLiveIn(Reg);
3843 }
3844
3845 // Insert the EHSELECTION instruction.
3846 SDVTList VTs = DAG.getVTList(VT, MVT::Other);
3847 SDValue Ops[2];
3848 Ops[0] = getValue(I.getOperand(1));
3849 Ops[1] = getRoot();
3850 SDValue Op = DAG.getNode(ISD::EHSELECTION, VTs, Ops, 2);
3851 setValue(&I, Op);
3852 DAG.setRoot(Op.getValue(1));
3853 } else {
3854 setValue(&I, DAG.getConstant(0, VT));
3855 }
3856
3857 return 0;
3858 }
3859
3860 case Intrinsic::eh_typeid_for_i32:
3861 case Intrinsic::eh_typeid_for_i64: {
3862 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3863 MVT VT = (Intrinsic == Intrinsic::eh_typeid_for_i32 ?
3864 MVT::i32 : MVT::i64);
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00003865
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003866 if (MMI) {
3867 // Find the type id for the given typeinfo.
3868 GlobalVariable *GV = ExtractTypeInfo(I.getOperand(1));
3869
3870 unsigned TypeID = MMI->getTypeIDFor(GV);
3871 setValue(&I, DAG.getConstant(TypeID, VT));
3872 } else {
3873 // Return something different to eh_selector.
3874 setValue(&I, DAG.getConstant(1, VT));
3875 }
3876
3877 return 0;
3878 }
3879
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00003880 case Intrinsic::eh_return_i32:
3881 case Intrinsic::eh_return_i64:
3882 if (MachineModuleInfo *MMI = DAG.getMachineModuleInfo()) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003883 MMI->setCallsEHReturn(true);
3884 DAG.setRoot(DAG.getNode(ISD::EH_RETURN,
3885 MVT::Other,
3886 getControlRoot(),
3887 getValue(I.getOperand(1)),
3888 getValue(I.getOperand(2))));
3889 } else {
3890 setValue(&I, DAG.getConstant(0, TLI.getPointerTy()));
3891 }
3892
3893 return 0;
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00003894 case Intrinsic::eh_unwind_init:
3895 if (MachineModuleInfo *MMI = DAG.getMachineModuleInfo()) {
3896 MMI->setCallsUnwindInit(true);
3897 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003898
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00003899 return 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003900
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00003901 case Intrinsic::eh_dwarf_cfa: {
3902 MVT VT = getValue(I.getOperand(1)).getValueType();
3903 SDValue CfaArg;
3904 if (VT.bitsGT(TLI.getPointerTy()))
3905 CfaArg = DAG.getNode(ISD::TRUNCATE,
3906 TLI.getPointerTy(), getValue(I.getOperand(1)));
3907 else
3908 CfaArg = DAG.getNode(ISD::SIGN_EXTEND,
3909 TLI.getPointerTy(), getValue(I.getOperand(1)));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003910
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00003911 SDValue Offset = DAG.getNode(ISD::ADD,
3912 TLI.getPointerTy(),
3913 DAG.getNode(ISD::FRAME_TO_ARGS_OFFSET,
3914 TLI.getPointerTy()),
3915 CfaArg);
3916 setValue(&I, DAG.getNode(ISD::ADD,
3917 TLI.getPointerTy(),
3918 DAG.getNode(ISD::FRAMEADDR,
3919 TLI.getPointerTy(),
3920 DAG.getConstant(0,
3921 TLI.getPointerTy())),
3922 Offset));
3923 return 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003924 }
3925
Mon P Wang77cdf302008-11-10 20:54:11 +00003926 case Intrinsic::convertff:
3927 case Intrinsic::convertfsi:
3928 case Intrinsic::convertfui:
3929 case Intrinsic::convertsif:
3930 case Intrinsic::convertuif:
3931 case Intrinsic::convertss:
3932 case Intrinsic::convertsu:
3933 case Intrinsic::convertus:
3934 case Intrinsic::convertuu: {
3935 ISD::CvtCode Code = ISD::CVT_INVALID;
3936 switch (Intrinsic) {
3937 case Intrinsic::convertff: Code = ISD::CVT_FF; break;
3938 case Intrinsic::convertfsi: Code = ISD::CVT_FS; break;
3939 case Intrinsic::convertfui: Code = ISD::CVT_FU; break;
3940 case Intrinsic::convertsif: Code = ISD::CVT_SF; break;
3941 case Intrinsic::convertuif: Code = ISD::CVT_UF; break;
3942 case Intrinsic::convertss: Code = ISD::CVT_SS; break;
3943 case Intrinsic::convertsu: Code = ISD::CVT_SU; break;
3944 case Intrinsic::convertus: Code = ISD::CVT_US; break;
3945 case Intrinsic::convertuu: Code = ISD::CVT_UU; break;
3946 }
3947 MVT DestVT = TLI.getValueType(I.getType());
3948 Value* Op1 = I.getOperand(1);
3949 setValue(&I, DAG.getConvertRndSat(DestVT, getValue(Op1),
3950 DAG.getValueType(DestVT),
3951 DAG.getValueType(getValue(Op1).getValueType()),
3952 getValue(I.getOperand(2)),
3953 getValue(I.getOperand(3)),
3954 Code));
3955 return 0;
3956 }
3957
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003958 case Intrinsic::sqrt:
3959 setValue(&I, DAG.getNode(ISD::FSQRT,
3960 getValue(I.getOperand(1)).getValueType(),
3961 getValue(I.getOperand(1))));
3962 return 0;
3963 case Intrinsic::powi:
3964 setValue(&I, DAG.getNode(ISD::FPOWI,
3965 getValue(I.getOperand(1)).getValueType(),
3966 getValue(I.getOperand(1)),
3967 getValue(I.getOperand(2))));
3968 return 0;
3969 case Intrinsic::sin:
3970 setValue(&I, DAG.getNode(ISD::FSIN,
3971 getValue(I.getOperand(1)).getValueType(),
3972 getValue(I.getOperand(1))));
3973 return 0;
3974 case Intrinsic::cos:
3975 setValue(&I, DAG.getNode(ISD::FCOS,
3976 getValue(I.getOperand(1)).getValueType(),
3977 getValue(I.getOperand(1))));
3978 return 0;
Dale Johannesen7794f2a2008-09-04 00:47:13 +00003979 case Intrinsic::log:
Dale Johannesen59e577f2008-09-05 18:38:42 +00003980 visitLog(I);
Dale Johannesen7794f2a2008-09-04 00:47:13 +00003981 return 0;
3982 case Intrinsic::log2:
Dale Johannesen59e577f2008-09-05 18:38:42 +00003983 visitLog2(I);
Dale Johannesen7794f2a2008-09-04 00:47:13 +00003984 return 0;
3985 case Intrinsic::log10:
Dale Johannesen59e577f2008-09-05 18:38:42 +00003986 visitLog10(I);
Dale Johannesen7794f2a2008-09-04 00:47:13 +00003987 return 0;
3988 case Intrinsic::exp:
Dale Johannesen59e577f2008-09-05 18:38:42 +00003989 visitExp(I);
Dale Johannesen7794f2a2008-09-04 00:47:13 +00003990 return 0;
3991 case Intrinsic::exp2:
Dale Johannesen601d3c02008-09-05 01:48:15 +00003992 visitExp2(I);
Dale Johannesen7794f2a2008-09-04 00:47:13 +00003993 return 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003994 case Intrinsic::pow:
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003995 visitPow(I);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003996 return 0;
3997 case Intrinsic::pcmarker: {
3998 SDValue Tmp = getValue(I.getOperand(1));
3999 DAG.setRoot(DAG.getNode(ISD::PCMARKER, MVT::Other, getRoot(), Tmp));
4000 return 0;
4001 }
4002 case Intrinsic::readcyclecounter: {
4003 SDValue Op = getRoot();
4004 SDValue Tmp = DAG.getNode(ISD::READCYCLECOUNTER,
4005 DAG.getNodeValueTypes(MVT::i64, MVT::Other), 2,
4006 &Op, 1);
4007 setValue(&I, Tmp);
4008 DAG.setRoot(Tmp.getValue(1));
4009 return 0;
4010 }
4011 case Intrinsic::part_select: {
4012 // Currently not implemented: just abort
4013 assert(0 && "part_select intrinsic not implemented");
4014 abort();
4015 }
4016 case Intrinsic::part_set: {
4017 // Currently not implemented: just abort
4018 assert(0 && "part_set intrinsic not implemented");
4019 abort();
4020 }
4021 case Intrinsic::bswap:
4022 setValue(&I, DAG.getNode(ISD::BSWAP,
4023 getValue(I.getOperand(1)).getValueType(),
4024 getValue(I.getOperand(1))));
4025 return 0;
4026 case Intrinsic::cttz: {
4027 SDValue Arg = getValue(I.getOperand(1));
4028 MVT Ty = Arg.getValueType();
4029 SDValue result = DAG.getNode(ISD::CTTZ, Ty, Arg);
4030 setValue(&I, result);
4031 return 0;
4032 }
4033 case Intrinsic::ctlz: {
4034 SDValue Arg = getValue(I.getOperand(1));
4035 MVT Ty = Arg.getValueType();
4036 SDValue result = DAG.getNode(ISD::CTLZ, Ty, Arg);
4037 setValue(&I, result);
4038 return 0;
4039 }
4040 case Intrinsic::ctpop: {
4041 SDValue Arg = getValue(I.getOperand(1));
4042 MVT Ty = Arg.getValueType();
4043 SDValue result = DAG.getNode(ISD::CTPOP, Ty, Arg);
4044 setValue(&I, result);
4045 return 0;
4046 }
4047 case Intrinsic::stacksave: {
4048 SDValue Op = getRoot();
4049 SDValue Tmp = DAG.getNode(ISD::STACKSAVE,
4050 DAG.getNodeValueTypes(TLI.getPointerTy(), MVT::Other), 2, &Op, 1);
4051 setValue(&I, Tmp);
4052 DAG.setRoot(Tmp.getValue(1));
4053 return 0;
4054 }
4055 case Intrinsic::stackrestore: {
4056 SDValue Tmp = getValue(I.getOperand(1));
4057 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, MVT::Other, getRoot(), Tmp));
4058 return 0;
4059 }
Bill Wendling57344502008-11-18 11:01:33 +00004060 case Intrinsic::stackprotector: {
Bill Wendlingb2a42982008-11-06 02:29:10 +00004061 // Emit code into the DAG to store the stack guard onto the stack.
4062 MachineFunction &MF = DAG.getMachineFunction();
4063 MachineFrameInfo *MFI = MF.getFrameInfo();
4064 MVT PtrTy = TLI.getPointerTy();
4065
Bill Wendlingb7c6ebc2008-11-07 01:23:58 +00004066 SDValue Src = getValue(I.getOperand(1)); // The guard's value.
4067 AllocaInst *Slot = cast<AllocaInst>(I.getOperand(2));
Bill Wendlingb2a42982008-11-06 02:29:10 +00004068
Bill Wendlingb7c6ebc2008-11-07 01:23:58 +00004069 int FI = FuncInfo.StaticAllocaMap[Slot];
Bill Wendlingb2a42982008-11-06 02:29:10 +00004070 MFI->setStackProtectorIndex(FI);
4071
4072 SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
4073
4074 // Store the stack protector onto the stack.
4075 SDValue Result = DAG.getStore(getRoot(), Src, FIN,
4076 PseudoSourceValue::getFixedStack(FI),
4077 0, true);
4078 setValue(&I, Result);
4079 DAG.setRoot(Result);
4080 return 0;
4081 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004082 case Intrinsic::var_annotation:
4083 // Discard annotate attributes
4084 return 0;
4085
4086 case Intrinsic::init_trampoline: {
4087 const Function *F = cast<Function>(I.getOperand(2)->stripPointerCasts());
4088
4089 SDValue Ops[6];
4090 Ops[0] = getRoot();
4091 Ops[1] = getValue(I.getOperand(1));
4092 Ops[2] = getValue(I.getOperand(2));
4093 Ops[3] = getValue(I.getOperand(3));
4094 Ops[4] = DAG.getSrcValue(I.getOperand(1));
4095 Ops[5] = DAG.getSrcValue(F);
4096
4097 SDValue Tmp = DAG.getNode(ISD::TRAMPOLINE,
4098 DAG.getNodeValueTypes(TLI.getPointerTy(),
4099 MVT::Other), 2,
4100 Ops, 6);
4101
4102 setValue(&I, Tmp);
4103 DAG.setRoot(Tmp.getValue(1));
4104 return 0;
4105 }
4106
4107 case Intrinsic::gcroot:
4108 if (GFI) {
4109 Value *Alloca = I.getOperand(1);
4110 Constant *TypeMap = cast<Constant>(I.getOperand(2));
4111
4112 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
4113 GFI->addStackRoot(FI->getIndex(), TypeMap);
4114 }
4115 return 0;
4116
4117 case Intrinsic::gcread:
4118 case Intrinsic::gcwrite:
4119 assert(0 && "GC failed to lower gcread/gcwrite intrinsics!");
4120 return 0;
4121
4122 case Intrinsic::flt_rounds: {
4123 setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, MVT::i32));
4124 return 0;
4125 }
4126
4127 case Intrinsic::trap: {
4128 DAG.setRoot(DAG.getNode(ISD::TRAP, MVT::Other, getRoot()));
4129 return 0;
4130 }
Bill Wendling7cdc3c82008-11-21 02:03:52 +00004131
Bill Wendlingef375462008-11-21 02:38:44 +00004132 case Intrinsic::uadd_with_overflow:
Bill Wendling74c37652008-12-09 22:08:41 +00004133 return implVisitAluOverflow(I, ISD::UADDO);
4134 case Intrinsic::sadd_with_overflow:
4135 return implVisitAluOverflow(I, ISD::SADDO);
4136 case Intrinsic::usub_with_overflow:
4137 return implVisitAluOverflow(I, ISD::USUBO);
4138 case Intrinsic::ssub_with_overflow:
4139 return implVisitAluOverflow(I, ISD::SSUBO);
4140 case Intrinsic::umul_with_overflow:
4141 return implVisitAluOverflow(I, ISD::UMULO);
4142 case Intrinsic::smul_with_overflow:
4143 return implVisitAluOverflow(I, ISD::SMULO);
Bill Wendling7cdc3c82008-11-21 02:03:52 +00004144
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004145 case Intrinsic::prefetch: {
4146 SDValue Ops[4];
4147 Ops[0] = getRoot();
4148 Ops[1] = getValue(I.getOperand(1));
4149 Ops[2] = getValue(I.getOperand(2));
4150 Ops[3] = getValue(I.getOperand(3));
4151 DAG.setRoot(DAG.getNode(ISD::PREFETCH, MVT::Other, &Ops[0], 4));
4152 return 0;
4153 }
4154
4155 case Intrinsic::memory_barrier: {
4156 SDValue Ops[6];
4157 Ops[0] = getRoot();
4158 for (int x = 1; x < 6; ++x)
4159 Ops[x] = getValue(I.getOperand(x));
4160
4161 DAG.setRoot(DAG.getNode(ISD::MEMBARRIER, MVT::Other, &Ops[0], 6));
4162 return 0;
4163 }
4164 case Intrinsic::atomic_cmp_swap: {
4165 SDValue Root = getRoot();
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004166 SDValue L =
4167 DAG.getAtomic(ISD::ATOMIC_CMP_SWAP,
4168 getValue(I.getOperand(2)).getValueType().getSimpleVT(),
4169 Root,
4170 getValue(I.getOperand(1)),
4171 getValue(I.getOperand(2)),
4172 getValue(I.getOperand(3)),
4173 I.getOperand(1));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004174 setValue(&I, L);
4175 DAG.setRoot(L.getValue(1));
4176 return 0;
4177 }
4178 case Intrinsic::atomic_load_add:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004179 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_ADD);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004180 case Intrinsic::atomic_load_sub:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004181 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_SUB);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004182 case Intrinsic::atomic_load_or:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004183 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_OR);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004184 case Intrinsic::atomic_load_xor:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004185 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_XOR);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004186 case Intrinsic::atomic_load_and:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004187 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_AND);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004188 case Intrinsic::atomic_load_nand:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004189 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_NAND);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004190 case Intrinsic::atomic_load_max:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004191 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MAX);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004192 case Intrinsic::atomic_load_min:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004193 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MIN);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004194 case Intrinsic::atomic_load_umin:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004195 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMIN);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004196 case Intrinsic::atomic_load_umax:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004197 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMAX);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004198 case Intrinsic::atomic_swap:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004199 return implVisitBinaryAtomic(I, ISD::ATOMIC_SWAP);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004200 }
4201}
4202
4203
4204void SelectionDAGLowering::LowerCallTo(CallSite CS, SDValue Callee,
4205 bool IsTailCall,
4206 MachineBasicBlock *LandingPad) {
4207 const PointerType *PT = cast<PointerType>(CS.getCalledValue()->getType());
4208 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
4209 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
4210 unsigned BeginLabel = 0, EndLabel = 0;
4211
4212 TargetLowering::ArgListTy Args;
4213 TargetLowering::ArgListEntry Entry;
4214 Args.reserve(CS.arg_size());
4215 for (CallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
4216 i != e; ++i) {
4217 SDValue ArgNode = getValue(*i);
4218 Entry.Node = ArgNode; Entry.Ty = (*i)->getType();
4219
4220 unsigned attrInd = i - CS.arg_begin() + 1;
Devang Patel05988662008-09-25 21:00:45 +00004221 Entry.isSExt = CS.paramHasAttr(attrInd, Attribute::SExt);
4222 Entry.isZExt = CS.paramHasAttr(attrInd, Attribute::ZExt);
4223 Entry.isInReg = CS.paramHasAttr(attrInd, Attribute::InReg);
4224 Entry.isSRet = CS.paramHasAttr(attrInd, Attribute::StructRet);
4225 Entry.isNest = CS.paramHasAttr(attrInd, Attribute::Nest);
4226 Entry.isByVal = CS.paramHasAttr(attrInd, Attribute::ByVal);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004227 Entry.Alignment = CS.getParamAlignment(attrInd);
4228 Args.push_back(Entry);
4229 }
4230
4231 if (LandingPad && MMI) {
4232 // Insert a label before the invoke call to mark the try range. This can be
4233 // used to detect deletion of the invoke via the MachineModuleInfo.
4234 BeginLabel = MMI->NextLabelID();
4235 // Both PendingLoads and PendingExports must be flushed here;
4236 // this call might not return.
4237 (void)getRoot();
4238 DAG.setRoot(DAG.getLabel(ISD::EH_LABEL, getControlRoot(), BeginLabel));
4239 }
4240
4241 std::pair<SDValue,SDValue> Result =
4242 TLI.LowerCallTo(getRoot(), CS.getType(),
Devang Patel05988662008-09-25 21:00:45 +00004243 CS.paramHasAttr(0, Attribute::SExt),
Dale Johannesen86098bd2008-09-26 19:31:26 +00004244 CS.paramHasAttr(0, Attribute::ZExt), FTy->isVarArg(),
4245 CS.paramHasAttr(0, Attribute::InReg),
4246 CS.getCallingConv(),
Dan Gohman1937e2f2008-09-16 01:42:28 +00004247 IsTailCall && PerformTailCallOpt,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004248 Callee, Args, DAG);
4249 if (CS.getType() != Type::VoidTy)
4250 setValue(CS.getInstruction(), Result.first);
4251 DAG.setRoot(Result.second);
4252
4253 if (LandingPad && MMI) {
4254 // Insert a label at the end of the invoke call to mark the try range. This
4255 // can be used to detect deletion of the invoke via the MachineModuleInfo.
4256 EndLabel = MMI->NextLabelID();
4257 DAG.setRoot(DAG.getLabel(ISD::EH_LABEL, getRoot(), EndLabel));
4258
4259 // Inform MachineModuleInfo of range.
4260 MMI->addInvoke(LandingPad, BeginLabel, EndLabel);
4261 }
4262}
4263
4264
4265void SelectionDAGLowering::visitCall(CallInst &I) {
4266 const char *RenameFn = 0;
4267 if (Function *F = I.getCalledFunction()) {
4268 if (F->isDeclaration()) {
4269 if (unsigned IID = F->getIntrinsicID()) {
4270 RenameFn = visitIntrinsicCall(I, IID);
4271 if (!RenameFn)
4272 return;
4273 }
4274 }
4275
4276 // Check for well-known libc/libm calls. If the function is internal, it
4277 // can't be a library call.
4278 unsigned NameLen = F->getNameLen();
Rafael Espindolabb46f522009-01-15 20:18:42 +00004279 if (!F->hasLocalLinkage() && NameLen) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004280 const char *NameStr = F->getNameStart();
4281 if (NameStr[0] == 'c' &&
4282 ((NameLen == 8 && !strcmp(NameStr, "copysign")) ||
4283 (NameLen == 9 && !strcmp(NameStr, "copysignf")))) {
4284 if (I.getNumOperands() == 3 && // Basic sanity checks.
4285 I.getOperand(1)->getType()->isFloatingPoint() &&
4286 I.getType() == I.getOperand(1)->getType() &&
4287 I.getType() == I.getOperand(2)->getType()) {
4288 SDValue LHS = getValue(I.getOperand(1));
4289 SDValue RHS = getValue(I.getOperand(2));
4290 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, LHS.getValueType(),
4291 LHS, RHS));
4292 return;
4293 }
4294 } else if (NameStr[0] == 'f' &&
4295 ((NameLen == 4 && !strcmp(NameStr, "fabs")) ||
4296 (NameLen == 5 && !strcmp(NameStr, "fabsf")) ||
4297 (NameLen == 5 && !strcmp(NameStr, "fabsl")))) {
4298 if (I.getNumOperands() == 2 && // Basic sanity checks.
4299 I.getOperand(1)->getType()->isFloatingPoint() &&
4300 I.getType() == I.getOperand(1)->getType()) {
4301 SDValue Tmp = getValue(I.getOperand(1));
4302 setValue(&I, DAG.getNode(ISD::FABS, Tmp.getValueType(), Tmp));
4303 return;
4304 }
4305 } else if (NameStr[0] == 's' &&
4306 ((NameLen == 3 && !strcmp(NameStr, "sin")) ||
4307 (NameLen == 4 && !strcmp(NameStr, "sinf")) ||
4308 (NameLen == 4 && !strcmp(NameStr, "sinl")))) {
4309 if (I.getNumOperands() == 2 && // Basic sanity checks.
4310 I.getOperand(1)->getType()->isFloatingPoint() &&
4311 I.getType() == I.getOperand(1)->getType()) {
4312 SDValue Tmp = getValue(I.getOperand(1));
4313 setValue(&I, DAG.getNode(ISD::FSIN, Tmp.getValueType(), Tmp));
4314 return;
4315 }
4316 } else if (NameStr[0] == 'c' &&
4317 ((NameLen == 3 && !strcmp(NameStr, "cos")) ||
4318 (NameLen == 4 && !strcmp(NameStr, "cosf")) ||
4319 (NameLen == 4 && !strcmp(NameStr, "cosl")))) {
4320 if (I.getNumOperands() == 2 && // Basic sanity checks.
4321 I.getOperand(1)->getType()->isFloatingPoint() &&
4322 I.getType() == I.getOperand(1)->getType()) {
4323 SDValue Tmp = getValue(I.getOperand(1));
4324 setValue(&I, DAG.getNode(ISD::FCOS, Tmp.getValueType(), Tmp));
4325 return;
4326 }
4327 }
4328 }
4329 } else if (isa<InlineAsm>(I.getOperand(0))) {
4330 visitInlineAsm(&I);
4331 return;
4332 }
4333
4334 SDValue Callee;
4335 if (!RenameFn)
4336 Callee = getValue(I.getOperand(0));
4337 else
Bill Wendling056292f2008-09-16 21:48:12 +00004338 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004339
4340 LowerCallTo(&I, Callee, I.isTailCall());
4341}
4342
4343
4344/// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
4345/// this value and returns the result as a ValueVT value. This uses
4346/// Chain/Flag as the input and updates them for the output Chain/Flag.
4347/// If the Flag pointer is NULL, no flag is used.
4348SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
4349 SDValue &Chain,
4350 SDValue *Flag) const {
4351 // Assemble the legal parts into the final values.
4352 SmallVector<SDValue, 4> Values(ValueVTs.size());
4353 SmallVector<SDValue, 8> Parts;
4354 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
4355 // Copy the legal parts from the registers.
4356 MVT ValueVT = ValueVTs[Value];
4357 unsigned NumRegs = TLI->getNumRegisters(ValueVT);
4358 MVT RegisterVT = RegVTs[Value];
4359
4360 Parts.resize(NumRegs);
4361 for (unsigned i = 0; i != NumRegs; ++i) {
4362 SDValue P;
4363 if (Flag == 0)
4364 P = DAG.getCopyFromReg(Chain, Regs[Part+i], RegisterVT);
4365 else {
4366 P = DAG.getCopyFromReg(Chain, Regs[Part+i], RegisterVT, *Flag);
4367 *Flag = P.getValue(2);
4368 }
4369 Chain = P.getValue(1);
4370
4371 // If the source register was virtual and if we know something about it,
4372 // add an assert node.
4373 if (TargetRegisterInfo::isVirtualRegister(Regs[Part+i]) &&
4374 RegisterVT.isInteger() && !RegisterVT.isVector()) {
4375 unsigned SlotNo = Regs[Part+i]-TargetRegisterInfo::FirstVirtualRegister;
4376 FunctionLoweringInfo &FLI = DAG.getFunctionLoweringInfo();
4377 if (FLI.LiveOutRegInfo.size() > SlotNo) {
4378 FunctionLoweringInfo::LiveOutInfo &LOI = FLI.LiveOutRegInfo[SlotNo];
4379
4380 unsigned RegSize = RegisterVT.getSizeInBits();
4381 unsigned NumSignBits = LOI.NumSignBits;
4382 unsigned NumZeroBits = LOI.KnownZero.countLeadingOnes();
4383
4384 // FIXME: We capture more information than the dag can represent. For
4385 // now, just use the tightest assertzext/assertsext possible.
4386 bool isSExt = true;
4387 MVT FromVT(MVT::Other);
4388 if (NumSignBits == RegSize)
4389 isSExt = true, FromVT = MVT::i1; // ASSERT SEXT 1
4390 else if (NumZeroBits >= RegSize-1)
4391 isSExt = false, FromVT = MVT::i1; // ASSERT ZEXT 1
4392 else if (NumSignBits > RegSize-8)
4393 isSExt = true, FromVT = MVT::i8; // ASSERT SEXT 8
4394 else if (NumZeroBits >= RegSize-9)
4395 isSExt = false, FromVT = MVT::i8; // ASSERT ZEXT 8
4396 else if (NumSignBits > RegSize-16)
Bill Wendling181b6272008-10-19 20:34:04 +00004397 isSExt = true, FromVT = MVT::i16; // ASSERT SEXT 16
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004398 else if (NumZeroBits >= RegSize-17)
Bill Wendling181b6272008-10-19 20:34:04 +00004399 isSExt = false, FromVT = MVT::i16; // ASSERT ZEXT 16
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004400 else if (NumSignBits > RegSize-32)
Bill Wendling181b6272008-10-19 20:34:04 +00004401 isSExt = true, FromVT = MVT::i32; // ASSERT SEXT 32
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004402 else if (NumZeroBits >= RegSize-33)
Bill Wendling181b6272008-10-19 20:34:04 +00004403 isSExt = false, FromVT = MVT::i32; // ASSERT ZEXT 32
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004404
4405 if (FromVT != MVT::Other) {
4406 P = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext,
4407 RegisterVT, P, DAG.getValueType(FromVT));
4408
4409 }
4410 }
4411 }
4412
4413 Parts[i] = P;
4414 }
4415
4416 Values[Value] = getCopyFromParts(DAG, Parts.begin(), NumRegs, RegisterVT,
4417 ValueVT);
4418 Part += NumRegs;
4419 Parts.clear();
4420 }
4421
Duncan Sandsaaffa052008-12-01 11:41:29 +00004422 return DAG.getNode(ISD::MERGE_VALUES,
4423 DAG.getVTList(&ValueVTs[0], ValueVTs.size()),
4424 &Values[0], ValueVTs.size());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004425}
4426
4427/// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
4428/// specified value into the registers specified by this object. This uses
4429/// Chain/Flag as the input and updates them for the output Chain/Flag.
4430/// If the Flag pointer is NULL, no flag is used.
4431void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG,
4432 SDValue &Chain, SDValue *Flag) const {
4433 // Get the list of the values's legal parts.
4434 unsigned NumRegs = Regs.size();
4435 SmallVector<SDValue, 8> Parts(NumRegs);
4436 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
4437 MVT ValueVT = ValueVTs[Value];
4438 unsigned NumParts = TLI->getNumRegisters(ValueVT);
4439 MVT RegisterVT = RegVTs[Value];
4440
4441 getCopyToParts(DAG, Val.getValue(Val.getResNo() + Value),
4442 &Parts[Part], NumParts, RegisterVT);
4443 Part += NumParts;
4444 }
4445
4446 // Copy the parts into the registers.
4447 SmallVector<SDValue, 8> Chains(NumRegs);
4448 for (unsigned i = 0; i != NumRegs; ++i) {
4449 SDValue Part;
4450 if (Flag == 0)
4451 Part = DAG.getCopyToReg(Chain, Regs[i], Parts[i]);
4452 else {
4453 Part = DAG.getCopyToReg(Chain, Regs[i], Parts[i], *Flag);
4454 *Flag = Part.getValue(1);
4455 }
4456 Chains[i] = Part.getValue(0);
4457 }
4458
4459 if (NumRegs == 1 || Flag)
4460 // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is
4461 // flagged to it. That is the CopyToReg nodes and the user are considered
4462 // a single scheduling unit. If we create a TokenFactor and return it as
4463 // chain, then the TokenFactor is both a predecessor (operand) of the
4464 // user as well as a successor (the TF operands are flagged to the user).
4465 // c1, f1 = CopyToReg
4466 // c2, f2 = CopyToReg
4467 // c3 = TokenFactor c1, c2
4468 // ...
4469 // = op c3, ..., f2
4470 Chain = Chains[NumRegs-1];
4471 else
4472 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other, &Chains[0], NumRegs);
4473}
4474
4475/// AddInlineAsmOperands - Add this value to the specified inlineasm node
4476/// operand list. This adds the code marker and includes the number of
4477/// values added into it.
4478void RegsForValue::AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
4479 std::vector<SDValue> &Ops) const {
4480 MVT IntPtrTy = DAG.getTargetLoweringInfo().getPointerTy();
4481 Ops.push_back(DAG.getTargetConstant(Code | (Regs.size() << 3), IntPtrTy));
4482 for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
4483 unsigned NumRegs = TLI->getNumRegisters(ValueVTs[Value]);
4484 MVT RegisterVT = RegVTs[Value];
Chris Lattner58f15c42008-10-17 16:21:11 +00004485 for (unsigned i = 0; i != NumRegs; ++i) {
4486 assert(Reg < Regs.size() && "Mismatch in # registers expected");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004487 Ops.push_back(DAG.getRegister(Regs[Reg++], RegisterVT));
Chris Lattner58f15c42008-10-17 16:21:11 +00004488 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004489 }
4490}
4491
4492/// isAllocatableRegister - If the specified register is safe to allocate,
4493/// i.e. it isn't a stack pointer or some other special register, return the
4494/// register class for the register. Otherwise, return null.
4495static const TargetRegisterClass *
4496isAllocatableRegister(unsigned Reg, MachineFunction &MF,
4497 const TargetLowering &TLI,
4498 const TargetRegisterInfo *TRI) {
4499 MVT FoundVT = MVT::Other;
4500 const TargetRegisterClass *FoundRC = 0;
4501 for (TargetRegisterInfo::regclass_iterator RCI = TRI->regclass_begin(),
4502 E = TRI->regclass_end(); RCI != E; ++RCI) {
4503 MVT ThisVT = MVT::Other;
4504
4505 const TargetRegisterClass *RC = *RCI;
4506 // If none of the the value types for this register class are valid, we
4507 // can't use it. For example, 64-bit reg classes on 32-bit targets.
4508 for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
4509 I != E; ++I) {
4510 if (TLI.isTypeLegal(*I)) {
4511 // If we have already found this register in a different register class,
4512 // choose the one with the largest VT specified. For example, on
4513 // PowerPC, we favor f64 register classes over f32.
4514 if (FoundVT == MVT::Other || FoundVT.bitsLT(*I)) {
4515 ThisVT = *I;
4516 break;
4517 }
4518 }
4519 }
4520
4521 if (ThisVT == MVT::Other) continue;
4522
4523 // NOTE: This isn't ideal. In particular, this might allocate the
4524 // frame pointer in functions that need it (due to them not being taken
4525 // out of allocation, because a variable sized allocation hasn't been seen
4526 // yet). This is a slight code pessimization, but should still work.
4527 for (TargetRegisterClass::iterator I = RC->allocation_order_begin(MF),
4528 E = RC->allocation_order_end(MF); I != E; ++I)
4529 if (*I == Reg) {
4530 // We found a matching register class. Keep looking at others in case
4531 // we find one with larger registers that this physreg is also in.
4532 FoundRC = RC;
4533 FoundVT = ThisVT;
4534 break;
4535 }
4536 }
4537 return FoundRC;
4538}
4539
4540
4541namespace llvm {
4542/// AsmOperandInfo - This contains information for each constraint that we are
4543/// lowering.
Daniel Dunbarc0c3b9a2008-09-10 04:16:29 +00004544struct VISIBILITY_HIDDEN SDISelAsmOperandInfo :
4545 public TargetLowering::AsmOperandInfo {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004546 /// CallOperand - If this is the result output operand or a clobber
4547 /// this is null, otherwise it is the incoming operand to the CallInst.
4548 /// This gets modified as the asm is processed.
4549 SDValue CallOperand;
4550
4551 /// AssignedRegs - If this is a register or register class operand, this
4552 /// contains the set of register corresponding to the operand.
4553 RegsForValue AssignedRegs;
4554
4555 explicit SDISelAsmOperandInfo(const InlineAsm::ConstraintInfo &info)
4556 : TargetLowering::AsmOperandInfo(info), CallOperand(0,0) {
4557 }
4558
4559 /// MarkAllocatedRegs - Once AssignedRegs is set, mark the assigned registers
4560 /// busy in OutputRegs/InputRegs.
4561 void MarkAllocatedRegs(bool isOutReg, bool isInReg,
4562 std::set<unsigned> &OutputRegs,
4563 std::set<unsigned> &InputRegs,
4564 const TargetRegisterInfo &TRI) const {
4565 if (isOutReg) {
4566 for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i)
4567 MarkRegAndAliases(AssignedRegs.Regs[i], OutputRegs, TRI);
4568 }
4569 if (isInReg) {
4570 for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i)
4571 MarkRegAndAliases(AssignedRegs.Regs[i], InputRegs, TRI);
4572 }
4573 }
Chris Lattner81249c92008-10-17 17:05:25 +00004574
4575 /// getCallOperandValMVT - Return the MVT of the Value* that this operand
4576 /// corresponds to. If there is no Value* for this operand, it returns
4577 /// MVT::Other.
4578 MVT getCallOperandValMVT(const TargetLowering &TLI,
4579 const TargetData *TD) const {
4580 if (CallOperandVal == 0) return MVT::Other;
4581
4582 if (isa<BasicBlock>(CallOperandVal))
4583 return TLI.getPointerTy();
4584
4585 const llvm::Type *OpTy = CallOperandVal->getType();
4586
4587 // If this is an indirect operand, the operand is a pointer to the
4588 // accessed type.
4589 if (isIndirect)
4590 OpTy = cast<PointerType>(OpTy)->getElementType();
4591
4592 // If OpTy is not a single value, it may be a struct/union that we
4593 // can tile with integers.
4594 if (!OpTy->isSingleValueType() && OpTy->isSized()) {
4595 unsigned BitSize = TD->getTypeSizeInBits(OpTy);
4596 switch (BitSize) {
4597 default: break;
4598 case 1:
4599 case 8:
4600 case 16:
4601 case 32:
4602 case 64:
Chris Lattnercfc14c12008-10-17 19:59:51 +00004603 case 128:
Chris Lattner81249c92008-10-17 17:05:25 +00004604 OpTy = IntegerType::get(BitSize);
4605 break;
4606 }
4607 }
4608
4609 return TLI.getValueType(OpTy, true);
4610 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004611
4612private:
4613 /// MarkRegAndAliases - Mark the specified register and all aliases in the
4614 /// specified set.
4615 static void MarkRegAndAliases(unsigned Reg, std::set<unsigned> &Regs,
4616 const TargetRegisterInfo &TRI) {
4617 assert(TargetRegisterInfo::isPhysicalRegister(Reg) && "Isn't a physreg");
4618 Regs.insert(Reg);
4619 if (const unsigned *Aliases = TRI.getAliasSet(Reg))
4620 for (; *Aliases; ++Aliases)
4621 Regs.insert(*Aliases);
4622 }
4623};
4624} // end llvm namespace.
4625
4626
4627/// GetRegistersForValue - Assign registers (virtual or physical) for the
4628/// specified operand. We prefer to assign virtual registers, to allow the
4629/// register allocator handle the assignment process. However, if the asm uses
4630/// features that we can't model on machineinstrs, we have SDISel do the
4631/// allocation. This produces generally horrible, but correct, code.
4632///
4633/// OpInfo describes the operand.
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004634/// Input and OutputRegs are the set of already allocated physical registers.
4635///
4636void SelectionDAGLowering::
Dale Johannesen8e3455b2008-09-24 23:13:09 +00004637GetRegistersForValue(SDISelAsmOperandInfo &OpInfo,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004638 std::set<unsigned> &OutputRegs,
4639 std::set<unsigned> &InputRegs) {
4640 // Compute whether this value requires an input register, an output register,
4641 // or both.
4642 bool isOutReg = false;
4643 bool isInReg = false;
4644 switch (OpInfo.Type) {
4645 case InlineAsm::isOutput:
4646 isOutReg = true;
4647
Dale Johannesen8e3455b2008-09-24 23:13:09 +00004648 // If there is an input constraint that matches this, we need to reserve
4649 // the input register so no other inputs allocate to it.
Chris Lattner6bdcda32008-10-17 16:47:46 +00004650 isInReg = OpInfo.hasMatchingInput();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004651 break;
4652 case InlineAsm::isInput:
4653 isInReg = true;
4654 isOutReg = false;
4655 break;
4656 case InlineAsm::isClobber:
4657 isOutReg = true;
4658 isInReg = true;
4659 break;
4660 }
4661
4662
4663 MachineFunction &MF = DAG.getMachineFunction();
4664 SmallVector<unsigned, 4> Regs;
4665
4666 // If this is a constraint for a single physreg, or a constraint for a
4667 // register class, find it.
4668 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
4669 TLI.getRegForInlineAsmConstraint(OpInfo.ConstraintCode,
4670 OpInfo.ConstraintVT);
4671
4672 unsigned NumRegs = 1;
Chris Lattner01426e12008-10-21 00:45:36 +00004673 if (OpInfo.ConstraintVT != MVT::Other) {
4674 // If this is a FP input in an integer register (or visa versa) insert a bit
4675 // cast of the input value. More generally, handle any case where the input
4676 // value disagrees with the register class we plan to stick this in.
4677 if (OpInfo.Type == InlineAsm::isInput &&
4678 PhysReg.second && !PhysReg.second->hasType(OpInfo.ConstraintVT)) {
4679 // Try to convert to the first MVT that the reg class contains. If the
4680 // types are identical size, use a bitcast to convert (e.g. two differing
4681 // vector types).
4682 MVT RegVT = *PhysReg.second->vt_begin();
4683 if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) {
4684 OpInfo.CallOperand = DAG.getNode(ISD::BIT_CONVERT, RegVT,
4685 OpInfo.CallOperand);
4686 OpInfo.ConstraintVT = RegVT;
4687 } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
4688 // If the input is a FP value and we want it in FP registers, do a
4689 // bitcast to the corresponding integer type. This turns an f64 value
4690 // into i64, which can be passed with two i32 values on a 32-bit
4691 // machine.
4692 RegVT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits());
4693 OpInfo.CallOperand = DAG.getNode(ISD::BIT_CONVERT, RegVT,
4694 OpInfo.CallOperand);
4695 OpInfo.ConstraintVT = RegVT;
4696 }
4697 }
4698
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004699 NumRegs = TLI.getNumRegisters(OpInfo.ConstraintVT);
Chris Lattner01426e12008-10-21 00:45:36 +00004700 }
4701
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004702 MVT RegVT;
4703 MVT ValueVT = OpInfo.ConstraintVT;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004704
4705 // If this is a constraint for a specific physical register, like {r17},
4706 // assign it now.
4707 if (PhysReg.first) {
4708 if (OpInfo.ConstraintVT == MVT::Other)
4709 ValueVT = *PhysReg.second->vt_begin();
4710
4711 // Get the actual register value type. This is important, because the user
4712 // may have asked for (e.g.) the AX register in i32 type. We need to
4713 // remember that AX is actually i16 to get the right extension.
4714 RegVT = *PhysReg.second->vt_begin();
4715
4716 // This is a explicit reference to a physical register.
4717 Regs.push_back(PhysReg.first);
4718
4719 // If this is an expanded reference, add the rest of the regs to Regs.
4720 if (NumRegs != 1) {
4721 TargetRegisterClass::iterator I = PhysReg.second->begin();
4722 for (; *I != PhysReg.first; ++I)
4723 assert(I != PhysReg.second->end() && "Didn't find reg!");
4724
4725 // Already added the first reg.
4726 --NumRegs; ++I;
4727 for (; NumRegs; --NumRegs, ++I) {
4728 assert(I != PhysReg.second->end() && "Ran out of registers to allocate!");
4729 Regs.push_back(*I);
4730 }
4731 }
4732 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, RegVT, ValueVT);
4733 const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
4734 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TRI);
4735 return;
4736 }
4737
4738 // Otherwise, if this was a reference to an LLVM register class, create vregs
4739 // for this reference.
4740 std::vector<unsigned> RegClassRegs;
4741 const TargetRegisterClass *RC = PhysReg.second;
4742 if (RC) {
Dale Johannesen8e3455b2008-09-24 23:13:09 +00004743 // If this is a tied register, our regalloc doesn't know how to maintain
Chris Lattner58f15c42008-10-17 16:21:11 +00004744 // the constraint, so we have to pick a register to pin the input/output to.
4745 // If it isn't a matched constraint, go ahead and create vreg and let the
4746 // regalloc do its thing.
Chris Lattner6bdcda32008-10-17 16:47:46 +00004747 if (!OpInfo.hasMatchingInput()) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004748 RegVT = *PhysReg.second->vt_begin();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004749 if (OpInfo.ConstraintVT == MVT::Other)
4750 ValueVT = RegVT;
4751
4752 // Create the appropriate number of virtual registers.
4753 MachineRegisterInfo &RegInfo = MF.getRegInfo();
4754 for (; NumRegs; --NumRegs)
4755 Regs.push_back(RegInfo.createVirtualRegister(PhysReg.second));
4756
4757 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, RegVT, ValueVT);
4758 return;
4759 }
4760
4761 // Otherwise, we can't allocate it. Let the code below figure out how to
4762 // maintain these constraints.
4763 RegClassRegs.assign(PhysReg.second->begin(), PhysReg.second->end());
4764
4765 } else {
4766 // This is a reference to a register class that doesn't directly correspond
4767 // to an LLVM register class. Allocate NumRegs consecutive, available,
4768 // registers from the class.
4769 RegClassRegs = TLI.getRegClassForInlineAsmConstraint(OpInfo.ConstraintCode,
4770 OpInfo.ConstraintVT);
4771 }
4772
4773 const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
4774 unsigned NumAllocated = 0;
4775 for (unsigned i = 0, e = RegClassRegs.size(); i != e; ++i) {
4776 unsigned Reg = RegClassRegs[i];
4777 // See if this register is available.
4778 if ((isOutReg && OutputRegs.count(Reg)) || // Already used.
4779 (isInReg && InputRegs.count(Reg))) { // Already used.
4780 // Make sure we find consecutive registers.
4781 NumAllocated = 0;
4782 continue;
4783 }
4784
4785 // Check to see if this register is allocatable (i.e. don't give out the
4786 // stack pointer).
4787 if (RC == 0) {
4788 RC = isAllocatableRegister(Reg, MF, TLI, TRI);
4789 if (!RC) { // Couldn't allocate this register.
4790 // Reset NumAllocated to make sure we return consecutive registers.
4791 NumAllocated = 0;
4792 continue;
4793 }
4794 }
4795
4796 // Okay, this register is good, we can use it.
4797 ++NumAllocated;
4798
4799 // If we allocated enough consecutive registers, succeed.
4800 if (NumAllocated == NumRegs) {
4801 unsigned RegStart = (i-NumAllocated)+1;
4802 unsigned RegEnd = i+1;
4803 // Mark all of the allocated registers used.
4804 for (unsigned i = RegStart; i != RegEnd; ++i)
4805 Regs.push_back(RegClassRegs[i]);
4806
4807 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, *RC->vt_begin(),
4808 OpInfo.ConstraintVT);
4809 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TRI);
4810 return;
4811 }
4812 }
4813
4814 // Otherwise, we couldn't allocate enough registers for this.
4815}
4816
Evan Chengda43bcf2008-09-24 00:05:32 +00004817/// hasInlineAsmMemConstraint - Return true if the inline asm instruction being
4818/// processed uses a memory 'm' constraint.
4819static bool
4820hasInlineAsmMemConstraint(std::vector<InlineAsm::ConstraintInfo> &CInfos,
Dan Gohmane9530ec2009-01-15 16:58:17 +00004821 const TargetLowering &TLI) {
Evan Chengda43bcf2008-09-24 00:05:32 +00004822 for (unsigned i = 0, e = CInfos.size(); i != e; ++i) {
4823 InlineAsm::ConstraintInfo &CI = CInfos[i];
4824 for (unsigned j = 0, ee = CI.Codes.size(); j != ee; ++j) {
4825 TargetLowering::ConstraintType CType = TLI.getConstraintType(CI.Codes[j]);
4826 if (CType == TargetLowering::C_Memory)
4827 return true;
4828 }
4829 }
4830
4831 return false;
4832}
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004833
4834/// visitInlineAsm - Handle a call to an InlineAsm object.
4835///
4836void SelectionDAGLowering::visitInlineAsm(CallSite CS) {
4837 InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
4838
4839 /// ConstraintOperands - Information about all of the constraints.
4840 std::vector<SDISelAsmOperandInfo> ConstraintOperands;
4841
4842 SDValue Chain = getRoot();
4843 SDValue Flag;
4844
4845 std::set<unsigned> OutputRegs, InputRegs;
4846
4847 // Do a prepass over the constraints, canonicalizing them, and building up the
4848 // ConstraintOperands list.
4849 std::vector<InlineAsm::ConstraintInfo>
4850 ConstraintInfos = IA->ParseConstraints();
4851
Evan Chengda43bcf2008-09-24 00:05:32 +00004852 bool hasMemory = hasInlineAsmMemConstraint(ConstraintInfos, TLI);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004853
4854 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst.
4855 unsigned ResNo = 0; // ResNo - The result number of the next output.
4856 for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) {
4857 ConstraintOperands.push_back(SDISelAsmOperandInfo(ConstraintInfos[i]));
4858 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
4859
4860 MVT OpVT = MVT::Other;
4861
4862 // Compute the value type for each operand.
4863 switch (OpInfo.Type) {
4864 case InlineAsm::isOutput:
4865 // Indirect outputs just consume an argument.
4866 if (OpInfo.isIndirect) {
4867 OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
4868 break;
4869 }
Chris Lattner2a0b96c2008-10-18 18:49:30 +00004870
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004871 // The return value of the call is this value. As such, there is no
4872 // corresponding argument.
4873 assert(CS.getType() != Type::VoidTy && "Bad inline asm!");
4874 if (const StructType *STy = dyn_cast<StructType>(CS.getType())) {
4875 OpVT = TLI.getValueType(STy->getElementType(ResNo));
4876 } else {
4877 assert(ResNo == 0 && "Asm only has one result!");
4878 OpVT = TLI.getValueType(CS.getType());
4879 }
4880 ++ResNo;
4881 break;
4882 case InlineAsm::isInput:
4883 OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
4884 break;
4885 case InlineAsm::isClobber:
4886 // Nothing to do.
4887 break;
4888 }
4889
4890 // If this is an input or an indirect output, process the call argument.
4891 // BasicBlocks are labels, currently appearing only in asm's.
4892 if (OpInfo.CallOperandVal) {
Chris Lattner81249c92008-10-17 17:05:25 +00004893 if (BasicBlock *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004894 OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
Chris Lattner81249c92008-10-17 17:05:25 +00004895 } else {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004896 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004897 }
Chris Lattner81249c92008-10-17 17:05:25 +00004898
4899 OpVT = OpInfo.getCallOperandValMVT(TLI, TD);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004900 }
4901
4902 OpInfo.ConstraintVT = OpVT;
Chris Lattner2a0b96c2008-10-18 18:49:30 +00004903 }
4904
4905 // Second pass over the constraints: compute which constraint option to use
4906 // and assign registers to constraints that want a specific physreg.
4907 for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) {
4908 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
4909
4910 // If this is an output operand with a matching input operand, look up the
Evan Cheng09dc9c02008-12-16 18:21:39 +00004911 // matching input. If their types mismatch, e.g. one is an integer, the
4912 // other is floating point, or their sizes are different, flag it as an
4913 // error.
Chris Lattner2a0b96c2008-10-18 18:49:30 +00004914 if (OpInfo.hasMatchingInput()) {
4915 SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
4916 if (OpInfo.ConstraintVT != Input.ConstraintVT) {
Evan Cheng09dc9c02008-12-16 18:21:39 +00004917 if ((OpInfo.ConstraintVT.isInteger() !=
4918 Input.ConstraintVT.isInteger()) ||
4919 (OpInfo.ConstraintVT.getSizeInBits() !=
4920 Input.ConstraintVT.getSizeInBits())) {
4921 cerr << "Unsupported asm: input constraint with a matching output "
4922 << "constraint of incompatible type!\n";
4923 exit(1);
4924 }
4925 Input.ConstraintVT = OpInfo.ConstraintVT;
Chris Lattner2a0b96c2008-10-18 18:49:30 +00004926 }
4927 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004928
4929 // Compute the constraint code and ConstraintType to use.
Evan Chengda43bcf2008-09-24 00:05:32 +00004930 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, hasMemory, &DAG);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004931
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004932 // If this is a memory input, and if the operand is not indirect, do what we
4933 // need to to provide an address for the memory input.
4934 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
4935 !OpInfo.isIndirect) {
4936 assert(OpInfo.Type == InlineAsm::isInput &&
4937 "Can only indirectify direct input operands!");
4938
4939 // Memory operands really want the address of the value. If we don't have
4940 // an indirect input, put it in the constpool if we can, otherwise spill
4941 // it to a stack slot.
4942
4943 // If the operand is a float, integer, or vector constant, spill to a
4944 // constant pool entry to get its address.
4945 Value *OpVal = OpInfo.CallOperandVal;
4946 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
4947 isa<ConstantVector>(OpVal)) {
4948 OpInfo.CallOperand = DAG.getConstantPool(cast<Constant>(OpVal),
4949 TLI.getPointerTy());
4950 } else {
4951 // Otherwise, create a stack slot and emit a store to it before the
4952 // asm.
4953 const Type *Ty = OpVal->getType();
Duncan Sandsceb4d1a2009-01-12 20:38:59 +00004954 uint64_t TySize = TLI.getTargetData()->getTypePaddedSize(Ty);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004955 unsigned Align = TLI.getTargetData()->getPrefTypeAlignment(Ty);
4956 MachineFunction &MF = DAG.getMachineFunction();
4957 int SSFI = MF.getFrameInfo()->CreateStackObject(TySize, Align);
4958 SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getPointerTy());
4959 Chain = DAG.getStore(Chain, OpInfo.CallOperand, StackSlot, NULL, 0);
4960 OpInfo.CallOperand = StackSlot;
4961 }
4962
4963 // There is no longer a Value* corresponding to this operand.
4964 OpInfo.CallOperandVal = 0;
4965 // It is now an indirect operand.
4966 OpInfo.isIndirect = true;
4967 }
4968
4969 // If this constraint is for a specific register, allocate it before
4970 // anything else.
4971 if (OpInfo.ConstraintType == TargetLowering::C_Register)
Dale Johannesen8e3455b2008-09-24 23:13:09 +00004972 GetRegistersForValue(OpInfo, OutputRegs, InputRegs);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004973 }
4974 ConstraintInfos.clear();
4975
4976
4977 // Second pass - Loop over all of the operands, assigning virtual or physregs
Chris Lattner58f15c42008-10-17 16:21:11 +00004978 // to register class operands.
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004979 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
4980 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
4981
4982 // C_Register operands have already been allocated, Other/Memory don't need
4983 // to be.
4984 if (OpInfo.ConstraintType == TargetLowering::C_RegisterClass)
Dale Johannesen8e3455b2008-09-24 23:13:09 +00004985 GetRegistersForValue(OpInfo, OutputRegs, InputRegs);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004986 }
4987
4988 // AsmNodeOperands - The operands for the ISD::INLINEASM node.
4989 std::vector<SDValue> AsmNodeOperands;
4990 AsmNodeOperands.push_back(SDValue()); // reserve space for input chain
4991 AsmNodeOperands.push_back(
Bill Wendling056292f2008-09-16 21:48:12 +00004992 DAG.getTargetExternalSymbol(IA->getAsmString().c_str(), MVT::Other));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004993
4994
4995 // Loop over all of the inputs, copying the operand values into the
4996 // appropriate registers and processing the output regs.
4997 RegsForValue RetValRegs;
4998
4999 // IndirectStoresToEmit - The set of stores to emit after the inline asm node.
5000 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
5001
5002 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
5003 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
5004
5005 switch (OpInfo.Type) {
5006 case InlineAsm::isOutput: {
5007 if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass &&
5008 OpInfo.ConstraintType != TargetLowering::C_Register) {
5009 // Memory output, or 'other' output (e.g. 'X' constraint).
5010 assert(OpInfo.isIndirect && "Memory output must be indirect operand");
5011
5012 // Add information to the INLINEASM node to know about this output.
Dale Johannesen86b49f82008-09-24 01:07:17 +00005013 unsigned ResOpType = 4/*MEM*/ | (1<<3);
5014 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005015 TLI.getPointerTy()));
5016 AsmNodeOperands.push_back(OpInfo.CallOperand);
5017 break;
5018 }
5019
5020 // Otherwise, this is a register or register class output.
5021
5022 // Copy the output from the appropriate register. Find a register that
5023 // we can use.
5024 if (OpInfo.AssignedRegs.Regs.empty()) {
5025 cerr << "Couldn't allocate output reg for constraint '"
5026 << OpInfo.ConstraintCode << "'!\n";
5027 exit(1);
5028 }
5029
5030 // If this is an indirect operand, store through the pointer after the
5031 // asm.
5032 if (OpInfo.isIndirect) {
5033 IndirectStoresToEmit.push_back(std::make_pair(OpInfo.AssignedRegs,
5034 OpInfo.CallOperandVal));
5035 } else {
5036 // This is the result value of the call.
5037 assert(CS.getType() != Type::VoidTy && "Bad inline asm!");
5038 // Concatenate this output onto the outputs list.
5039 RetValRegs.append(OpInfo.AssignedRegs);
5040 }
5041
5042 // Add information to the INLINEASM node to know that this register is
5043 // set.
Dale Johannesen913d3df2008-09-12 17:49:03 +00005044 OpInfo.AssignedRegs.AddInlineAsmOperands(OpInfo.isEarlyClobber ?
5045 6 /* EARLYCLOBBER REGDEF */ :
5046 2 /* REGDEF */ ,
5047 DAG, AsmNodeOperands);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005048 break;
5049 }
5050 case InlineAsm::isInput: {
5051 SDValue InOperandVal = OpInfo.CallOperand;
5052
Chris Lattner6bdcda32008-10-17 16:47:46 +00005053 if (OpInfo.isMatchingInputConstraint()) { // Matching constraint?
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005054 // If this is required to match an output register we have already set,
5055 // just use its register.
Chris Lattner58f15c42008-10-17 16:21:11 +00005056 unsigned OperandNo = OpInfo.getMatchedOperand();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005057
5058 // Scan until we find the definition we already emitted of this operand.
5059 // When we find it, create a RegsForValue operand.
5060 unsigned CurOp = 2; // The first operand.
5061 for (; OperandNo; --OperandNo) {
5062 // Advance to the next operand.
5063 unsigned NumOps =
Dan Gohmanf5aeb1a2008-09-12 16:56:44 +00005064 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005065 assert(((NumOps & 7) == 2 /*REGDEF*/ ||
Dale Johannesen913d3df2008-09-12 17:49:03 +00005066 (NumOps & 7) == 6 /*EARLYCLOBBER REGDEF*/ ||
Dale Johannesen86b49f82008-09-24 01:07:17 +00005067 (NumOps & 7) == 4 /*MEM*/) &&
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005068 "Skipped past definitions?");
5069 CurOp += (NumOps>>3)+1;
5070 }
5071
5072 unsigned NumOps =
Dan Gohmanf5aeb1a2008-09-12 16:56:44 +00005073 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
Dale Johannesen913d3df2008-09-12 17:49:03 +00005074 if ((NumOps & 7) == 2 /*REGDEF*/
5075 || (NumOps & 7) == 6 /* EARLYCLOBBER REGDEF */) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005076 // Add NumOps>>3 registers to MatchedRegs.
5077 RegsForValue MatchedRegs;
5078 MatchedRegs.TLI = &TLI;
5079 MatchedRegs.ValueVTs.push_back(InOperandVal.getValueType());
5080 MatchedRegs.RegVTs.push_back(AsmNodeOperands[CurOp+1].getValueType());
5081 for (unsigned i = 0, e = NumOps>>3; i != e; ++i) {
5082 unsigned Reg =
5083 cast<RegisterSDNode>(AsmNodeOperands[++CurOp])->getReg();
5084 MatchedRegs.Regs.push_back(Reg);
5085 }
5086
5087 // Use the produced MatchedRegs object to
5088 MatchedRegs.getCopyToRegs(InOperandVal, DAG, Chain, &Flag);
Dale Johannesen86b49f82008-09-24 01:07:17 +00005089 MatchedRegs.AddInlineAsmOperands(1 /*REGUSE*/, DAG, AsmNodeOperands);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005090 break;
5091 } else {
Dale Johannesen86b49f82008-09-24 01:07:17 +00005092 assert(((NumOps & 7) == 4) && "Unknown matching constraint!");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005093 assert((NumOps >> 3) == 1 && "Unexpected number of operands");
5094 // Add information to the INLINEASM node to know about this input.
Dale Johannesen91aac102008-09-17 21:13:11 +00005095 AsmNodeOperands.push_back(DAG.getTargetConstant(NumOps,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005096 TLI.getPointerTy()));
5097 AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
5098 break;
5099 }
5100 }
5101
5102 if (OpInfo.ConstraintType == TargetLowering::C_Other) {
5103 assert(!OpInfo.isIndirect &&
5104 "Don't know how to handle indirect other inputs yet!");
5105
5106 std::vector<SDValue> Ops;
5107 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode[0],
Evan Chengda43bcf2008-09-24 00:05:32 +00005108 hasMemory, Ops, DAG);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005109 if (Ops.empty()) {
5110 cerr << "Invalid operand for inline asm constraint '"
5111 << OpInfo.ConstraintCode << "'!\n";
5112 exit(1);
5113 }
5114
5115 // Add information to the INLINEASM node to know about this input.
5116 unsigned ResOpType = 3 /*IMM*/ | (Ops.size() << 3);
5117 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
5118 TLI.getPointerTy()));
5119 AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end());
5120 break;
5121 } else if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
5122 assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
5123 assert(InOperandVal.getValueType() == TLI.getPointerTy() &&
5124 "Memory operands expect pointer values");
5125
5126 // Add information to the INLINEASM node to know about this input.
Dale Johannesen86b49f82008-09-24 01:07:17 +00005127 unsigned ResOpType = 4/*MEM*/ | (1<<3);
5128 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005129 TLI.getPointerTy()));
5130 AsmNodeOperands.push_back(InOperandVal);
5131 break;
5132 }
5133
5134 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
5135 OpInfo.ConstraintType == TargetLowering::C_Register) &&
5136 "Unknown constraint type!");
5137 assert(!OpInfo.isIndirect &&
5138 "Don't know how to handle indirect register inputs yet!");
5139
5140 // Copy the input into the appropriate registers.
Evan Chengaa765b82008-09-25 00:14:04 +00005141 if (OpInfo.AssignedRegs.Regs.empty()) {
5142 cerr << "Couldn't allocate output reg for constraint '"
5143 << OpInfo.ConstraintCode << "'!\n";
5144 exit(1);
5145 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005146
5147 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, Chain, &Flag);
5148
Dale Johannesen86b49f82008-09-24 01:07:17 +00005149 OpInfo.AssignedRegs.AddInlineAsmOperands(1/*REGUSE*/,
5150 DAG, AsmNodeOperands);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005151 break;
5152 }
5153 case InlineAsm::isClobber: {
5154 // Add the clobbered value to the operand list, so that the register
5155 // allocator is aware that the physreg got clobbered.
5156 if (!OpInfo.AssignedRegs.Regs.empty())
Dale Johannesen91aac102008-09-17 21:13:11 +00005157 OpInfo.AssignedRegs.AddInlineAsmOperands(6 /* EARLYCLOBBER REGDEF */,
5158 DAG, AsmNodeOperands);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005159 break;
5160 }
5161 }
5162 }
5163
5164 // Finish up input operands.
5165 AsmNodeOperands[0] = Chain;
5166 if (Flag.getNode()) AsmNodeOperands.push_back(Flag);
5167
5168 Chain = DAG.getNode(ISD::INLINEASM,
5169 DAG.getNodeValueTypes(MVT::Other, MVT::Flag), 2,
5170 &AsmNodeOperands[0], AsmNodeOperands.size());
5171 Flag = Chain.getValue(1);
5172
5173 // If this asm returns a register value, copy the result from that register
5174 // and set it as the value of the call.
5175 if (!RetValRegs.Regs.empty()) {
5176 SDValue Val = RetValRegs.getCopyFromRegs(DAG, Chain, &Flag);
Chris Lattner2a0b96c2008-10-18 18:49:30 +00005177
5178 // FIXME: Why don't we do this for inline asms with MRVs?
5179 if (CS.getType()->isSingleValueType() && CS.getType()->isSized()) {
5180 MVT ResultType = TLI.getValueType(CS.getType());
5181
5182 // If any of the results of the inline asm is a vector, it may have the
5183 // wrong width/num elts. This can happen for register classes that can
5184 // contain multiple different value types. The preg or vreg allocated may
5185 // not have the same VT as was expected. Convert it to the right type
5186 // with bit_convert.
5187 if (ResultType != Val.getValueType() && Val.getValueType().isVector()) {
5188 Val = DAG.getNode(ISD::BIT_CONVERT, ResultType, Val);
Dan Gohman95915732008-10-18 01:03:45 +00005189
Chris Lattner2a0b96c2008-10-18 18:49:30 +00005190 } else if (ResultType != Val.getValueType() &&
5191 ResultType.isInteger() && Val.getValueType().isInteger()) {
5192 // If a result value was tied to an input value, the computed result may
5193 // have a wider width than the expected result. Extract the relevant
5194 // portion.
5195 Val = DAG.getNode(ISD::TRUNCATE, ResultType, Val);
Dan Gohman95915732008-10-18 01:03:45 +00005196 }
Chris Lattner2a0b96c2008-10-18 18:49:30 +00005197
5198 assert(ResultType == Val.getValueType() && "Asm result value mismatch!");
Chris Lattner0c526442008-10-17 17:52:49 +00005199 }
Dan Gohman95915732008-10-18 01:03:45 +00005200
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005201 setValue(CS.getInstruction(), Val);
5202 }
5203
5204 std::vector<std::pair<SDValue, Value*> > StoresToEmit;
5205
5206 // Process indirect outputs, first output all of the flagged copies out of
5207 // physregs.
5208 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
5209 RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
5210 Value *Ptr = IndirectStoresToEmit[i].second;
5211 SDValue OutVal = OutRegs.getCopyFromRegs(DAG, Chain, &Flag);
5212 StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
5213 }
5214
5215 // Emit the non-flagged stores from the physregs.
5216 SmallVector<SDValue, 8> OutChains;
5217 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i)
5218 OutChains.push_back(DAG.getStore(Chain, StoresToEmit[i].first,
5219 getValue(StoresToEmit[i].second),
5220 StoresToEmit[i].second, 0));
5221 if (!OutChains.empty())
5222 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
5223 &OutChains[0], OutChains.size());
5224 DAG.setRoot(Chain);
5225}
5226
5227
5228void SelectionDAGLowering::visitMalloc(MallocInst &I) {
5229 SDValue Src = getValue(I.getOperand(0));
5230
5231 MVT IntPtr = TLI.getPointerTy();
5232
5233 if (IntPtr.bitsLT(Src.getValueType()))
5234 Src = DAG.getNode(ISD::TRUNCATE, IntPtr, Src);
5235 else if (IntPtr.bitsGT(Src.getValueType()))
5236 Src = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, Src);
5237
5238 // Scale the source by the type size.
Duncan Sandsceb4d1a2009-01-12 20:38:59 +00005239 uint64_t ElementSize = TD->getTypePaddedSize(I.getType()->getElementType());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005240 Src = DAG.getNode(ISD::MUL, Src.getValueType(),
5241 Src, DAG.getIntPtrConstant(ElementSize));
5242
5243 TargetLowering::ArgListTy Args;
5244 TargetLowering::ArgListEntry Entry;
5245 Entry.Node = Src;
5246 Entry.Ty = TLI.getTargetData()->getIntPtrType();
5247 Args.push_back(Entry);
5248
5249 std::pair<SDValue,SDValue> Result =
Dale Johannesen86098bd2008-09-26 19:31:26 +00005250 TLI.LowerCallTo(getRoot(), I.getType(), false, false, false, false,
5251 CallingConv::C, PerformTailCallOpt,
5252 DAG.getExternalSymbol("malloc", IntPtr),
Dan Gohman1937e2f2008-09-16 01:42:28 +00005253 Args, DAG);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005254 setValue(&I, Result.first); // Pointers always fit in registers
5255 DAG.setRoot(Result.second);
5256}
5257
5258void SelectionDAGLowering::visitFree(FreeInst &I) {
5259 TargetLowering::ArgListTy Args;
5260 TargetLowering::ArgListEntry Entry;
5261 Entry.Node = getValue(I.getOperand(0));
5262 Entry.Ty = TLI.getTargetData()->getIntPtrType();
5263 Args.push_back(Entry);
5264 MVT IntPtr = TLI.getPointerTy();
5265 std::pair<SDValue,SDValue> Result =
Dale Johannesen86098bd2008-09-26 19:31:26 +00005266 TLI.LowerCallTo(getRoot(), Type::VoidTy, false, false, false, false,
Dan Gohman1937e2f2008-09-16 01:42:28 +00005267 CallingConv::C, PerformTailCallOpt,
Bill Wendling056292f2008-09-16 21:48:12 +00005268 DAG.getExternalSymbol("free", IntPtr), Args, DAG);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005269 DAG.setRoot(Result.second);
5270}
5271
5272void SelectionDAGLowering::visitVAStart(CallInst &I) {
5273 DAG.setRoot(DAG.getNode(ISD::VASTART, MVT::Other, getRoot(),
5274 getValue(I.getOperand(1)),
5275 DAG.getSrcValue(I.getOperand(1))));
5276}
5277
5278void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
5279 SDValue V = DAG.getVAArg(TLI.getValueType(I.getType()), getRoot(),
5280 getValue(I.getOperand(0)),
5281 DAG.getSrcValue(I.getOperand(0)));
5282 setValue(&I, V);
5283 DAG.setRoot(V.getValue(1));
5284}
5285
5286void SelectionDAGLowering::visitVAEnd(CallInst &I) {
5287 DAG.setRoot(DAG.getNode(ISD::VAEND, MVT::Other, getRoot(),
5288 getValue(I.getOperand(1)),
5289 DAG.getSrcValue(I.getOperand(1))));
5290}
5291
5292void SelectionDAGLowering::visitVACopy(CallInst &I) {
5293 DAG.setRoot(DAG.getNode(ISD::VACOPY, MVT::Other, getRoot(),
5294 getValue(I.getOperand(1)),
5295 getValue(I.getOperand(2)),
5296 DAG.getSrcValue(I.getOperand(1)),
5297 DAG.getSrcValue(I.getOperand(2))));
5298}
5299
5300/// TargetLowering::LowerArguments - This is the default LowerArguments
5301/// implementation, which just inserts a FORMAL_ARGUMENTS node. FIXME: When all
5302/// targets are migrated to using FORMAL_ARGUMENTS, this hook should be
5303/// integrated into SDISel.
5304void TargetLowering::LowerArguments(Function &F, SelectionDAG &DAG,
5305 SmallVectorImpl<SDValue> &ArgValues) {
5306 // Add CC# and isVararg as operands to the FORMAL_ARGUMENTS node.
5307 SmallVector<SDValue, 3+16> Ops;
5308 Ops.push_back(DAG.getRoot());
5309 Ops.push_back(DAG.getConstant(F.getCallingConv(), getPointerTy()));
5310 Ops.push_back(DAG.getConstant(F.isVarArg(), getPointerTy()));
5311
5312 // Add one result value for each formal argument.
5313 SmallVector<MVT, 16> RetVals;
5314 unsigned j = 1;
5315 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end();
5316 I != E; ++I, ++j) {
5317 SmallVector<MVT, 4> ValueVTs;
5318 ComputeValueVTs(*this, I->getType(), ValueVTs);
5319 for (unsigned Value = 0, NumValues = ValueVTs.size();
5320 Value != NumValues; ++Value) {
5321 MVT VT = ValueVTs[Value];
5322 const Type *ArgTy = VT.getTypeForMVT();
5323 ISD::ArgFlagsTy Flags;
5324 unsigned OriginalAlignment =
5325 getTargetData()->getABITypeAlignment(ArgTy);
5326
Devang Patel05988662008-09-25 21:00:45 +00005327 if (F.paramHasAttr(j, Attribute::ZExt))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005328 Flags.setZExt();
Devang Patel05988662008-09-25 21:00:45 +00005329 if (F.paramHasAttr(j, Attribute::SExt))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005330 Flags.setSExt();
Devang Patel05988662008-09-25 21:00:45 +00005331 if (F.paramHasAttr(j, Attribute::InReg))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005332 Flags.setInReg();
Devang Patel05988662008-09-25 21:00:45 +00005333 if (F.paramHasAttr(j, Attribute::StructRet))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005334 Flags.setSRet();
Devang Patel05988662008-09-25 21:00:45 +00005335 if (F.paramHasAttr(j, Attribute::ByVal)) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005336 Flags.setByVal();
5337 const PointerType *Ty = cast<PointerType>(I->getType());
5338 const Type *ElementTy = Ty->getElementType();
5339 unsigned FrameAlign = getByValTypeAlignment(ElementTy);
Duncan Sandsceb4d1a2009-01-12 20:38:59 +00005340 unsigned FrameSize = getTargetData()->getTypePaddedSize(ElementTy);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005341 // For ByVal, alignment should be passed from FE. BE will guess if
5342 // this info is not there but there are cases it cannot get right.
5343 if (F.getParamAlignment(j))
5344 FrameAlign = F.getParamAlignment(j);
5345 Flags.setByValAlign(FrameAlign);
5346 Flags.setByValSize(FrameSize);
5347 }
Devang Patel05988662008-09-25 21:00:45 +00005348 if (F.paramHasAttr(j, Attribute::Nest))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005349 Flags.setNest();
5350 Flags.setOrigAlign(OriginalAlignment);
5351
5352 MVT RegisterVT = getRegisterType(VT);
5353 unsigned NumRegs = getNumRegisters(VT);
5354 for (unsigned i = 0; i != NumRegs; ++i) {
5355 RetVals.push_back(RegisterVT);
5356 ISD::ArgFlagsTy MyFlags = Flags;
5357 if (NumRegs > 1 && i == 0)
5358 MyFlags.setSplit();
5359 // if it isn't first piece, alignment must be 1
5360 else if (i > 0)
5361 MyFlags.setOrigAlign(1);
5362 Ops.push_back(DAG.getArgFlags(MyFlags));
5363 }
5364 }
5365 }
5366
5367 RetVals.push_back(MVT::Other);
5368
5369 // Create the node.
5370 SDNode *Result = DAG.getNode(ISD::FORMAL_ARGUMENTS,
5371 DAG.getVTList(&RetVals[0], RetVals.size()),
5372 &Ops[0], Ops.size()).getNode();
5373
5374 // Prelower FORMAL_ARGUMENTS. This isn't required for functionality, but
5375 // allows exposing the loads that may be part of the argument access to the
5376 // first DAGCombiner pass.
5377 SDValue TmpRes = LowerOperation(SDValue(Result, 0), DAG);
5378
5379 // The number of results should match up, except that the lowered one may have
5380 // an extra flag result.
5381 assert((Result->getNumValues() == TmpRes.getNode()->getNumValues() ||
5382 (Result->getNumValues()+1 == TmpRes.getNode()->getNumValues() &&
5383 TmpRes.getValue(Result->getNumValues()).getValueType() == MVT::Flag))
5384 && "Lowering produced unexpected number of results!");
5385
5386 // The FORMAL_ARGUMENTS node itself is likely no longer needed.
5387 if (Result != TmpRes.getNode() && Result->use_empty()) {
5388 HandleSDNode Dummy(DAG.getRoot());
5389 DAG.RemoveDeadNode(Result);
5390 }
5391
5392 Result = TmpRes.getNode();
5393
5394 unsigned NumArgRegs = Result->getNumValues() - 1;
5395 DAG.setRoot(SDValue(Result, NumArgRegs));
5396
5397 // Set up the return result vector.
5398 unsigned i = 0;
5399 unsigned Idx = 1;
5400 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E;
5401 ++I, ++Idx) {
5402 SmallVector<MVT, 4> ValueVTs;
5403 ComputeValueVTs(*this, I->getType(), ValueVTs);
5404 for (unsigned Value = 0, NumValues = ValueVTs.size();
5405 Value != NumValues; ++Value) {
5406 MVT VT = ValueVTs[Value];
5407 MVT PartVT = getRegisterType(VT);
5408
5409 unsigned NumParts = getNumRegisters(VT);
5410 SmallVector<SDValue, 4> Parts(NumParts);
5411 for (unsigned j = 0; j != NumParts; ++j)
5412 Parts[j] = SDValue(Result, i++);
5413
5414 ISD::NodeType AssertOp = ISD::DELETED_NODE;
Devang Patel05988662008-09-25 21:00:45 +00005415 if (F.paramHasAttr(Idx, Attribute::SExt))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005416 AssertOp = ISD::AssertSext;
Devang Patel05988662008-09-25 21:00:45 +00005417 else if (F.paramHasAttr(Idx, Attribute::ZExt))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005418 AssertOp = ISD::AssertZext;
5419
5420 ArgValues.push_back(getCopyFromParts(DAG, &Parts[0], NumParts, PartVT, VT,
5421 AssertOp));
5422 }
5423 }
5424 assert(i == NumArgRegs && "Argument register count mismatch!");
5425}
5426
5427
5428/// TargetLowering::LowerCallTo - This is the default LowerCallTo
5429/// implementation, which just inserts an ISD::CALL node, which is later custom
5430/// lowered by the target to something concrete. FIXME: When all targets are
5431/// migrated to using ISD::CALL, this hook should be integrated into SDISel.
5432std::pair<SDValue, SDValue>
5433TargetLowering::LowerCallTo(SDValue Chain, const Type *RetTy,
5434 bool RetSExt, bool RetZExt, bool isVarArg,
Dale Johannesen86098bd2008-09-26 19:31:26 +00005435 bool isInreg,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005436 unsigned CallingConv, bool isTailCall,
5437 SDValue Callee,
5438 ArgListTy &Args, SelectionDAG &DAG) {
Dan Gohman1937e2f2008-09-16 01:42:28 +00005439 assert((!isTailCall || PerformTailCallOpt) &&
5440 "isTailCall set when tail-call optimizations are disabled!");
5441
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005442 SmallVector<SDValue, 32> Ops;
5443 Ops.push_back(Chain); // Op#0 - Chain
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005444 Ops.push_back(Callee);
5445
5446 // Handle all of the outgoing arguments.
5447 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
5448 SmallVector<MVT, 4> ValueVTs;
5449 ComputeValueVTs(*this, Args[i].Ty, ValueVTs);
5450 for (unsigned Value = 0, NumValues = ValueVTs.size();
5451 Value != NumValues; ++Value) {
5452 MVT VT = ValueVTs[Value];
5453 const Type *ArgTy = VT.getTypeForMVT();
Chris Lattner2a0b96c2008-10-18 18:49:30 +00005454 SDValue Op = SDValue(Args[i].Node.getNode(),
5455 Args[i].Node.getResNo() + Value);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005456 ISD::ArgFlagsTy Flags;
5457 unsigned OriginalAlignment =
5458 getTargetData()->getABITypeAlignment(ArgTy);
5459
5460 if (Args[i].isZExt)
5461 Flags.setZExt();
5462 if (Args[i].isSExt)
5463 Flags.setSExt();
5464 if (Args[i].isInReg)
5465 Flags.setInReg();
5466 if (Args[i].isSRet)
5467 Flags.setSRet();
5468 if (Args[i].isByVal) {
5469 Flags.setByVal();
5470 const PointerType *Ty = cast<PointerType>(Args[i].Ty);
5471 const Type *ElementTy = Ty->getElementType();
5472 unsigned FrameAlign = getByValTypeAlignment(ElementTy);
Duncan Sandsceb4d1a2009-01-12 20:38:59 +00005473 unsigned FrameSize = getTargetData()->getTypePaddedSize(ElementTy);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005474 // For ByVal, alignment should come from FE. BE will guess if this
5475 // info is not there but there are cases it cannot get right.
5476 if (Args[i].Alignment)
5477 FrameAlign = Args[i].Alignment;
5478 Flags.setByValAlign(FrameAlign);
5479 Flags.setByValSize(FrameSize);
5480 }
5481 if (Args[i].isNest)
5482 Flags.setNest();
5483 Flags.setOrigAlign(OriginalAlignment);
5484
5485 MVT PartVT = getRegisterType(VT);
5486 unsigned NumParts = getNumRegisters(VT);
5487 SmallVector<SDValue, 4> Parts(NumParts);
5488 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
5489
5490 if (Args[i].isSExt)
5491 ExtendKind = ISD::SIGN_EXTEND;
5492 else if (Args[i].isZExt)
5493 ExtendKind = ISD::ZERO_EXTEND;
5494
5495 getCopyToParts(DAG, Op, &Parts[0], NumParts, PartVT, ExtendKind);
5496
5497 for (unsigned i = 0; i != NumParts; ++i) {
5498 // if it isn't first piece, alignment must be 1
5499 ISD::ArgFlagsTy MyFlags = Flags;
5500 if (NumParts > 1 && i == 0)
5501 MyFlags.setSplit();
5502 else if (i != 0)
5503 MyFlags.setOrigAlign(1);
5504
5505 Ops.push_back(Parts[i]);
5506 Ops.push_back(DAG.getArgFlags(MyFlags));
5507 }
5508 }
5509 }
5510
5511 // Figure out the result value types. We start by making a list of
5512 // the potentially illegal return value types.
5513 SmallVector<MVT, 4> LoweredRetTys;
5514 SmallVector<MVT, 4> RetTys;
5515 ComputeValueVTs(*this, RetTy, RetTys);
5516
5517 // Then we translate that to a list of legal types.
5518 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
5519 MVT VT = RetTys[I];
5520 MVT RegisterVT = getRegisterType(VT);
5521 unsigned NumRegs = getNumRegisters(VT);
5522 for (unsigned i = 0; i != NumRegs; ++i)
5523 LoweredRetTys.push_back(RegisterVT);
5524 }
5525
5526 LoweredRetTys.push_back(MVT::Other); // Always has a chain.
5527
5528 // Create the CALL node.
Dale Johannesen86098bd2008-09-26 19:31:26 +00005529 SDValue Res = DAG.getCall(CallingConv, isVarArg, isTailCall, isInreg,
Dan Gohman095cc292008-09-13 01:54:27 +00005530 DAG.getVTList(&LoweredRetTys[0],
5531 LoweredRetTys.size()),
Dale Johannesen86098bd2008-09-26 19:31:26 +00005532 &Ops[0], Ops.size()
5533 );
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005534 Chain = Res.getValue(LoweredRetTys.size() - 1);
5535
5536 // Gather up the call result into a single value.
Dan Gohmanb5cc34d2008-10-07 00:12:37 +00005537 if (RetTy != Type::VoidTy && !RetTys.empty()) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005538 ISD::NodeType AssertOp = ISD::DELETED_NODE;
5539
5540 if (RetSExt)
5541 AssertOp = ISD::AssertSext;
5542 else if (RetZExt)
5543 AssertOp = ISD::AssertZext;
5544
5545 SmallVector<SDValue, 4> ReturnValues;
5546 unsigned RegNo = 0;
5547 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
5548 MVT VT = RetTys[I];
5549 MVT RegisterVT = getRegisterType(VT);
5550 unsigned NumRegs = getNumRegisters(VT);
5551 unsigned RegNoEnd = NumRegs + RegNo;
5552 SmallVector<SDValue, 4> Results;
5553 for (; RegNo != RegNoEnd; ++RegNo)
5554 Results.push_back(Res.getValue(RegNo));
5555 SDValue ReturnValue =
5556 getCopyFromParts(DAG, &Results[0], NumRegs, RegisterVT, VT,
5557 AssertOp);
5558 ReturnValues.push_back(ReturnValue);
5559 }
Duncan Sandsaaffa052008-12-01 11:41:29 +00005560 Res = DAG.getNode(ISD::MERGE_VALUES,
5561 DAG.getVTList(&RetTys[0], RetTys.size()),
5562 &ReturnValues[0], ReturnValues.size());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005563 }
5564
5565 return std::make_pair(Res, Chain);
5566}
5567
5568SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) {
5569 assert(0 && "LowerOperation not implemented for this target!");
5570 abort();
5571 return SDValue();
5572}
5573
5574
5575void SelectionDAGLowering::CopyValueToVirtualRegister(Value *V, unsigned Reg) {
5576 SDValue Op = getValue(V);
5577 assert((Op.getOpcode() != ISD::CopyFromReg ||
5578 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
5579 "Copy from a reg to the same reg!");
5580 assert(!TargetRegisterInfo::isPhysicalRegister(Reg) && "Is a physreg");
5581
5582 RegsForValue RFV(TLI, Reg, V->getType());
5583 SDValue Chain = DAG.getEntryNode();
5584 RFV.getCopyToRegs(Op, DAG, Chain, 0);
5585 PendingExports.push_back(Chain);
5586}
5587
5588#include "llvm/CodeGen/SelectionDAGISel.h"
5589
5590void SelectionDAGISel::
5591LowerArguments(BasicBlock *LLVMBB) {
5592 // If this is the entry block, emit arguments.
5593 Function &F = *LLVMBB->getParent();
5594 SDValue OldRoot = SDL->DAG.getRoot();
5595 SmallVector<SDValue, 16> Args;
5596 TLI.LowerArguments(F, SDL->DAG, Args);
5597
5598 unsigned a = 0;
5599 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
5600 AI != E; ++AI) {
5601 SmallVector<MVT, 4> ValueVTs;
5602 ComputeValueVTs(TLI, AI->getType(), ValueVTs);
5603 unsigned NumValues = ValueVTs.size();
5604 if (!AI->use_empty()) {
5605 SDL->setValue(AI, SDL->DAG.getMergeValues(&Args[a], NumValues));
5606 // If this argument is live outside of the entry block, insert a copy from
5607 // whereever we got it to the vreg that other BB's will reference it as.
5608 DenseMap<const Value*, unsigned>::iterator VMI=FuncInfo->ValueMap.find(AI);
5609 if (VMI != FuncInfo->ValueMap.end()) {
5610 SDL->CopyValueToVirtualRegister(AI, VMI->second);
5611 }
5612 }
5613 a += NumValues;
5614 }
5615
5616 // Finally, if the target has anything special to do, allow it to do so.
5617 // FIXME: this should insert code into the DAG!
5618 EmitFunctionEntryCode(F, SDL->DAG.getMachineFunction());
5619}
5620
5621/// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
5622/// ensure constants are generated when needed. Remember the virtual registers
5623/// that need to be added to the Machine PHI nodes as input. We cannot just
5624/// directly add them, because expansion might result in multiple MBB's for one
5625/// BB. As such, the start of the BB might correspond to a different MBB than
5626/// the end.
5627///
5628void
5629SelectionDAGISel::HandlePHINodesInSuccessorBlocks(BasicBlock *LLVMBB) {
5630 TerminatorInst *TI = LLVMBB->getTerminator();
5631
5632 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
5633
5634 // Check successor nodes' PHI nodes that expect a constant to be available
5635 // from this block.
5636 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
5637 BasicBlock *SuccBB = TI->getSuccessor(succ);
5638 if (!isa<PHINode>(SuccBB->begin())) continue;
5639 MachineBasicBlock *SuccMBB = FuncInfo->MBBMap[SuccBB];
5640
5641 // If this terminator has multiple identical successors (common for
5642 // switches), only handle each succ once.
5643 if (!SuccsHandled.insert(SuccMBB)) continue;
5644
5645 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
5646 PHINode *PN;
5647
5648 // At this point we know that there is a 1-1 correspondence between LLVM PHI
5649 // nodes and Machine PHI nodes, but the incoming operands have not been
5650 // emitted yet.
5651 for (BasicBlock::iterator I = SuccBB->begin();
5652 (PN = dyn_cast<PHINode>(I)); ++I) {
5653 // Ignore dead phi's.
5654 if (PN->use_empty()) continue;
5655
5656 unsigned Reg;
5657 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
5658
5659 if (Constant *C = dyn_cast<Constant>(PHIOp)) {
5660 unsigned &RegOut = SDL->ConstantsOut[C];
5661 if (RegOut == 0) {
5662 RegOut = FuncInfo->CreateRegForValue(C);
5663 SDL->CopyValueToVirtualRegister(C, RegOut);
5664 }
5665 Reg = RegOut;
5666 } else {
5667 Reg = FuncInfo->ValueMap[PHIOp];
5668 if (Reg == 0) {
5669 assert(isa<AllocaInst>(PHIOp) &&
5670 FuncInfo->StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
5671 "Didn't codegen value into a register!??");
5672 Reg = FuncInfo->CreateRegForValue(PHIOp);
5673 SDL->CopyValueToVirtualRegister(PHIOp, Reg);
5674 }
5675 }
5676
5677 // Remember that this register needs to added to the machine PHI node as
5678 // the input for this MBB.
5679 SmallVector<MVT, 4> ValueVTs;
5680 ComputeValueVTs(TLI, PN->getType(), ValueVTs);
5681 for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
5682 MVT VT = ValueVTs[vti];
5683 unsigned NumRegisters = TLI.getNumRegisters(VT);
5684 for (unsigned i = 0, e = NumRegisters; i != e; ++i)
5685 SDL->PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
5686 Reg += NumRegisters;
5687 }
5688 }
5689 }
5690 SDL->ConstantsOut.clear();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005691}
5692
Dan Gohman3df24e62008-09-03 23:12:08 +00005693/// This is the Fast-ISel version of HandlePHINodesInSuccessorBlocks. It only
5694/// supports legal types, and it emits MachineInstrs directly instead of
5695/// creating SelectionDAG nodes.
5696///
5697bool
5698SelectionDAGISel::HandlePHINodesInSuccessorBlocksFast(BasicBlock *LLVMBB,
5699 FastISel *F) {
5700 TerminatorInst *TI = LLVMBB->getTerminator();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005701
Dan Gohman3df24e62008-09-03 23:12:08 +00005702 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
5703 unsigned OrigNumPHINodesToUpdate = SDL->PHINodesToUpdate.size();
5704
5705 // Check successor nodes' PHI nodes that expect a constant to be available
5706 // from this block.
5707 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
5708 BasicBlock *SuccBB = TI->getSuccessor(succ);
5709 if (!isa<PHINode>(SuccBB->begin())) continue;
5710 MachineBasicBlock *SuccMBB = FuncInfo->MBBMap[SuccBB];
5711
5712 // If this terminator has multiple identical successors (common for
5713 // switches), only handle each succ once.
5714 if (!SuccsHandled.insert(SuccMBB)) continue;
5715
5716 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
5717 PHINode *PN;
5718
5719 // At this point we know that there is a 1-1 correspondence between LLVM PHI
5720 // nodes and Machine PHI nodes, but the incoming operands have not been
5721 // emitted yet.
5722 for (BasicBlock::iterator I = SuccBB->begin();
5723 (PN = dyn_cast<PHINode>(I)); ++I) {
5724 // Ignore dead phi's.
5725 if (PN->use_empty()) continue;
5726
5727 // Only handle legal types. Two interesting things to note here. First,
5728 // by bailing out early, we may leave behind some dead instructions,
5729 // since SelectionDAG's HandlePHINodesInSuccessorBlocks will insert its
5730 // own moves. Second, this check is necessary becuase FastISel doesn't
5731 // use CreateRegForValue to create registers, so it always creates
5732 // exactly one register for each non-void instruction.
5733 MVT VT = TLI.getValueType(PN->getType(), /*AllowUnknown=*/true);
5734 if (VT == MVT::Other || !TLI.isTypeLegal(VT)) {
Dan Gohman74321ab2008-09-10 21:01:31 +00005735 // Promote MVT::i1.
5736 if (VT == MVT::i1)
5737 VT = TLI.getTypeToTransformTo(VT);
5738 else {
5739 SDL->PHINodesToUpdate.resize(OrigNumPHINodesToUpdate);
5740 return false;
5741 }
Dan Gohman3df24e62008-09-03 23:12:08 +00005742 }
5743
5744 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
5745
5746 unsigned Reg = F->getRegForValue(PHIOp);
5747 if (Reg == 0) {
5748 SDL->PHINodesToUpdate.resize(OrigNumPHINodesToUpdate);
5749 return false;
5750 }
5751 SDL->PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg));
5752 }
5753 }
5754
5755 return true;
5756}