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