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