blob: f1dc64d3296c264877dc39554859fa0a887bf9a2 [file] [log] [blame]
Chris Lattner1c08c712005-01-07 07:47:53 +00001//===-- SelectionDAGISel.cpp - Implement the SelectionDAGISel class -------===//
Misha Brukmanedf128a2005-04-21 22:36:52 +00002//
Chris Lattner1c08c712005-01-07 07:47:53 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanedf128a2005-04-21 22:36:52 +00007//
Chris Lattner1c08c712005-01-07 07:47:53 +00008//===----------------------------------------------------------------------===//
9//
10// This implements the SelectionDAGISel class.
11//
12//===----------------------------------------------------------------------===//
13
14#define DEBUG_TYPE "isel"
Anton Korobeynikov5502bf62007-04-04 21:14:49 +000015#include "llvm/ADT/BitVector.h"
Jim Laskeyc7c3f112006-10-16 20:52:31 +000016#include "llvm/Analysis/AliasAnalysis.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000017#include "llvm/CodeGen/SelectionDAGISel.h"
Evan Chenga9c20912006-01-21 02:32:06 +000018#include "llvm/CodeGen/ScheduleDAG.h"
Anton Korobeynikov5502bf62007-04-04 21:14:49 +000019#include "llvm/Constants.h"
Chris Lattneradf6a962005-05-13 18:50:42 +000020#include "llvm/CallingConv.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000021#include "llvm/DerivedTypes.h"
22#include "llvm/Function.h"
Chris Lattner36ce6912005-11-29 06:21:05 +000023#include "llvm/GlobalVariable.h"
Chris Lattnerce7518c2006-01-26 22:24:51 +000024#include "llvm/InlineAsm.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000025#include "llvm/Instructions.h"
26#include "llvm/Intrinsics.h"
Jim Laskey43970fe2006-03-23 18:06:46 +000027#include "llvm/IntrinsicInst.h"
Reid Spencer5694b6e2007-04-09 06:17:21 +000028#include "llvm/ParameterAttributes.h"
Gordon Henriksence224772008-01-07 01:30:38 +000029#include "llvm/CodeGen/Collector.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000030#include "llvm/CodeGen/MachineFunction.h"
31#include "llvm/CodeGen/MachineFrameInfo.h"
32#include "llvm/CodeGen/MachineInstrBuilder.h"
Chris Lattner84bc5422007-12-31 04:13:23 +000033#include "llvm/CodeGen/MachineJumpTableInfo.h"
34#include "llvm/CodeGen/MachineModuleInfo.h"
35#include "llvm/CodeGen/MachineRegisterInfo.h"
Jim Laskeyeb577ba2006-08-02 12:30:23 +000036#include "llvm/CodeGen/SchedulerRegistry.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000037#include "llvm/CodeGen/SelectionDAG.h"
Dan Gohman6f0d0242008-02-10 18:45:23 +000038#include "llvm/Target/TargetRegisterInfo.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000039#include "llvm/Target/TargetData.h"
40#include "llvm/Target/TargetFrameInfo.h"
41#include "llvm/Target/TargetInstrInfo.h"
42#include "llvm/Target/TargetLowering.h"
43#include "llvm/Target/TargetMachine.h"
Vladimir Prus12472912006-05-23 13:43:15 +000044#include "llvm/Target/TargetOptions.h"
Chris Lattner7c0104b2005-11-09 04:45:33 +000045#include "llvm/Support/MathExtras.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000046#include "llvm/Support/Debug.h"
Chris Lattnera4f0b3a2006-08-27 12:54:02 +000047#include "llvm/Support/Compiler.h"
Jeff Cohen7e881032006-02-24 02:52:40 +000048#include <algorithm>
Chris Lattner1c08c712005-01-07 07:47:53 +000049using namespace llvm;
50
Chris Lattnerda8abb02005-09-01 18:44:10 +000051#ifndef NDEBUG
Chris Lattner7944d9d2005-01-12 03:41:21 +000052static cl::opt<bool>
Evan Chenga9c20912006-01-21 02:32:06 +000053ViewISelDAGs("view-isel-dags", cl::Hidden,
54 cl::desc("Pop up a window to show isel dags as they are selected"));
55static cl::opt<bool>
56ViewSchedDAGs("view-sched-dags", cl::Hidden,
57 cl::desc("Pop up a window to show sched dags as they are processed"));
Dan Gohman3e1a7ae2007-08-28 20:32:58 +000058static cl::opt<bool>
59ViewSUnitDAGs("view-sunit-dags", cl::Hidden,
Chris Lattner5bab7852008-01-25 17:24:52 +000060 cl::desc("Pop up a window to show SUnit dags after they are processed"));
Chris Lattner7944d9d2005-01-12 03:41:21 +000061#else
Dan Gohman3e1a7ae2007-08-28 20:32:58 +000062static const bool ViewISelDAGs = 0, ViewSchedDAGs = 0, ViewSUnitDAGs = 0;
Chris Lattner7944d9d2005-01-12 03:41:21 +000063#endif
64
Jim Laskeyeb577ba2006-08-02 12:30:23 +000065//===---------------------------------------------------------------------===//
66///
67/// RegisterScheduler class - Track the registration of instruction schedulers.
68///
69//===---------------------------------------------------------------------===//
70MachinePassRegistry RegisterScheduler::Registry;
71
72//===---------------------------------------------------------------------===//
73///
74/// ISHeuristic command line option for instruction schedulers.
75///
76//===---------------------------------------------------------------------===//
Dan Gohman844731a2008-05-13 00:00:25 +000077static cl::opt<RegisterScheduler::FunctionPassCtor, false,
78 RegisterPassParser<RegisterScheduler> >
79ISHeuristic("pre-RA-sched",
80 cl::init(&createDefaultScheduler),
81 cl::desc("Instruction schedulers available (before register"
82 " allocation):"));
Jim Laskey13ec7022006-08-01 14:21:23 +000083
Dan Gohman844731a2008-05-13 00:00:25 +000084static RegisterScheduler
85defaultListDAGScheduler("default", " Best scheduler for the target",
86 createDefaultScheduler);
Evan Cheng4ef10862006-01-23 07:01:07 +000087
Evan Cheng5c807602008-02-26 02:33:44 +000088namespace { struct SDISelAsmOperandInfo; }
Chris Lattnerbf996f12007-04-30 17:29:31 +000089
Dan Gohman1d685a42008-06-07 02:02:36 +000090/// ComputeLinearIndex - Given an LLVM IR aggregate type and a sequence
91/// insertvalue or extractvalue indices that identify a member, return
92/// the linearized index of the start of the member.
93///
94static unsigned ComputeLinearIndex(const TargetLowering &TLI, const Type *Ty,
95 const unsigned *Indices,
96 const unsigned *IndicesEnd,
97 unsigned CurIndex = 0) {
98 // Base case: We're done.
99 if (Indices == IndicesEnd)
100 return CurIndex;
101
102 // Otherwise we need to recurse. A non-negative value is used to
103 // indicate the final result value; a negative value carries the
104 // complemented position to continue the search.
105 CurIndex = ~CurIndex;
106
Chris Lattnerf899fce2008-04-27 23:48:12 +0000107 // Given a struct type, recursively traverse the elements.
108 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
109 for (StructType::element_iterator EI = STy->element_begin(),
Dan Gohman1d685a42008-06-07 02:02:36 +0000110 EE = STy->element_end();
111 EI != EE; ++EI) {
112 CurIndex = ComputeLinearIndex(TLI, *EI, Indices+1, IndicesEnd,
113 ~CurIndex);
114 if ((int)CurIndex >= 0)
115 return CurIndex;
116 }
117 }
118 // Given an array type, recursively traverse the elements.
119 else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
120 const Type *EltTy = ATy->getElementType();
121 for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i) {
122 CurIndex = ComputeLinearIndex(TLI, EltTy, Indices+1, IndicesEnd,
123 ~CurIndex);
124 if ((int)CurIndex >= 0)
125 return CurIndex;
126 }
127 }
128 // We haven't found the type we're looking for, so keep searching.
129 return CurIndex;
130}
131
132/// ComputeValueVTs - Given an LLVM IR type, compute a sequence of
133/// MVTs that represent all the individual underlying
134/// non-aggregate types that comprise it.
135///
136/// If Offsets is non-null, it points to a vector to be filled in
137/// with the in-memory offsets of each of the individual values.
138///
139static void ComputeValueVTs(const TargetLowering &TLI, const Type *Ty,
140 SmallVectorImpl<MVT> &ValueVTs,
141 SmallVectorImpl<uint64_t> *Offsets = 0,
142 uint64_t StartingOffset = 0) {
143 // Given a struct type, recursively traverse the elements.
144 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
145 const StructLayout *SL = TLI.getTargetData()->getStructLayout(STy);
146 for (StructType::element_iterator EB = STy->element_begin(),
147 EI = EB,
148 EE = STy->element_end();
149 EI != EE; ++EI)
150 ComputeValueVTs(TLI, *EI, ValueVTs, Offsets,
151 StartingOffset + SL->getElementOffset(EI - EB));
Chris Lattnerf899fce2008-04-27 23:48:12 +0000152 return;
Dan Gohman23ce5022008-04-25 18:27:55 +0000153 }
Chris Lattnerf899fce2008-04-27 23:48:12 +0000154 // Given an array type, recursively traverse the elements.
155 if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
156 const Type *EltTy = ATy->getElementType();
Dan Gohman1d685a42008-06-07 02:02:36 +0000157 uint64_t EltSize = TLI.getTargetData()->getABITypeSize(EltTy);
Chris Lattnerf899fce2008-04-27 23:48:12 +0000158 for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i)
Dan Gohman1d685a42008-06-07 02:02:36 +0000159 ComputeValueVTs(TLI, EltTy, ValueVTs, Offsets,
160 StartingOffset + i * EltSize);
Chris Lattnerf899fce2008-04-27 23:48:12 +0000161 return;
162 }
Duncan Sands83ec4b62008-06-06 12:08:01 +0000163 // Base case: we can get an MVT for this LLVM IR type.
Chris Lattnerf899fce2008-04-27 23:48:12 +0000164 ValueVTs.push_back(TLI.getValueType(Ty));
Dan Gohman1d685a42008-06-07 02:02:36 +0000165 if (Offsets)
166 Offsets->push_back(StartingOffset);
Chris Lattnerf899fce2008-04-27 23:48:12 +0000167}
Dan Gohman23ce5022008-04-25 18:27:55 +0000168
Chris Lattnerf899fce2008-04-27 23:48:12 +0000169namespace {
Dan Gohman0fe00902008-04-28 18:10:39 +0000170 /// RegsForValue - This struct represents the registers (physical or virtual)
171 /// that a particular set of values is assigned, and the type information about
172 /// the value. The most common situation is to represent one value at a time,
173 /// but struct or array values are handled element-wise as multiple values.
174 /// The splitting of aggregates is performed recursively, so that we never
175 /// have aggregate-typed registers. The values at this point do not necessarily
176 /// have legal types, so each value may require one or more registers of some
177 /// legal type.
178 ///
Chris Lattner95255282006-06-28 23:17:24 +0000179 struct VISIBILITY_HIDDEN RegsForValue {
Dan Gohman23ce5022008-04-25 18:27:55 +0000180 /// TLI - The TargetLowering object.
Dan Gohman0fe00902008-04-28 18:10:39 +0000181 ///
Dan Gohman23ce5022008-04-25 18:27:55 +0000182 const TargetLowering *TLI;
183
Dan Gohman0fe00902008-04-28 18:10:39 +0000184 /// ValueVTs - The value types of the values, which may not be legal, and
185 /// may need be promoted or synthesized from one or more registers.
186 ///
Duncan Sands83ec4b62008-06-06 12:08:01 +0000187 SmallVector<MVT, 4> ValueVTs;
Chris Lattner864635a2006-02-22 22:37:12 +0000188
Dan Gohman0fe00902008-04-28 18:10:39 +0000189 /// RegVTs - The value types of the registers. This is the same size as
190 /// ValueVTs and it records, for each value, what the type of the assigned
191 /// register or registers are. (Individual values are never synthesized
192 /// from more than one type of register.)
193 ///
194 /// With virtual registers, the contents of RegVTs is redundant with TLI's
195 /// getRegisterType member function, however when with physical registers
196 /// it is necessary to have a separate record of the types.
Chris Lattner864635a2006-02-22 22:37:12 +0000197 ///
Duncan Sands83ec4b62008-06-06 12:08:01 +0000198 SmallVector<MVT, 4> RegVTs;
Chris Lattner864635a2006-02-22 22:37:12 +0000199
Dan Gohman0fe00902008-04-28 18:10:39 +0000200 /// Regs - This list holds the registers assigned to the values.
201 /// Each legal or promoted value requires one register, and each
202 /// expanded value requires multiple registers.
203 ///
204 SmallVector<unsigned, 4> Regs;
Chris Lattner864635a2006-02-22 22:37:12 +0000205
Dan Gohman23ce5022008-04-25 18:27:55 +0000206 RegsForValue() : TLI(0) {}
Chris Lattner864635a2006-02-22 22:37:12 +0000207
Dan Gohman23ce5022008-04-25 18:27:55 +0000208 RegsForValue(const TargetLowering &tli,
Chris Lattnerb606dba2008-04-28 06:44:42 +0000209 const SmallVector<unsigned, 4> &regs,
Duncan Sands83ec4b62008-06-06 12:08:01 +0000210 MVT regvt, MVT valuevt)
Dan Gohman0fe00902008-04-28 18:10:39 +0000211 : TLI(&tli), ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs) {}
Dan Gohman23ce5022008-04-25 18:27:55 +0000212 RegsForValue(const TargetLowering &tli,
Chris Lattnerb606dba2008-04-28 06:44:42 +0000213 const SmallVector<unsigned, 4> &regs,
Duncan Sands83ec4b62008-06-06 12:08:01 +0000214 const SmallVector<MVT, 4> &regvts,
215 const SmallVector<MVT, 4> &valuevts)
Dan Gohman0fe00902008-04-28 18:10:39 +0000216 : TLI(&tli), ValueVTs(valuevts), RegVTs(regvts), Regs(regs) {}
Dan Gohman23ce5022008-04-25 18:27:55 +0000217 RegsForValue(const TargetLowering &tli,
218 unsigned Reg, const Type *Ty) : TLI(&tli) {
219 ComputeValueVTs(tli, Ty, ValueVTs);
220
Dan Gohmanb20d4f82008-04-28 17:42:03 +0000221 for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
Duncan Sands83ec4b62008-06-06 12:08:01 +0000222 MVT ValueVT = ValueVTs[Value];
Dan Gohman23ce5022008-04-25 18:27:55 +0000223 unsigned NumRegs = TLI->getNumRegisters(ValueVT);
Duncan Sands83ec4b62008-06-06 12:08:01 +0000224 MVT RegisterVT = TLI->getRegisterType(ValueVT);
Dan Gohman23ce5022008-04-25 18:27:55 +0000225 for (unsigned i = 0; i != NumRegs; ++i)
226 Regs.push_back(Reg + i);
227 RegVTs.push_back(RegisterVT);
228 Reg += NumRegs;
229 }
Chris Lattner864635a2006-02-22 22:37:12 +0000230 }
231
Chris Lattner41f62592008-04-29 04:29:54 +0000232 /// append - Add the specified values to this one.
233 void append(const RegsForValue &RHS) {
234 TLI = RHS.TLI;
235 ValueVTs.append(RHS.ValueVTs.begin(), RHS.ValueVTs.end());
236 RegVTs.append(RHS.RegVTs.begin(), RHS.RegVTs.end());
237 Regs.append(RHS.Regs.begin(), RHS.Regs.end());
238 }
239
240
Chris Lattner864635a2006-02-22 22:37:12 +0000241 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
Dan Gohman23ce5022008-04-25 18:27:55 +0000242 /// this value and returns the result as a ValueVTs value. This uses
Chris Lattner864635a2006-02-22 22:37:12 +0000243 /// Chain/Flag as the input and updates them for the output Chain/Flag.
Dan Gohmanb6f5b002007-06-28 23:29:44 +0000244 /// If the Flag pointer is NULL, no flag is used.
Chris Lattner864635a2006-02-22 22:37:12 +0000245 SDOperand getCopyFromRegs(SelectionDAG &DAG,
Dan Gohmanb6f5b002007-06-28 23:29:44 +0000246 SDOperand &Chain, SDOperand *Flag) const;
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +0000247
248 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
249 /// specified value into the registers specified by this object. This uses
250 /// Chain/Flag as the input and updates them for the output Chain/Flag.
Dan Gohmanb6f5b002007-06-28 23:29:44 +0000251 /// If the Flag pointer is NULL, no flag is used.
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +0000252 void getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
Dan Gohmanb6f5b002007-06-28 23:29:44 +0000253 SDOperand &Chain, SDOperand *Flag) const;
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +0000254
255 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
256 /// operand list. This adds the code marker and includes the number of
257 /// values added into it.
258 void AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
Chris Lattner9f6637d2006-02-23 20:06:57 +0000259 std::vector<SDOperand> &Ops) const;
Chris Lattner864635a2006-02-22 22:37:12 +0000260 };
261}
Evan Cheng4ef10862006-01-23 07:01:07 +0000262
Chris Lattner1c08c712005-01-07 07:47:53 +0000263namespace llvm {
264 //===--------------------------------------------------------------------===//
Jim Laskey9373beb2006-08-01 19:14:14 +0000265 /// createDefaultScheduler - This creates an instruction scheduler appropriate
266 /// for the target.
267 ScheduleDAG* createDefaultScheduler(SelectionDAGISel *IS,
268 SelectionDAG *DAG,
269 MachineBasicBlock *BB) {
270 TargetLowering &TLI = IS->getTargetLowering();
271
272 if (TLI.getSchedulingPreference() == TargetLowering::SchedulingForLatency) {
273 return createTDListDAGScheduler(IS, DAG, BB);
274 } else {
275 assert(TLI.getSchedulingPreference() ==
276 TargetLowering::SchedulingForRegPressure && "Unknown sched type!");
277 return createBURRListDAGScheduler(IS, DAG, BB);
278 }
279 }
280
281
282 //===--------------------------------------------------------------------===//
Chris Lattner1c08c712005-01-07 07:47:53 +0000283 /// FunctionLoweringInfo - This contains information that is global to a
284 /// function that is used when lowering a region of the function.
Chris Lattnerf26bc8e2005-01-08 19:52:31 +0000285 class FunctionLoweringInfo {
286 public:
Chris Lattner1c08c712005-01-07 07:47:53 +0000287 TargetLowering &TLI;
288 Function &Fn;
289 MachineFunction &MF;
Chris Lattner84bc5422007-12-31 04:13:23 +0000290 MachineRegisterInfo &RegInfo;
Chris Lattner1c08c712005-01-07 07:47:53 +0000291
292 FunctionLoweringInfo(TargetLowering &TLI, Function &Fn,MachineFunction &MF);
293
294 /// MBBMap - A mapping from LLVM basic blocks to their machine code entry.
295 std::map<const BasicBlock*, MachineBasicBlock *> MBBMap;
296
297 /// ValueMap - Since we emit code for the function a basic block at a time,
298 /// we must remember which virtual registers hold the values for
299 /// cross-basic-block values.
Chris Lattner9f24ad72007-02-04 01:35:11 +0000300 DenseMap<const Value*, unsigned> ValueMap;
Chris Lattner1c08c712005-01-07 07:47:53 +0000301
302 /// StaticAllocaMap - Keep track of frame indices for fixed sized allocas in
303 /// the entry block. This allows the allocas to be efficiently referenced
304 /// anywhere in the function.
305 std::map<const AllocaInst*, int> StaticAllocaMap;
306
Duncan Sandsf4070822007-06-15 19:04:19 +0000307#ifndef NDEBUG
308 SmallSet<Instruction*, 8> CatchInfoLost;
309 SmallSet<Instruction*, 8> CatchInfoFound;
310#endif
311
Duncan Sands83ec4b62008-06-06 12:08:01 +0000312 unsigned MakeReg(MVT VT) {
Chris Lattner84bc5422007-12-31 04:13:23 +0000313 return RegInfo.createVirtualRegister(TLI.getRegClassFor(VT));
Chris Lattner1c08c712005-01-07 07:47:53 +0000314 }
Chris Lattner571e4342006-10-27 21:36:01 +0000315
316 /// isExportedInst - Return true if the specified value is an instruction
317 /// exported from its block.
318 bool isExportedInst(const Value *V) {
319 return ValueMap.count(V);
320 }
Misha Brukmanedf128a2005-04-21 22:36:52 +0000321
Chris Lattner3c384492006-03-16 19:51:18 +0000322 unsigned CreateRegForValue(const Value *V);
323
Chris Lattner1c08c712005-01-07 07:47:53 +0000324 unsigned InitializeRegForValue(const Value *V) {
325 unsigned &R = ValueMap[V];
326 assert(R == 0 && "Already initialized this value register!");
327 return R = CreateRegForValue(V);
328 }
329 };
330}
331
Duncan Sandscf26d7c2007-07-04 20:52:51 +0000332/// isSelector - Return true if this instruction is a call to the
333/// eh.selector intrinsic.
334static bool isSelector(Instruction *I) {
Duncan Sandsf4070822007-06-15 19:04:19 +0000335 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
Anton Korobeynikov8806c7b2007-09-07 11:39:35 +0000336 return (II->getIntrinsicID() == Intrinsic::eh_selector_i32 ||
337 II->getIntrinsicID() == Intrinsic::eh_selector_i64);
Duncan Sandsf4070822007-06-15 19:04:19 +0000338 return false;
339}
340
Chris Lattner1c08c712005-01-07 07:47:53 +0000341/// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by
Nate Begemanf15485a2006-03-27 01:32:24 +0000342/// PHI nodes or outside of the basic block that defines it, or used by a
Andrew Lenharthab0b9492008-02-21 06:45:13 +0000343/// switch or atomic instruction, which may expand to multiple basic blocks.
Chris Lattner1c08c712005-01-07 07:47:53 +0000344static bool isUsedOutsideOfDefiningBlock(Instruction *I) {
345 if (isa<PHINode>(I)) return true;
346 BasicBlock *BB = I->getParent();
347 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; ++UI)
Nate Begemanf15485a2006-03-27 01:32:24 +0000348 if (cast<Instruction>(*UI)->getParent() != BB || isa<PHINode>(*UI) ||
Chris Lattner571e4342006-10-27 21:36:01 +0000349 // FIXME: Remove switchinst special case.
Nate Begemanf15485a2006-03-27 01:32:24 +0000350 isa<SwitchInst>(*UI))
Chris Lattner1c08c712005-01-07 07:47:53 +0000351 return true;
352 return false;
353}
354
Chris Lattnerbf209482005-10-30 19:42:35 +0000355/// isOnlyUsedInEntryBlock - If the specified argument is only used in the
Nate Begemanf15485a2006-03-27 01:32:24 +0000356/// entry block, return true. This includes arguments used by switches, since
357/// the switch may expand into multiple basic blocks.
Chris Lattnerbf209482005-10-30 19:42:35 +0000358static bool isOnlyUsedInEntryBlock(Argument *A) {
359 BasicBlock *Entry = A->getParent()->begin();
360 for (Value::use_iterator UI = A->use_begin(), E = A->use_end(); UI != E; ++UI)
Nate Begemanf15485a2006-03-27 01:32:24 +0000361 if (cast<Instruction>(*UI)->getParent() != Entry || isa<SwitchInst>(*UI))
Chris Lattnerbf209482005-10-30 19:42:35 +0000362 return false; // Use not in entry block.
363 return true;
364}
365
Chris Lattner1c08c712005-01-07 07:47:53 +0000366FunctionLoweringInfo::FunctionLoweringInfo(TargetLowering &tli,
Misha Brukmanedf128a2005-04-21 22:36:52 +0000367 Function &fn, MachineFunction &mf)
Chris Lattner84bc5422007-12-31 04:13:23 +0000368 : TLI(tli), Fn(fn), MF(mf), RegInfo(MF.getRegInfo()) {
Chris Lattner1c08c712005-01-07 07:47:53 +0000369
Chris Lattnerbf209482005-10-30 19:42:35 +0000370 // Create a vreg for each argument register that is not dead and is used
371 // outside of the entry block for the function.
372 for (Function::arg_iterator AI = Fn.arg_begin(), E = Fn.arg_end();
373 AI != E; ++AI)
374 if (!isOnlyUsedInEntryBlock(AI))
375 InitializeRegForValue(AI);
376
Chris Lattner1c08c712005-01-07 07:47:53 +0000377 // Initialize the mapping of values to registers. This is only set up for
378 // instruction values that are used outside of the block that defines
379 // them.
Jeff Cohen2aeaf4e2005-10-01 03:57:14 +0000380 Function::iterator BB = Fn.begin(), EB = Fn.end();
Chris Lattner1c08c712005-01-07 07:47:53 +0000381 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
382 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
Reid Spencerb83eb642006-10-20 07:07:24 +0000383 if (ConstantInt *CUI = dyn_cast<ConstantInt>(AI->getArraySize())) {
Chris Lattner1c08c712005-01-07 07:47:53 +0000384 const Type *Ty = AI->getAllocatedType();
Duncan Sands514ab342007-11-01 20:53:16 +0000385 uint64_t TySize = TLI.getTargetData()->getABITypeSize(Ty);
Nate Begemanae232e72005-11-06 09:00:38 +0000386 unsigned Align =
Chris Lattnerd2b7cec2007-02-14 05:52:17 +0000387 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
Nate Begemanae232e72005-11-06 09:00:38 +0000388 AI->getAlignment());
Chris Lattnera8217e32005-05-13 23:14:17 +0000389
Reid Spencerb83eb642006-10-20 07:07:24 +0000390 TySize *= CUI->getZExtValue(); // Get total allocated size.
Chris Lattnerd222f6a2005-10-18 22:14:06 +0000391 if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
Chris Lattner1c08c712005-01-07 07:47:53 +0000392 StaticAllocaMap[AI] =
Chris Lattner6266c182007-04-25 04:08:28 +0000393 MF.getFrameInfo()->CreateStackObject(TySize, Align);
Chris Lattner1c08c712005-01-07 07:47:53 +0000394 }
395
Jeff Cohen2aeaf4e2005-10-01 03:57:14 +0000396 for (; BB != EB; ++BB)
397 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
Chris Lattner1c08c712005-01-07 07:47:53 +0000398 if (!I->use_empty() && isUsedOutsideOfDefiningBlock(I))
399 if (!isa<AllocaInst>(I) ||
400 !StaticAllocaMap.count(cast<AllocaInst>(I)))
401 InitializeRegForValue(I);
402
403 // Create an initial MachineBasicBlock for each LLVM BasicBlock in F. This
404 // also creates the initial PHI MachineInstrs, though none of the input
405 // operands are populated.
Jeff Cohen2aeaf4e2005-10-01 03:57:14 +0000406 for (BB = Fn.begin(), EB = Fn.end(); BB != EB; ++BB) {
Chris Lattner1c08c712005-01-07 07:47:53 +0000407 MachineBasicBlock *MBB = new MachineBasicBlock(BB);
408 MBBMap[BB] = MBB;
409 MF.getBasicBlockList().push_back(MBB);
410
411 // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
412 // appropriate.
413 PHINode *PN;
Chris Lattner8c494ab2006-10-27 23:50:33 +0000414 for (BasicBlock::iterator I = BB->begin();(PN = dyn_cast<PHINode>(I)); ++I){
415 if (PN->use_empty()) continue;
416
Duncan Sands83ec4b62008-06-06 12:08:01 +0000417 MVT VT = TLI.getValueType(PN->getType());
Dan Gohman7f321562007-06-25 16:23:39 +0000418 unsigned NumRegisters = TLI.getNumRegisters(VT);
Chris Lattner8c494ab2006-10-27 23:50:33 +0000419 unsigned PHIReg = ValueMap[PN];
420 assert(PHIReg && "PHI node does not have an assigned virtual register!");
Evan Chengc0f64ff2006-11-27 23:37:22 +0000421 const TargetInstrInfo *TII = TLI.getTargetMachine().getInstrInfo();
Dan Gohmanb9f10192007-06-21 14:42:22 +0000422 for (unsigned i = 0; i != NumRegisters; ++i)
Evan Chengc0f64ff2006-11-27 23:37:22 +0000423 BuildMI(MBB, TII->get(TargetInstrInfo::PHI), PHIReg+i);
Chris Lattner8c494ab2006-10-27 23:50:33 +0000424 }
Chris Lattner1c08c712005-01-07 07:47:53 +0000425 }
426}
427
Chris Lattner3c384492006-03-16 19:51:18 +0000428/// CreateRegForValue - Allocate the appropriate number of virtual registers of
429/// the correctly promoted or expanded types. Assign these registers
430/// consecutive vreg numbers and return the first assigned number.
Dan Gohman10a6b7a2008-04-28 18:19:43 +0000431///
432/// In the case that the given value has struct or array type, this function
433/// will assign registers for each member or element.
434///
Chris Lattner3c384492006-03-16 19:51:18 +0000435unsigned FunctionLoweringInfo::CreateRegForValue(const Value *V) {
Duncan Sands83ec4b62008-06-06 12:08:01 +0000436 SmallVector<MVT, 4> ValueVTs;
Chris Lattnerb606dba2008-04-28 06:44:42 +0000437 ComputeValueVTs(TLI, V->getType(), ValueVTs);
Bill Wendling95b39552007-04-24 21:13:23 +0000438
Dan Gohman23ce5022008-04-25 18:27:55 +0000439 unsigned FirstReg = 0;
Dan Gohmanb20d4f82008-04-28 17:42:03 +0000440 for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
Duncan Sands83ec4b62008-06-06 12:08:01 +0000441 MVT ValueVT = ValueVTs[Value];
442 MVT RegisterVT = TLI.getRegisterType(ValueVT);
Dan Gohman8c8c5fc2007-06-27 14:34:07 +0000443
Chris Lattnerb606dba2008-04-28 06:44:42 +0000444 unsigned NumRegs = TLI.getNumRegisters(ValueVT);
Dan Gohman23ce5022008-04-25 18:27:55 +0000445 for (unsigned i = 0; i != NumRegs; ++i) {
446 unsigned R = MakeReg(RegisterVT);
447 if (!FirstReg) FirstReg = R;
448 }
449 }
450 return FirstReg;
Chris Lattner3c384492006-03-16 19:51:18 +0000451}
Chris Lattner1c08c712005-01-07 07:47:53 +0000452
453//===----------------------------------------------------------------------===//
454/// SelectionDAGLowering - This is the common target-independent lowering
455/// implementation that is parameterized by a TargetLowering object.
456/// Also, targets can overload any lowering method.
457///
458namespace llvm {
459class SelectionDAGLowering {
460 MachineBasicBlock *CurMBB;
461
Chris Lattner0da331f2007-02-04 01:31:47 +0000462 DenseMap<const Value*, SDOperand> NodeMap;
Chris Lattner1c08c712005-01-07 07:47:53 +0000463
Chris Lattnerd3948112005-01-17 22:19:26 +0000464 /// PendingLoads - Loads are not emitted to the program immediately. We bunch
465 /// them up and then emit token factor nodes when possible. This allows us to
466 /// get simple disambiguation between loads without worrying about alias
467 /// analysis.
468 std::vector<SDOperand> PendingLoads;
469
Dan Gohman86e1ebf2008-03-27 19:56:19 +0000470 /// PendingExports - CopyToReg nodes that copy values to virtual registers
471 /// for export to other blocks need to be emitted before any terminator
472 /// instruction, but they have no other ordering requirements. We bunch them
473 /// up and the emit a single tokenfactor for them just before terminator
474 /// instructions.
475 std::vector<SDOperand> PendingExports;
476
Anton Korobeynikov5502bf62007-04-04 21:14:49 +0000477 /// Case - A struct to record the Value for a switch case, and the
478 /// case's target basic block.
479 struct Case {
480 Constant* Low;
481 Constant* High;
482 MachineBasicBlock* BB;
483
484 Case() : Low(0), High(0), BB(0) { }
485 Case(Constant* low, Constant* high, MachineBasicBlock* bb) :
486 Low(low), High(high), BB(bb) { }
487 uint64_t size() const {
488 uint64_t rHigh = cast<ConstantInt>(High)->getSExtValue();
489 uint64_t rLow = cast<ConstantInt>(Low)->getSExtValue();
490 return (rHigh - rLow + 1ULL);
491 }
492 };
493
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000494 struct CaseBits {
495 uint64_t Mask;
496 MachineBasicBlock* BB;
497 unsigned Bits;
498
499 CaseBits(uint64_t mask, MachineBasicBlock* bb, unsigned bits):
500 Mask(mask), BB(bb), Bits(bits) { }
501 };
502
Anton Korobeynikov5502bf62007-04-04 21:14:49 +0000503 typedef std::vector<Case> CaseVector;
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000504 typedef std::vector<CaseBits> CaseBitsVector;
Anton Korobeynikov5502bf62007-04-04 21:14:49 +0000505 typedef CaseVector::iterator CaseItr;
506 typedef std::pair<CaseItr, CaseItr> CaseRange;
Nate Begemanf15485a2006-03-27 01:32:24 +0000507
508 /// CaseRec - A struct with ctor used in lowering switches to a binary tree
509 /// of conditional branches.
510 struct CaseRec {
511 CaseRec(MachineBasicBlock *bb, Constant *lt, Constant *ge, CaseRange r) :
512 CaseBB(bb), LT(lt), GE(ge), Range(r) {}
513
514 /// CaseBB - The MBB in which to emit the compare and branch
515 MachineBasicBlock *CaseBB;
516 /// LT, GE - If nonzero, we know the current case value must be less-than or
517 /// greater-than-or-equal-to these Constants.
518 Constant *LT;
519 Constant *GE;
520 /// Range - A pair of iterators representing the range of case values to be
521 /// processed at this point in the binary search tree.
522 CaseRange Range;
523 };
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +0000524
525 typedef std::vector<CaseRec> CaseRecVector;
Anton Korobeynikov5502bf62007-04-04 21:14:49 +0000526
527 /// The comparison function for sorting the switch case values in the vector.
528 /// WARNING: Case ranges should be disjoint!
Nate Begemanf15485a2006-03-27 01:32:24 +0000529 struct CaseCmp {
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000530 bool operator () (const Case& C1, const Case& C2) {
Anton Korobeynikov5502bf62007-04-04 21:14:49 +0000531 assert(isa<ConstantInt>(C1.Low) && isa<ConstantInt>(C2.High));
532 const ConstantInt* CI1 = cast<const ConstantInt>(C1.Low);
533 const ConstantInt* CI2 = cast<const ConstantInt>(C2.High);
534 return CI1->getValue().slt(CI2->getValue());
Nate Begemanf15485a2006-03-27 01:32:24 +0000535 }
536 };
Anton Korobeynikov5502bf62007-04-04 21:14:49 +0000537
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000538 struct CaseBitsCmp {
539 bool operator () (const CaseBits& C1, const CaseBits& C2) {
540 return C1.Bits > C2.Bits;
541 }
542 };
543
Anton Korobeynikov5502bf62007-04-04 21:14:49 +0000544 unsigned Clusterify(CaseVector& Cases, const SwitchInst &SI);
Nate Begemanf15485a2006-03-27 01:32:24 +0000545
Chris Lattner1c08c712005-01-07 07:47:53 +0000546public:
547 // TLI - This is information that describes the available target features we
548 // need for lowering. This indicates when operations are unavailable,
549 // implemented with a libcall, etc.
550 TargetLowering &TLI;
551 SelectionDAG &DAG;
Owen Andersona69571c2006-05-03 01:29:57 +0000552 const TargetData *TD;
Dan Gohman5f43f922007-08-27 16:26:13 +0000553 AliasAnalysis &AA;
Chris Lattner1c08c712005-01-07 07:47:53 +0000554
Nate Begemanf15485a2006-03-27 01:32:24 +0000555 /// SwitchCases - Vector of CaseBlock structures used to communicate
556 /// SwitchInst code generation information.
557 std::vector<SelectionDAGISel::CaseBlock> SwitchCases;
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +0000558 /// JTCases - Vector of JumpTable structures used to communicate
559 /// SwitchInst code generation information.
560 std::vector<SelectionDAGISel::JumpTableBlock> JTCases;
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000561 std::vector<SelectionDAGISel::BitTestBlock> BitTestCases;
Nate Begemanf15485a2006-03-27 01:32:24 +0000562
Chris Lattner1c08c712005-01-07 07:47:53 +0000563 /// FuncInfo - Information about the function as a whole.
564 ///
565 FunctionLoweringInfo &FuncInfo;
Gordon Henriksence224772008-01-07 01:30:38 +0000566
567 /// GCI - Garbage collection metadata for the function.
568 CollectorMetadata *GCI;
Chris Lattner1c08c712005-01-07 07:47:53 +0000569
570 SelectionDAGLowering(SelectionDAG &dag, TargetLowering &tli,
Dan Gohman5f43f922007-08-27 16:26:13 +0000571 AliasAnalysis &aa,
Gordon Henriksence224772008-01-07 01:30:38 +0000572 FunctionLoweringInfo &funcinfo,
573 CollectorMetadata *gci)
Dan Gohman5f43f922007-08-27 16:26:13 +0000574 : TLI(tli), DAG(dag), TD(DAG.getTarget().getTargetData()), AA(aa),
Gordon Henriksence224772008-01-07 01:30:38 +0000575 FuncInfo(funcinfo), GCI(gci) {
Chris Lattner1c08c712005-01-07 07:47:53 +0000576 }
577
Dan Gohman86e1ebf2008-03-27 19:56:19 +0000578 /// getRoot - Return the current virtual root of the Selection DAG,
579 /// flushing any PendingLoad items. This must be done before emitting
580 /// a store or any other node that may need to be ordered after any
581 /// prior load instructions.
Chris Lattnera651cf62005-01-17 19:43:36 +0000582 ///
583 SDOperand getRoot() {
Chris Lattnerd3948112005-01-17 22:19:26 +0000584 if (PendingLoads.empty())
585 return DAG.getRoot();
Misha Brukmanedf128a2005-04-21 22:36:52 +0000586
Chris Lattnerd3948112005-01-17 22:19:26 +0000587 if (PendingLoads.size() == 1) {
588 SDOperand Root = PendingLoads[0];
589 DAG.setRoot(Root);
590 PendingLoads.clear();
591 return Root;
592 }
593
594 // Otherwise, we have to make a token factor node.
Chris Lattnerbd564bf2006-08-08 02:23:42 +0000595 SDOperand Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
596 &PendingLoads[0], PendingLoads.size());
Chris Lattnerd3948112005-01-17 22:19:26 +0000597 PendingLoads.clear();
598 DAG.setRoot(Root);
599 return Root;
Chris Lattnera651cf62005-01-17 19:43:36 +0000600 }
601
Dan Gohman86e1ebf2008-03-27 19:56:19 +0000602 /// getControlRoot - Similar to getRoot, but instead of flushing all the
603 /// PendingLoad items, flush all the PendingExports items. It is necessary
604 /// to do this before emitting a terminator instruction.
605 ///
606 SDOperand getControlRoot() {
607 SDOperand Root = DAG.getRoot();
608
609 if (PendingExports.empty())
610 return Root;
611
612 // Turn all of the CopyToReg chains into one factored node.
613 if (Root.getOpcode() != ISD::EntryToken) {
614 unsigned i = 0, e = PendingExports.size();
615 for (; i != e; ++i) {
616 assert(PendingExports[i].Val->getNumOperands() > 1);
617 if (PendingExports[i].Val->getOperand(0) == Root)
618 break; // Don't add the root if we already indirectly depend on it.
619 }
620
621 if (i == e)
622 PendingExports.push_back(Root);
623 }
624
625 Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
626 &PendingExports[0],
627 PendingExports.size());
628 PendingExports.clear();
629 DAG.setRoot(Root);
630 return Root;
631 }
632
633 void CopyValueToVirtualRegister(Value *V, unsigned Reg);
Chris Lattner571e4342006-10-27 21:36:01 +0000634
Chris Lattner1c08c712005-01-07 07:47:53 +0000635 void visit(Instruction &I) { visit(I.getOpcode(), I); }
636
637 void visit(unsigned Opcode, User &I) {
Chris Lattner1e7aa5c2006-11-10 04:41:34 +0000638 // Note: this doesn't use InstVisitor, because it has to work with
639 // ConstantExpr's in addition to instructions.
Chris Lattner1c08c712005-01-07 07:47:53 +0000640 switch (Opcode) {
641 default: assert(0 && "Unknown instruction type encountered!");
642 abort();
643 // Build the switch statement using the Instruction.def file.
644#define HANDLE_INST(NUM, OPCODE, CLASS) \
645 case Instruction::OPCODE:return visit##OPCODE((CLASS&)I);
646#include "llvm/Instruction.def"
647 }
648 }
649
650 void setCurrentBasicBlock(MachineBasicBlock *MBB) { CurMBB = MBB; }
651
Chris Lattner199862b2006-03-16 19:57:50 +0000652 SDOperand getValue(const Value *V);
Chris Lattner1c08c712005-01-07 07:47:53 +0000653
Chris Lattner0da331f2007-02-04 01:31:47 +0000654 void setValue(const Value *V, SDOperand NewN) {
Chris Lattner1c08c712005-01-07 07:47:53 +0000655 SDOperand &N = NodeMap[V];
656 assert(N.Val == 0 && "Already set a value for this node!");
Chris Lattner0da331f2007-02-04 01:31:47 +0000657 N = NewN;
Chris Lattner1c08c712005-01-07 07:47:53 +0000658 }
Chris Lattner4e4b5762006-02-01 18:59:47 +0000659
Evan Cheng5c807602008-02-26 02:33:44 +0000660 void GetRegistersForValue(SDISelAsmOperandInfo &OpInfo, bool HasEarlyClobber,
Chris Lattnere7cf56a2007-04-30 21:11:17 +0000661 std::set<unsigned> &OutputRegs,
662 std::set<unsigned> &InputRegs);
Nate Begemanf15485a2006-03-27 01:32:24 +0000663
Chris Lattner571e4342006-10-27 21:36:01 +0000664 void FindMergedConditions(Value *Cond, MachineBasicBlock *TBB,
665 MachineBasicBlock *FBB, MachineBasicBlock *CurBB,
666 unsigned Opc);
Chris Lattner8c494ab2006-10-27 23:50:33 +0000667 bool isExportableFromCurrentBlock(Value *V, const BasicBlock *FromBB);
Chris Lattner571e4342006-10-27 21:36:01 +0000668 void ExportFromCurrentBlock(Value *V);
Duncan Sands6f74b482007-12-19 09:48:52 +0000669 void LowerCallTo(CallSite CS, SDOperand Callee, bool IsTailCall,
Anton Korobeynikov070280e2007-05-23 11:08:31 +0000670 MachineBasicBlock *LandingPad = NULL);
Duncan Sandsdc024672007-11-27 13:23:08 +0000671
Chris Lattner1c08c712005-01-07 07:47:53 +0000672 // Terminator instructions.
673 void visitRet(ReturnInst &I);
674 void visitBr(BranchInst &I);
Nate Begemanf15485a2006-03-27 01:32:24 +0000675 void visitSwitch(SwitchInst &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000676 void visitUnreachable(UnreachableInst &I) { /* noop */ }
677
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +0000678 // Helpers for visitSwitch
Anton Korobeynikovdd433212007-03-27 12:05:48 +0000679 bool handleSmallSwitchRange(CaseRec& CR,
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +0000680 CaseRecVector& WorkList,
681 Value* SV,
682 MachineBasicBlock* Default);
Anton Korobeynikovdd433212007-03-27 12:05:48 +0000683 bool handleJTSwitchCase(CaseRec& CR,
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +0000684 CaseRecVector& WorkList,
685 Value* SV,
686 MachineBasicBlock* Default);
Anton Korobeynikovdd433212007-03-27 12:05:48 +0000687 bool handleBTSplitSwitchCase(CaseRec& CR,
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +0000688 CaseRecVector& WorkList,
689 Value* SV,
690 MachineBasicBlock* Default);
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000691 bool handleBitTestsSwitchCase(CaseRec& CR,
692 CaseRecVector& WorkList,
693 Value* SV,
694 MachineBasicBlock* Default);
Nate Begemanf15485a2006-03-27 01:32:24 +0000695 void visitSwitchCase(SelectionDAGISel::CaseBlock &CB);
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000696 void visitBitTestHeader(SelectionDAGISel::BitTestBlock &B);
697 void visitBitTestCase(MachineBasicBlock* NextMBB,
698 unsigned Reg,
699 SelectionDAGISel::BitTestCase &B);
Nate Begeman37efe672006-04-22 18:53:45 +0000700 void visitJumpTable(SelectionDAGISel::JumpTable &JT);
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +0000701 void visitJumpTableHeader(SelectionDAGISel::JumpTable &JT,
702 SelectionDAGISel::JumpTableHeader &JTH);
Nate Begemanf15485a2006-03-27 01:32:24 +0000703
Chris Lattner1c08c712005-01-07 07:47:53 +0000704 // These all get lowered before this pass.
Jim Laskeyb180aa12007-02-21 22:53:45 +0000705 void visitInvoke(InvokeInst &I);
706 void visitUnwind(UnwindInst &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000707
Dan Gohman7f321562007-06-25 16:23:39 +0000708 void visitBinary(User &I, unsigned OpCode);
Nate Begemane21ea612005-11-18 07:42:56 +0000709 void visitShift(User &I, unsigned Opcode);
Nate Begeman5fbb5d22005-11-19 00:36:38 +0000710 void visitAdd(User &I) {
Dan Gohman7f321562007-06-25 16:23:39 +0000711 if (I.getType()->isFPOrFPVector())
712 visitBinary(I, ISD::FADD);
Reid Spencer1628cec2006-10-26 06:15:43 +0000713 else
Dan Gohman7f321562007-06-25 16:23:39 +0000714 visitBinary(I, ISD::ADD);
Chris Lattner01b3d732005-09-28 22:28:18 +0000715 }
Chris Lattnerb9fccc42005-04-02 05:04:50 +0000716 void visitSub(User &I);
Reid Spencer1628cec2006-10-26 06:15:43 +0000717 void visitMul(User &I) {
Dan Gohman7f321562007-06-25 16:23:39 +0000718 if (I.getType()->isFPOrFPVector())
719 visitBinary(I, ISD::FMUL);
Reid Spencer1628cec2006-10-26 06:15:43 +0000720 else
Dan Gohman7f321562007-06-25 16:23:39 +0000721 visitBinary(I, ISD::MUL);
Chris Lattner01b3d732005-09-28 22:28:18 +0000722 }
Dan Gohman7f321562007-06-25 16:23:39 +0000723 void visitURem(User &I) { visitBinary(I, ISD::UREM); }
724 void visitSRem(User &I) { visitBinary(I, ISD::SREM); }
725 void visitFRem(User &I) { visitBinary(I, ISD::FREM); }
726 void visitUDiv(User &I) { visitBinary(I, ISD::UDIV); }
727 void visitSDiv(User &I) { visitBinary(I, ISD::SDIV); }
728 void visitFDiv(User &I) { visitBinary(I, ISD::FDIV); }
729 void visitAnd (User &I) { visitBinary(I, ISD::AND); }
730 void visitOr (User &I) { visitBinary(I, ISD::OR); }
731 void visitXor (User &I) { visitBinary(I, ISD::XOR); }
Reid Spencer24d6da52007-01-21 00:29:26 +0000732 void visitShl (User &I) { visitShift(I, ISD::SHL); }
Reid Spencer3822ff52006-11-08 06:47:33 +0000733 void visitLShr(User &I) { visitShift(I, ISD::SRL); }
734 void visitAShr(User &I) { visitShift(I, ISD::SRA); }
Reid Spencer45fb3f32006-11-20 01:22:35 +0000735 void visitICmp(User &I);
736 void visitFCmp(User &I);
Nate Begemanb43e9c12008-05-12 19:40:03 +0000737 void visitVICmp(User &I);
738 void visitVFCmp(User &I);
Reid Spencer3da59db2006-11-27 01:05:10 +0000739 // Visit the conversion instructions
740 void visitTrunc(User &I);
741 void visitZExt(User &I);
742 void visitSExt(User &I);
743 void visitFPTrunc(User &I);
744 void visitFPExt(User &I);
745 void visitFPToUI(User &I);
746 void visitFPToSI(User &I);
747 void visitUIToFP(User &I);
748 void visitSIToFP(User &I);
749 void visitPtrToInt(User &I);
750 void visitIntToPtr(User &I);
751 void visitBitCast(User &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000752
Chris Lattner2bbd8102006-03-29 00:11:43 +0000753 void visitExtractElement(User &I);
754 void visitInsertElement(User &I);
Chris Lattner3e104b12006-04-08 04:15:24 +0000755 void visitShuffleVector(User &I);
Chris Lattnerc7029802006-03-18 01:44:44 +0000756
Dan Gohman1d685a42008-06-07 02:02:36 +0000757 void visitExtractValue(ExtractValueInst &I);
758 void visitInsertValue(InsertValueInst &I);
Dan Gohman041e2eb2008-05-15 19:50:34 +0000759
Chris Lattner1c08c712005-01-07 07:47:53 +0000760 void visitGetElementPtr(User &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000761 void visitSelect(User &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000762
763 void visitMalloc(MallocInst &I);
764 void visitFree(FreeInst &I);
765 void visitAlloca(AllocaInst &I);
766 void visitLoad(LoadInst &I);
767 void visitStore(StoreInst &I);
768 void visitPHI(PHINode &I) { } // PHI nodes are handled specially.
769 void visitCall(CallInst &I);
Duncan Sandsfd7b3262007-12-17 18:08:19 +0000770 void visitInlineAsm(CallSite CS);
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +0000771 const char *visitIntrinsicCall(CallInst &I, unsigned Intrinsic);
Chris Lattner0eade312006-03-24 02:22:33 +0000772 void visitTargetIntrinsic(CallInst &I, unsigned Intrinsic);
Chris Lattner1c08c712005-01-07 07:47:53 +0000773
Chris Lattner1c08c712005-01-07 07:47:53 +0000774 void visitVAStart(CallInst &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000775 void visitVAArg(VAArgInst &I);
776 void visitVAEnd(CallInst &I);
777 void visitVACopy(CallInst &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000778
Dan Gohmanef5d1942008-03-11 21:11:25 +0000779 void visitGetResult(GetResultInst &I);
Devang Patel40a04212008-02-19 22:15:16 +0000780
Chris Lattner1c08c712005-01-07 07:47:53 +0000781 void visitUserOp1(Instruction &I) {
782 assert(0 && "UserOp1 should not exist at instruction selection time!");
783 abort();
784 }
785 void visitUserOp2(Instruction &I) {
786 assert(0 && "UserOp2 should not exist at instruction selection time!");
787 abort();
788 }
Mon P Wang63307c32008-05-05 19:05:59 +0000789
790private:
791 inline const char *implVisitBinaryAtomic(CallInst& I, ISD::NodeType Op);
792
Chris Lattner1c08c712005-01-07 07:47:53 +0000793};
794} // end namespace llvm
795
Dan Gohman6183f782007-07-05 20:12:34 +0000796
Duncan Sandsb988bac2008-02-11 20:58:28 +0000797/// getCopyFromParts - Create a value that contains the specified legal parts
798/// combined into the value they represent. If the parts combine to a type
799/// larger then ValueVT then AssertOp can be used to specify whether the extra
800/// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
Chris Lattner4468c1f2008-03-09 09:38:46 +0000801/// (ISD::AssertSext).
Dan Gohman6183f782007-07-05 20:12:34 +0000802static SDOperand getCopyFromParts(SelectionDAG &DAG,
803 const SDOperand *Parts,
804 unsigned NumParts,
Duncan Sands83ec4b62008-06-06 12:08:01 +0000805 MVT PartVT,
806 MVT ValueVT,
Chris Lattner4468c1f2008-03-09 09:38:46 +0000807 ISD::NodeType AssertOp = ISD::DELETED_NODE) {
Duncan Sands014e04a2008-02-12 20:46:31 +0000808 assert(NumParts > 0 && "No parts to assemble!");
809 TargetLowering &TLI = DAG.getTargetLoweringInfo();
810 SDOperand Val = Parts[0];
Dan Gohman6183f782007-07-05 20:12:34 +0000811
Duncan Sands014e04a2008-02-12 20:46:31 +0000812 if (NumParts > 1) {
813 // Assemble the value from multiple parts.
Duncan Sands83ec4b62008-06-06 12:08:01 +0000814 if (!ValueVT.isVector()) {
815 unsigned PartBits = PartVT.getSizeInBits();
816 unsigned ValueBits = ValueVT.getSizeInBits();
Dan Gohman6183f782007-07-05 20:12:34 +0000817
Duncan Sands014e04a2008-02-12 20:46:31 +0000818 // Assemble the power of 2 part.
819 unsigned RoundParts = NumParts & (NumParts - 1) ?
820 1 << Log2_32(NumParts) : NumParts;
821 unsigned RoundBits = PartBits * RoundParts;
Duncan Sands83ec4b62008-06-06 12:08:01 +0000822 MVT RoundVT = RoundBits == ValueBits ?
823 ValueVT : MVT::getIntegerVT(RoundBits);
Duncan Sands014e04a2008-02-12 20:46:31 +0000824 SDOperand Lo, Hi;
825
826 if (RoundParts > 2) {
Duncan Sands83ec4b62008-06-06 12:08:01 +0000827 MVT HalfVT = MVT::getIntegerVT(RoundBits/2);
Duncan Sands014e04a2008-02-12 20:46:31 +0000828 Lo = getCopyFromParts(DAG, Parts, RoundParts/2, PartVT, HalfVT);
829 Hi = getCopyFromParts(DAG, Parts+RoundParts/2, RoundParts/2,
830 PartVT, HalfVT);
Dan Gohman6183f782007-07-05 20:12:34 +0000831 } else {
Duncan Sands014e04a2008-02-12 20:46:31 +0000832 Lo = Parts[0];
833 Hi = Parts[1];
Dan Gohman6183f782007-07-05 20:12:34 +0000834 }
Duncan Sands014e04a2008-02-12 20:46:31 +0000835 if (TLI.isBigEndian())
836 std::swap(Lo, Hi);
837 Val = DAG.getNode(ISD::BUILD_PAIR, RoundVT, Lo, Hi);
838
839 if (RoundParts < NumParts) {
840 // Assemble the trailing non-power-of-2 part.
841 unsigned OddParts = NumParts - RoundParts;
Duncan Sands83ec4b62008-06-06 12:08:01 +0000842 MVT OddVT = MVT::getIntegerVT(OddParts * PartBits);
Duncan Sands014e04a2008-02-12 20:46:31 +0000843 Hi = getCopyFromParts(DAG, Parts+RoundParts, OddParts, PartVT, OddVT);
844
845 // Combine the round and odd parts.
846 Lo = Val;
847 if (TLI.isBigEndian())
848 std::swap(Lo, Hi);
Duncan Sands83ec4b62008-06-06 12:08:01 +0000849 MVT TotalVT = MVT::getIntegerVT(NumParts * PartBits);
Duncan Sands014e04a2008-02-12 20:46:31 +0000850 Hi = DAG.getNode(ISD::ANY_EXTEND, TotalVT, Hi);
851 Hi = DAG.getNode(ISD::SHL, TotalVT, Hi,
Duncan Sands83ec4b62008-06-06 12:08:01 +0000852 DAG.getConstant(Lo.getValueType().getSizeInBits(),
Duncan Sands014e04a2008-02-12 20:46:31 +0000853 TLI.getShiftAmountTy()));
854 Lo = DAG.getNode(ISD::ZERO_EXTEND, TotalVT, Lo);
855 Val = DAG.getNode(ISD::OR, TotalVT, Lo, Hi);
856 }
857 } else {
858 // Handle a multi-element vector.
Duncan Sands83ec4b62008-06-06 12:08:01 +0000859 MVT IntermediateVT, RegisterVT;
Duncan Sands014e04a2008-02-12 20:46:31 +0000860 unsigned NumIntermediates;
861 unsigned NumRegs =
862 TLI.getVectorTypeBreakdown(ValueVT, IntermediateVT, NumIntermediates,
863 RegisterVT);
Duncan Sands014e04a2008-02-12 20:46:31 +0000864 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
Evan Cheng35213342008-05-14 20:29:30 +0000865 NumParts = NumRegs; // Silence a compiler warning.
Duncan Sands014e04a2008-02-12 20:46:31 +0000866 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
867 assert(RegisterVT == Parts[0].getValueType() &&
868 "Part type doesn't match part!");
869
870 // Assemble the parts into intermediate operands.
871 SmallVector<SDOperand, 8> Ops(NumIntermediates);
872 if (NumIntermediates == NumParts) {
873 // If the register was not expanded, truncate or copy the value,
874 // as appropriate.
875 for (unsigned i = 0; i != NumParts; ++i)
876 Ops[i] = getCopyFromParts(DAG, &Parts[i], 1,
877 PartVT, IntermediateVT);
878 } else if (NumParts > 0) {
879 // If the intermediate type was expanded, build the intermediate operands
880 // from the parts.
881 assert(NumParts % NumIntermediates == 0 &&
882 "Must expand into a divisible number of parts!");
883 unsigned Factor = NumParts / NumIntermediates;
884 for (unsigned i = 0; i != NumIntermediates; ++i)
885 Ops[i] = getCopyFromParts(DAG, &Parts[i * Factor], Factor,
886 PartVT, IntermediateVT);
887 }
888
889 // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the intermediate
890 // operands.
Duncan Sands83ec4b62008-06-06 12:08:01 +0000891 Val = DAG.getNode(IntermediateVT.isVector() ?
Duncan Sands014e04a2008-02-12 20:46:31 +0000892 ISD::CONCAT_VECTORS : ISD::BUILD_VECTOR,
893 ValueVT, &Ops[0], NumIntermediates);
Dan Gohman6183f782007-07-05 20:12:34 +0000894 }
Dan Gohman6183f782007-07-05 20:12:34 +0000895 }
896
Duncan Sands014e04a2008-02-12 20:46:31 +0000897 // There is now one part, held in Val. Correct it to match ValueVT.
898 PartVT = Val.getValueType();
Dan Gohman6183f782007-07-05 20:12:34 +0000899
Duncan Sands014e04a2008-02-12 20:46:31 +0000900 if (PartVT == ValueVT)
901 return Val;
Dan Gohman6183f782007-07-05 20:12:34 +0000902
Duncan Sands83ec4b62008-06-06 12:08:01 +0000903 if (PartVT.isVector()) {
904 assert(ValueVT.isVector() && "Unknown vector conversion!");
Duncan Sands014e04a2008-02-12 20:46:31 +0000905 return DAG.getNode(ISD::BIT_CONVERT, ValueVT, Val);
Dan Gohman6183f782007-07-05 20:12:34 +0000906 }
Duncan Sands014e04a2008-02-12 20:46:31 +0000907
Duncan Sands83ec4b62008-06-06 12:08:01 +0000908 if (ValueVT.isVector()) {
909 assert(ValueVT.getVectorElementType() == PartVT &&
910 ValueVT.getVectorNumElements() == 1 &&
Duncan Sands014e04a2008-02-12 20:46:31 +0000911 "Only trivial scalar-to-vector conversions should get here!");
912 return DAG.getNode(ISD::BUILD_VECTOR, ValueVT, Val);
913 }
914
Duncan Sands83ec4b62008-06-06 12:08:01 +0000915 if (PartVT.isInteger() &&
916 ValueVT.isInteger()) {
Duncan Sands8e4eb092008-06-08 20:54:56 +0000917 if (ValueVT.bitsLT(PartVT)) {
Duncan Sands014e04a2008-02-12 20:46:31 +0000918 // For a truncate, see if we have any information to
919 // indicate whether the truncated bits will always be
920 // zero or sign-extension.
921 if (AssertOp != ISD::DELETED_NODE)
922 Val = DAG.getNode(AssertOp, PartVT, Val,
923 DAG.getValueType(ValueVT));
924 return DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
925 } else {
926 return DAG.getNode(ISD::ANY_EXTEND, ValueVT, Val);
927 }
928 }
929
Duncan Sands83ec4b62008-06-06 12:08:01 +0000930 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
Duncan Sands8e4eb092008-06-08 20:54:56 +0000931 if (ValueVT.bitsLT(Val.getValueType()))
Chris Lattner4468c1f2008-03-09 09:38:46 +0000932 // FP_ROUND's are always exact here.
Chris Lattnerd43d85c2008-03-09 07:47:22 +0000933 return DAG.getNode(ISD::FP_ROUND, ValueVT, Val,
Chris Lattner4468c1f2008-03-09 09:38:46 +0000934 DAG.getIntPtrConstant(1));
Chris Lattnerd43d85c2008-03-09 07:47:22 +0000935 return DAG.getNode(ISD::FP_EXTEND, ValueVT, Val);
936 }
Duncan Sands014e04a2008-02-12 20:46:31 +0000937
Duncan Sands83ec4b62008-06-06 12:08:01 +0000938 if (PartVT.getSizeInBits() == ValueVT.getSizeInBits())
Duncan Sands014e04a2008-02-12 20:46:31 +0000939 return DAG.getNode(ISD::BIT_CONVERT, ValueVT, Val);
940
941 assert(0 && "Unknown mismatch!");
Chris Lattnerd27c9912008-03-30 18:22:13 +0000942 return SDOperand();
Dan Gohman6183f782007-07-05 20:12:34 +0000943}
944
Duncan Sandsb988bac2008-02-11 20:58:28 +0000945/// getCopyToParts - Create a series of nodes that contain the specified value
946/// split into legal parts. If the parts contain more bits than Val, then, for
947/// integers, ExtendKind can be used to specify how to generate the extra bits.
Dan Gohman6183f782007-07-05 20:12:34 +0000948static void getCopyToParts(SelectionDAG &DAG,
949 SDOperand Val,
950 SDOperand *Parts,
951 unsigned NumParts,
Duncan Sands83ec4b62008-06-06 12:08:01 +0000952 MVT PartVT,
Duncan Sandsb988bac2008-02-11 20:58:28 +0000953 ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
Dan Gohman25ac7e82007-08-10 14:59:38 +0000954 TargetLowering &TLI = DAG.getTargetLoweringInfo();
Duncan Sands83ec4b62008-06-06 12:08:01 +0000955 MVT PtrVT = TLI.getPointerTy();
956 MVT ValueVT = Val.getValueType();
957 unsigned PartBits = PartVT.getSizeInBits();
Duncan Sands014e04a2008-02-12 20:46:31 +0000958 assert(TLI.isTypeLegal(PartVT) && "Copying to an illegal type!");
Dan Gohman6183f782007-07-05 20:12:34 +0000959
Duncan Sands014e04a2008-02-12 20:46:31 +0000960 if (!NumParts)
961 return;
962
Duncan Sands83ec4b62008-06-06 12:08:01 +0000963 if (!ValueVT.isVector()) {
Duncan Sands014e04a2008-02-12 20:46:31 +0000964 if (PartVT == ValueVT) {
965 assert(NumParts == 1 && "No-op copy with multiple parts!");
966 Parts[0] = Val;
Dan Gohman6183f782007-07-05 20:12:34 +0000967 return;
968 }
969
Duncan Sands83ec4b62008-06-06 12:08:01 +0000970 if (NumParts * PartBits > ValueVT.getSizeInBits()) {
Duncan Sands014e04a2008-02-12 20:46:31 +0000971 // If the parts cover more bits than the value has, promote the value.
Duncan Sands83ec4b62008-06-06 12:08:01 +0000972 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
Duncan Sands014e04a2008-02-12 20:46:31 +0000973 assert(NumParts == 1 && "Do not know what to promote to!");
Dan Gohman6183f782007-07-05 20:12:34 +0000974 Val = DAG.getNode(ISD::FP_EXTEND, PartVT, Val);
Duncan Sands83ec4b62008-06-06 12:08:01 +0000975 } else if (PartVT.isInteger() && ValueVT.isInteger()) {
976 ValueVT = MVT::getIntegerVT(NumParts * PartBits);
Duncan Sands014e04a2008-02-12 20:46:31 +0000977 Val = DAG.getNode(ExtendKind, ValueVT, Val);
978 } else {
979 assert(0 && "Unknown mismatch!");
980 }
Duncan Sands83ec4b62008-06-06 12:08:01 +0000981 } else if (PartBits == ValueVT.getSizeInBits()) {
Duncan Sands014e04a2008-02-12 20:46:31 +0000982 // Different types of the same size.
983 assert(NumParts == 1 && PartVT != ValueVT);
984 Val = DAG.getNode(ISD::BIT_CONVERT, PartVT, Val);
Duncan Sands83ec4b62008-06-06 12:08:01 +0000985 } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
Duncan Sands014e04a2008-02-12 20:46:31 +0000986 // If the parts cover less bits than value has, truncate the value.
Duncan Sands83ec4b62008-06-06 12:08:01 +0000987 if (PartVT.isInteger() && ValueVT.isInteger()) {
988 ValueVT = MVT::getIntegerVT(NumParts * PartBits);
Duncan Sands014e04a2008-02-12 20:46:31 +0000989 Val = DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
Dan Gohman6183f782007-07-05 20:12:34 +0000990 } else {
991 assert(0 && "Unknown mismatch!");
992 }
993 }
Duncan Sands014e04a2008-02-12 20:46:31 +0000994
995 // The value may have changed - recompute ValueVT.
996 ValueVT = Val.getValueType();
Duncan Sands83ec4b62008-06-06 12:08:01 +0000997 assert(NumParts * PartBits == ValueVT.getSizeInBits() &&
Duncan Sands014e04a2008-02-12 20:46:31 +0000998 "Failed to tile the value with PartVT!");
999
1000 if (NumParts == 1) {
1001 assert(PartVT == ValueVT && "Type conversion failed!");
1002 Parts[0] = Val;
1003 return;
1004 }
1005
1006 // Expand the value into multiple parts.
1007 if (NumParts & (NumParts - 1)) {
1008 // The number of parts is not a power of 2. Split off and copy the tail.
Duncan Sands83ec4b62008-06-06 12:08:01 +00001009 assert(PartVT.isInteger() && ValueVT.isInteger() &&
Duncan Sands014e04a2008-02-12 20:46:31 +00001010 "Do not know what to expand to!");
1011 unsigned RoundParts = 1 << Log2_32(NumParts);
1012 unsigned RoundBits = RoundParts * PartBits;
1013 unsigned OddParts = NumParts - RoundParts;
1014 SDOperand OddVal = DAG.getNode(ISD::SRL, ValueVT, Val,
1015 DAG.getConstant(RoundBits,
1016 TLI.getShiftAmountTy()));
1017 getCopyToParts(DAG, OddVal, Parts + RoundParts, OddParts, PartVT);
1018 if (TLI.isBigEndian())
1019 // The odd parts were reversed by getCopyToParts - unreverse them.
1020 std::reverse(Parts + RoundParts, Parts + NumParts);
1021 NumParts = RoundParts;
Duncan Sands83ec4b62008-06-06 12:08:01 +00001022 ValueVT = MVT::getIntegerVT(NumParts * PartBits);
Duncan Sands014e04a2008-02-12 20:46:31 +00001023 Val = DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
1024 }
1025
1026 // The number of parts is a power of 2. Repeatedly bisect the value using
1027 // EXTRACT_ELEMENT.
Duncan Sands25eb0432008-03-12 20:30:08 +00001028 Parts[0] = DAG.getNode(ISD::BIT_CONVERT,
Duncan Sands83ec4b62008-06-06 12:08:01 +00001029 MVT::getIntegerVT(ValueVT.getSizeInBits()),
Duncan Sands25eb0432008-03-12 20:30:08 +00001030 Val);
Duncan Sands014e04a2008-02-12 20:46:31 +00001031 for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
1032 for (unsigned i = 0; i < NumParts; i += StepSize) {
1033 unsigned ThisBits = StepSize * PartBits / 2;
Duncan Sands83ec4b62008-06-06 12:08:01 +00001034 MVT ThisVT = MVT::getIntegerVT (ThisBits);
Duncan Sands25eb0432008-03-12 20:30:08 +00001035 SDOperand &Part0 = Parts[i];
1036 SDOperand &Part1 = Parts[i+StepSize/2];
Duncan Sands014e04a2008-02-12 20:46:31 +00001037
Duncan Sands25eb0432008-03-12 20:30:08 +00001038 Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, ThisVT, Part0,
1039 DAG.getConstant(1, PtrVT));
1040 Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, ThisVT, Part0,
1041 DAG.getConstant(0, PtrVT));
1042
1043 if (ThisBits == PartBits && ThisVT != PartVT) {
1044 Part0 = DAG.getNode(ISD::BIT_CONVERT, PartVT, Part0);
1045 Part1 = DAG.getNode(ISD::BIT_CONVERT, PartVT, Part1);
1046 }
Duncan Sands014e04a2008-02-12 20:46:31 +00001047 }
1048 }
1049
1050 if (TLI.isBigEndian())
1051 std::reverse(Parts, Parts + NumParts);
1052
1053 return;
1054 }
1055
1056 // Vector ValueVT.
1057 if (NumParts == 1) {
1058 if (PartVT != ValueVT) {
Duncan Sands83ec4b62008-06-06 12:08:01 +00001059 if (PartVT.isVector()) {
Duncan Sands014e04a2008-02-12 20:46:31 +00001060 Val = DAG.getNode(ISD::BIT_CONVERT, PartVT, Val);
1061 } else {
Duncan Sands83ec4b62008-06-06 12:08:01 +00001062 assert(ValueVT.getVectorElementType() == PartVT &&
1063 ValueVT.getVectorNumElements() == 1 &&
Duncan Sands014e04a2008-02-12 20:46:31 +00001064 "Only trivial vector-to-scalar conversions should get here!");
1065 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, PartVT, Val,
1066 DAG.getConstant(0, PtrVT));
1067 }
1068 }
1069
Dan Gohman6183f782007-07-05 20:12:34 +00001070 Parts[0] = Val;
1071 return;
1072 }
1073
1074 // Handle a multi-element vector.
Duncan Sands83ec4b62008-06-06 12:08:01 +00001075 MVT IntermediateVT, RegisterVT;
Dan Gohman6183f782007-07-05 20:12:34 +00001076 unsigned NumIntermediates;
1077 unsigned NumRegs =
1078 DAG.getTargetLoweringInfo()
1079 .getVectorTypeBreakdown(ValueVT, IntermediateVT, NumIntermediates,
1080 RegisterVT);
Duncan Sands83ec4b62008-06-06 12:08:01 +00001081 unsigned NumElements = ValueVT.getVectorNumElements();
Dan Gohman6183f782007-07-05 20:12:34 +00001082
1083 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
Evan Cheng35213342008-05-14 20:29:30 +00001084 NumParts = NumRegs; // Silence a compiler warning.
Dan Gohman6183f782007-07-05 20:12:34 +00001085 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
1086
1087 // Split the vector into intermediate operands.
1088 SmallVector<SDOperand, 8> Ops(NumIntermediates);
1089 for (unsigned i = 0; i != NumIntermediates; ++i)
Duncan Sands83ec4b62008-06-06 12:08:01 +00001090 if (IntermediateVT.isVector())
Dan Gohman6183f782007-07-05 20:12:34 +00001091 Ops[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR,
1092 IntermediateVT, Val,
1093 DAG.getConstant(i * (NumElements / NumIntermediates),
Dan Gohman25ac7e82007-08-10 14:59:38 +00001094 PtrVT));
Dan Gohman6183f782007-07-05 20:12:34 +00001095 else
1096 Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
1097 IntermediateVT, Val,
Dan Gohman25ac7e82007-08-10 14:59:38 +00001098 DAG.getConstant(i, PtrVT));
Dan Gohman6183f782007-07-05 20:12:34 +00001099
1100 // Split the intermediate operands into legal parts.
1101 if (NumParts == NumIntermediates) {
1102 // If the register was not expanded, promote or copy the value,
1103 // as appropriate.
1104 for (unsigned i = 0; i != NumParts; ++i)
Dan Gohman532dc2e2007-07-09 20:59:04 +00001105 getCopyToParts(DAG, Ops[i], &Parts[i], 1, PartVT);
Dan Gohman6183f782007-07-05 20:12:34 +00001106 } else if (NumParts > 0) {
1107 // If the intermediate type was expanded, split each the value into
1108 // legal parts.
1109 assert(NumParts % NumIntermediates == 0 &&
1110 "Must expand into a divisible number of parts!");
1111 unsigned Factor = NumParts / NumIntermediates;
1112 for (unsigned i = 0; i != NumIntermediates; ++i)
Dan Gohman532dc2e2007-07-09 20:59:04 +00001113 getCopyToParts(DAG, Ops[i], &Parts[i * Factor], Factor, PartVT);
Dan Gohman6183f782007-07-05 20:12:34 +00001114 }
1115}
1116
1117
Chris Lattner199862b2006-03-16 19:57:50 +00001118SDOperand SelectionDAGLowering::getValue(const Value *V) {
1119 SDOperand &N = NodeMap[V];
1120 if (N.Val) return N;
1121
Chris Lattner199862b2006-03-16 19:57:50 +00001122 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V))) {
Duncan Sands83ec4b62008-06-06 12:08:01 +00001123 MVT VT = TLI.getValueType(V->getType(), true);
Chris Lattnerb606dba2008-04-28 06:44:42 +00001124
1125 if (ConstantInt *CI = dyn_cast<ConstantInt>(C))
1126 return N = DAG.getConstant(CI->getValue(), VT);
1127
1128 if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
Chris Lattner199862b2006-03-16 19:57:50 +00001129 return N = DAG.getGlobalAddress(GV, VT);
Chris Lattnerb606dba2008-04-28 06:44:42 +00001130
1131 if (isa<ConstantPointerNull>(C))
Chris Lattner199862b2006-03-16 19:57:50 +00001132 return N = DAG.getConstant(0, TLI.getPointerTy());
Chris Lattnerb606dba2008-04-28 06:44:42 +00001133
1134 if (ConstantFP *CFP = dyn_cast<ConstantFP>(C))
1135 return N = DAG.getConstantFP(CFP->getValueAPF(), VT);
1136
Dan Gohman1d685a42008-06-07 02:02:36 +00001137 if (isa<UndefValue>(C) && !isa<VectorType>(V->getType()) &&
1138 !V->getType()->isAggregateType())
Chris Lattner6833b062008-04-28 07:16:35 +00001139 return N = DAG.getNode(ISD::UNDEF, VT);
Chris Lattnerb606dba2008-04-28 06:44:42 +00001140
1141 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
1142 visit(CE->getOpcode(), *CE);
1143 SDOperand N1 = NodeMap[V];
1144 assert(N1.Val && "visit didn't populate the ValueMap!");
1145 return N1;
1146 }
1147
Dan Gohman1d685a42008-06-07 02:02:36 +00001148 if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
1149 SmallVector<SDOperand, 4> Constants;
1150 SmallVector<MVT, 4> ValueVTs;
1151 for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end();
1152 OI != OE; ++OI) {
1153 SDNode *Val = getValue(*OI).Val;
1154 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i) {
1155 Constants.push_back(SDOperand(Val, i));
1156 ValueVTs.push_back(Val->getValueType(i));
1157 }
1158 }
1159 return DAG.getNode(ISD::MERGE_VALUES,
1160 DAG.getVTList(&ValueVTs[0], ValueVTs.size()),
1161 &Constants[0], Constants.size());
1162 }
1163
1164 if (const ArrayType *ATy = dyn_cast<ArrayType>(C->getType())) {
1165 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
1166 "Unknown array constant!");
1167 unsigned NumElts = ATy->getNumElements();
Dan Gohman8a6ccb52008-06-09 15:21:47 +00001168 if (NumElts == 0)
1169 return SDOperand(); // empty array
Dan Gohman1d685a42008-06-07 02:02:36 +00001170 MVT EltVT = TLI.getValueType(ATy->getElementType());
1171 SmallVector<SDOperand, 4> Constants(NumElts);
1172 SmallVector<MVT, 4> ValueVTs(NumElts, EltVT);
1173 for (unsigned i = 0, e = NumElts; i != e; ++i) {
1174 if (isa<UndefValue>(C))
1175 Constants[i] = DAG.getNode(ISD::UNDEF, EltVT);
1176 else if (EltVT.isFloatingPoint())
1177 Constants[i] = DAG.getConstantFP(0, EltVT);
1178 else
1179 Constants[i] = DAG.getConstant(0, EltVT);
1180 }
1181 return DAG.getNode(ISD::MERGE_VALUES,
1182 DAG.getVTList(&ValueVTs[0], ValueVTs.size()),
1183 &Constants[0], Constants.size());
1184 }
1185
1186 if (const StructType *STy = dyn_cast<StructType>(C->getType())) {
1187 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
1188 "Unknown struct constant!");
1189 unsigned NumElts = STy->getNumElements();
Dan Gohman8a6ccb52008-06-09 15:21:47 +00001190 if (NumElts == 0)
1191 return SDOperand(); // empty struct
Dan Gohman1d685a42008-06-07 02:02:36 +00001192 SmallVector<SDOperand, 4> Constants(NumElts);
1193 SmallVector<MVT, 4> ValueVTs(NumElts);
1194 for (unsigned i = 0, e = NumElts; i != e; ++i) {
1195 MVT EltVT = TLI.getValueType(STy->getElementType(i));
1196 ValueVTs[i] = EltVT;
1197 if (isa<UndefValue>(C))
1198 Constants[i] = DAG.getNode(ISD::UNDEF, EltVT);
1199 else if (EltVT.isFloatingPoint())
1200 Constants[i] = DAG.getConstantFP(0, EltVT);
1201 else
1202 Constants[i] = DAG.getConstant(0, EltVT);
1203 }
1204 return DAG.getNode(ISD::MERGE_VALUES,
1205 DAG.getVTList(&ValueVTs[0], ValueVTs.size()),
1206 &Constants[0], Constants.size());
1207 }
1208
Chris Lattner6833b062008-04-28 07:16:35 +00001209 const VectorType *VecTy = cast<VectorType>(V->getType());
Chris Lattnerb606dba2008-04-28 06:44:42 +00001210 unsigned NumElements = VecTy->getNumElements();
Chris Lattnerb606dba2008-04-28 06:44:42 +00001211
Chris Lattner6833b062008-04-28 07:16:35 +00001212 // Now that we know the number and type of the elements, get that number of
1213 // elements into the Ops array based on what kind of constant it is.
1214 SmallVector<SDOperand, 16> Ops;
Chris Lattnerb606dba2008-04-28 06:44:42 +00001215 if (ConstantVector *CP = dyn_cast<ConstantVector>(C)) {
1216 for (unsigned i = 0; i != NumElements; ++i)
1217 Ops.push_back(getValue(CP->getOperand(i)));
1218 } else {
Chris Lattner6833b062008-04-28 07:16:35 +00001219 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
1220 "Unknown vector constant!");
Duncan Sands83ec4b62008-06-06 12:08:01 +00001221 MVT EltVT = TLI.getValueType(VecTy->getElementType());
Chris Lattner6833b062008-04-28 07:16:35 +00001222
Chris Lattnerb606dba2008-04-28 06:44:42 +00001223 SDOperand Op;
Chris Lattner6833b062008-04-28 07:16:35 +00001224 if (isa<UndefValue>(C))
1225 Op = DAG.getNode(ISD::UNDEF, EltVT);
Duncan Sands83ec4b62008-06-06 12:08:01 +00001226 else if (EltVT.isFloatingPoint())
Chris Lattner6833b062008-04-28 07:16:35 +00001227 Op = DAG.getConstantFP(0, EltVT);
Chris Lattnerb606dba2008-04-28 06:44:42 +00001228 else
Chris Lattner6833b062008-04-28 07:16:35 +00001229 Op = DAG.getConstant(0, EltVT);
Chris Lattnerb606dba2008-04-28 06:44:42 +00001230 Ops.assign(NumElements, Op);
1231 }
1232
1233 // Create a BUILD_VECTOR node.
1234 return NodeMap[V] = DAG.getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
Chris Lattner199862b2006-03-16 19:57:50 +00001235 }
1236
Chris Lattnerb606dba2008-04-28 06:44:42 +00001237 // If this is a static alloca, generate it as the frameindex instead of
1238 // computation.
Chris Lattner199862b2006-03-16 19:57:50 +00001239 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1240 std::map<const AllocaInst*, int>::iterator SI =
Chris Lattnerb606dba2008-04-28 06:44:42 +00001241 FuncInfo.StaticAllocaMap.find(AI);
Chris Lattner199862b2006-03-16 19:57:50 +00001242 if (SI != FuncInfo.StaticAllocaMap.end())
1243 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
1244 }
1245
Chris Lattner251db182007-02-25 18:40:32 +00001246 unsigned InReg = FuncInfo.ValueMap[V];
1247 assert(InReg && "Value not in map!");
Chris Lattner199862b2006-03-16 19:57:50 +00001248
Chris Lattner6833b062008-04-28 07:16:35 +00001249 RegsForValue RFV(TLI, InReg, V->getType());
Dan Gohmanb6f5b002007-06-28 23:29:44 +00001250 SDOperand Chain = DAG.getEntryNode();
Dan Gohmanb6f5b002007-06-28 23:29:44 +00001251 return RFV.getCopyFromRegs(DAG, Chain, NULL);
Chris Lattner199862b2006-03-16 19:57:50 +00001252}
1253
1254
Chris Lattner1c08c712005-01-07 07:47:53 +00001255void SelectionDAGLowering::visitRet(ReturnInst &I) {
1256 if (I.getNumOperands() == 0) {
Dan Gohman86e1ebf2008-03-27 19:56:19 +00001257 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getControlRoot()));
Chris Lattner1c08c712005-01-07 07:47:53 +00001258 return;
1259 }
Chris Lattnerb606dba2008-04-28 06:44:42 +00001260
Chris Lattnerbd564bf2006-08-08 02:23:42 +00001261 SmallVector<SDOperand, 8> NewValues;
Dan Gohman86e1ebf2008-03-27 19:56:19 +00001262 NewValues.push_back(getControlRoot());
1263 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
Nate Begemanee625572006-01-27 21:09:22 +00001264 SDOperand RetOp = getValue(I.getOperand(i));
Duncan Sands83ec4b62008-06-06 12:08:01 +00001265 MVT VT = RetOp.getValueType();
Duncan Sandsb988bac2008-02-11 20:58:28 +00001266
Evan Cheng8e7d0562006-05-26 23:09:09 +00001267 // FIXME: C calling convention requires the return type to be promoted to
1268 // at least 32-bit. But this is not necessary for non-C calling conventions.
Duncan Sands83ec4b62008-06-06 12:08:01 +00001269 if (VT.isInteger()) {
1270 MVT MinVT = TLI.getRegisterType(MVT::i32);
Duncan Sands8e4eb092008-06-08 20:54:56 +00001271 if (VT.bitsLT(MinVT))
Duncan Sandsb988bac2008-02-11 20:58:28 +00001272 VT = MinVT;
1273 }
1274
1275 unsigned NumParts = TLI.getNumRegisters(VT);
Duncan Sands83ec4b62008-06-06 12:08:01 +00001276 MVT PartVT = TLI.getRegisterType(VT);
Duncan Sandsb988bac2008-02-11 20:58:28 +00001277 SmallVector<SDOperand, 4> Parts(NumParts);
1278 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
1279
1280 const Function *F = I.getParent()->getParent();
1281 if (F->paramHasAttr(0, ParamAttr::SExt))
1282 ExtendKind = ISD::SIGN_EXTEND;
1283 else if (F->paramHasAttr(0, ParamAttr::ZExt))
1284 ExtendKind = ISD::ZERO_EXTEND;
1285
1286 getCopyToParts(DAG, RetOp, &Parts[0], NumParts, PartVT, ExtendKind);
1287
1288 for (unsigned i = 0; i < NumParts; ++i) {
1289 NewValues.push_back(Parts[i]);
Duncan Sands276dcbd2008-03-21 09:14:45 +00001290 NewValues.push_back(DAG.getArgFlags(ISD::ArgFlagsTy()));
Nate Begemanee625572006-01-27 21:09:22 +00001291 }
Chris Lattner1c08c712005-01-07 07:47:53 +00001292 }
Chris Lattnerbd564bf2006-08-08 02:23:42 +00001293 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other,
1294 &NewValues[0], NewValues.size()));
Chris Lattner1c08c712005-01-07 07:47:53 +00001295}
1296
Chris Lattner571e4342006-10-27 21:36:01 +00001297/// ExportFromCurrentBlock - If this condition isn't known to be exported from
1298/// the current basic block, add it to ValueMap now so that we'll get a
1299/// CopyTo/FromReg.
1300void SelectionDAGLowering::ExportFromCurrentBlock(Value *V) {
1301 // No need to export constants.
1302 if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
1303
1304 // Already exported?
1305 if (FuncInfo.isExportedInst(V)) return;
1306
1307 unsigned Reg = FuncInfo.InitializeRegForValue(V);
Dan Gohman86e1ebf2008-03-27 19:56:19 +00001308 CopyValueToVirtualRegister(V, Reg);
Chris Lattner571e4342006-10-27 21:36:01 +00001309}
1310
Chris Lattner8c494ab2006-10-27 23:50:33 +00001311bool SelectionDAGLowering::isExportableFromCurrentBlock(Value *V,
1312 const BasicBlock *FromBB) {
1313 // The operands of the setcc have to be in this block. We don't know
1314 // how to export them from some other block.
1315 if (Instruction *VI = dyn_cast<Instruction>(V)) {
1316 // Can export from current BB.
1317 if (VI->getParent() == FromBB)
1318 return true;
1319
1320 // Is already exported, noop.
1321 return FuncInfo.isExportedInst(V);
1322 }
1323
1324 // If this is an argument, we can export it if the BB is the entry block or
1325 // if it is already exported.
1326 if (isa<Argument>(V)) {
1327 if (FromBB == &FromBB->getParent()->getEntryBlock())
1328 return true;
1329
1330 // Otherwise, can only export this if it is already exported.
1331 return FuncInfo.isExportedInst(V);
1332 }
1333
1334 // Otherwise, constants can always be exported.
1335 return true;
1336}
1337
Chris Lattner6a586c82006-10-29 21:01:20 +00001338static bool InBlock(const Value *V, const BasicBlock *BB) {
1339 if (const Instruction *I = dyn_cast<Instruction>(V))
1340 return I->getParent() == BB;
1341 return true;
1342}
1343
Chris Lattner571e4342006-10-27 21:36:01 +00001344/// FindMergedConditions - If Cond is an expression like
1345void SelectionDAGLowering::FindMergedConditions(Value *Cond,
1346 MachineBasicBlock *TBB,
1347 MachineBasicBlock *FBB,
1348 MachineBasicBlock *CurBB,
1349 unsigned Opc) {
Chris Lattner571e4342006-10-27 21:36:01 +00001350 // If this node is not part of the or/and tree, emit it as a branch.
Reid Spencere4d87aa2006-12-23 06:05:41 +00001351 Instruction *BOp = dyn_cast<Instruction>(Cond);
Chris Lattner571e4342006-10-27 21:36:01 +00001352
Reid Spencere4d87aa2006-12-23 06:05:41 +00001353 if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
1354 (unsigned)BOp->getOpcode() != Opc || !BOp->hasOneUse() ||
Chris Lattner6a586c82006-10-29 21:01:20 +00001355 BOp->getParent() != CurBB->getBasicBlock() ||
1356 !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
1357 !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
Chris Lattner571e4342006-10-27 21:36:01 +00001358 const BasicBlock *BB = CurBB->getBasicBlock();
1359
Reid Spencere4d87aa2006-12-23 06:05:41 +00001360 // If the leaf of the tree is a comparison, merge the condition into
1361 // the caseblock.
1362 if ((isa<ICmpInst>(Cond) || isa<FCmpInst>(Cond)) &&
1363 // The operands of the cmp have to be in this block. We don't know
Chris Lattner5a145f02006-10-29 18:23:37 +00001364 // how to export them from some other block. If this is the first block
1365 // of the sequence, no exporting is needed.
1366 (CurBB == CurMBB ||
1367 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
1368 isExportableFromCurrentBlock(BOp->getOperand(1), BB)))) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00001369 BOp = cast<Instruction>(Cond);
1370 ISD::CondCode Condition;
1371 if (ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
1372 switch (IC->getPredicate()) {
1373 default: assert(0 && "Unknown icmp predicate opcode!");
1374 case ICmpInst::ICMP_EQ: Condition = ISD::SETEQ; break;
1375 case ICmpInst::ICMP_NE: Condition = ISD::SETNE; break;
1376 case ICmpInst::ICMP_SLE: Condition = ISD::SETLE; break;
1377 case ICmpInst::ICMP_ULE: Condition = ISD::SETULE; break;
1378 case ICmpInst::ICMP_SGE: Condition = ISD::SETGE; break;
1379 case ICmpInst::ICMP_UGE: Condition = ISD::SETUGE; break;
1380 case ICmpInst::ICMP_SLT: Condition = ISD::SETLT; break;
1381 case ICmpInst::ICMP_ULT: Condition = ISD::SETULT; break;
1382 case ICmpInst::ICMP_SGT: Condition = ISD::SETGT; break;
1383 case ICmpInst::ICMP_UGT: Condition = ISD::SETUGT; break;
1384 }
1385 } else if (FCmpInst *FC = dyn_cast<FCmpInst>(Cond)) {
1386 ISD::CondCode FPC, FOC;
1387 switch (FC->getPredicate()) {
1388 default: assert(0 && "Unknown fcmp predicate opcode!");
1389 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
1390 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
1391 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
1392 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
1393 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
1394 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
1395 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
Chris Lattner6bf30ab2008-05-01 07:26:11 +00001396 case FCmpInst::FCMP_ORD: FOC = FPC = ISD::SETO; break;
1397 case FCmpInst::FCMP_UNO: FOC = FPC = ISD::SETUO; break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00001398 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
1399 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
1400 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
1401 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
1402 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
1403 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
1404 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
1405 }
1406 if (FiniteOnlyFPMath())
1407 Condition = FOC;
1408 else
1409 Condition = FPC;
1410 } else {
Chris Lattner0da331f2007-02-04 01:31:47 +00001411 Condition = ISD::SETEQ; // silence warning.
Reid Spencere4d87aa2006-12-23 06:05:41 +00001412 assert(0 && "Unknown compare instruction");
Chris Lattner571e4342006-10-27 21:36:01 +00001413 }
1414
Chris Lattner571e4342006-10-27 21:36:01 +00001415 SelectionDAGISel::CaseBlock CB(Condition, BOp->getOperand(0),
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001416 BOp->getOperand(1), NULL, TBB, FBB, CurBB);
Chris Lattner571e4342006-10-27 21:36:01 +00001417 SwitchCases.push_back(CB);
1418 return;
1419 }
1420
1421 // Create a CaseBlock record representing this branch.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001422 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, Cond, ConstantInt::getTrue(),
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001423 NULL, TBB, FBB, CurBB);
Chris Lattner571e4342006-10-27 21:36:01 +00001424 SwitchCases.push_back(CB);
Chris Lattner571e4342006-10-27 21:36:01 +00001425 return;
1426 }
1427
Chris Lattnerd2f9ee92006-10-27 21:54:23 +00001428
1429 // Create TmpBB after CurBB.
Chris Lattner571e4342006-10-27 21:36:01 +00001430 MachineFunction::iterator BBI = CurBB;
1431 MachineBasicBlock *TmpBB = new MachineBasicBlock(CurBB->getBasicBlock());
1432 CurBB->getParent()->getBasicBlockList().insert(++BBI, TmpBB);
1433
Chris Lattnerd2f9ee92006-10-27 21:54:23 +00001434 if (Opc == Instruction::Or) {
1435 // Codegen X | Y as:
1436 // jmp_if_X TBB
1437 // jmp TmpBB
1438 // TmpBB:
1439 // jmp_if_Y TBB
1440 // jmp FBB
1441 //
Chris Lattner571e4342006-10-27 21:36:01 +00001442
Chris Lattnerd2f9ee92006-10-27 21:54:23 +00001443 // Emit the LHS condition.
1444 FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, Opc);
1445
1446 // Emit the RHS condition into TmpBB.
1447 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
1448 } else {
1449 assert(Opc == Instruction::And && "Unknown merge op!");
1450 // Codegen X & Y as:
1451 // jmp_if_X TmpBB
1452 // jmp FBB
1453 // TmpBB:
1454 // jmp_if_Y TBB
1455 // jmp FBB
1456 //
1457 // This requires creation of TmpBB after CurBB.
1458
1459 // Emit the LHS condition.
1460 FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, Opc);
1461
1462 // Emit the RHS condition into TmpBB.
1463 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
1464 }
Chris Lattner571e4342006-10-27 21:36:01 +00001465}
1466
Chris Lattnerdf19f272006-10-31 22:37:42 +00001467/// If the set of cases should be emitted as a series of branches, return true.
1468/// If we should emit this as a bunch of and/or'd together conditions, return
1469/// false.
1470static bool
1471ShouldEmitAsBranches(const std::vector<SelectionDAGISel::CaseBlock> &Cases) {
1472 if (Cases.size() != 2) return true;
1473
Chris Lattner0ccb5002006-10-31 23:06:00 +00001474 // If this is two comparisons of the same values or'd or and'd together, they
1475 // will get folded into a single comparison, so don't emit two blocks.
1476 if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
1477 Cases[0].CmpRHS == Cases[1].CmpRHS) ||
1478 (Cases[0].CmpRHS == Cases[1].CmpLHS &&
1479 Cases[0].CmpLHS == Cases[1].CmpRHS)) {
1480 return false;
1481 }
1482
Chris Lattnerdf19f272006-10-31 22:37:42 +00001483 return true;
1484}
1485
Chris Lattner1c08c712005-01-07 07:47:53 +00001486void SelectionDAGLowering::visitBr(BranchInst &I) {
1487 // Update machine-CFG edges.
1488 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
Chris Lattner1c08c712005-01-07 07:47:53 +00001489
1490 // Figure out which block is immediately after the current one.
1491 MachineBasicBlock *NextBlock = 0;
1492 MachineFunction::iterator BBI = CurMBB;
1493 if (++BBI != CurMBB->getParent()->end())
1494 NextBlock = BBI;
1495
1496 if (I.isUnconditional()) {
Owen Anderson2d389e82008-06-07 00:00:23 +00001497 // Update machine-CFG edges.
1498 CurMBB->addSuccessor(Succ0MBB);
1499
Chris Lattner1c08c712005-01-07 07:47:53 +00001500 // If this is not a fall-through branch, emit the branch.
1501 if (Succ0MBB != NextBlock)
Dan Gohman86e1ebf2008-03-27 19:56:19 +00001502 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getControlRoot(),
Misha Brukmandedf2bd2005-04-22 04:01:18 +00001503 DAG.getBasicBlock(Succ0MBB)));
Chris Lattner57ab6592006-10-24 17:57:59 +00001504 return;
1505 }
1506
1507 // If this condition is one of the special cases we handle, do special stuff
1508 // now.
1509 Value *CondVal = I.getCondition();
Chris Lattner57ab6592006-10-24 17:57:59 +00001510 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
Chris Lattner571e4342006-10-27 21:36:01 +00001511
1512 // If this is a series of conditions that are or'd or and'd together, emit
1513 // this as a sequence of branches instead of setcc's with and/or operations.
1514 // For example, instead of something like:
1515 // cmp A, B
1516 // C = seteq
1517 // cmp D, E
1518 // F = setle
1519 // or C, F
1520 // jnz foo
1521 // Emit:
1522 // cmp A, B
1523 // je foo
1524 // cmp D, E
1525 // jle foo
1526 //
1527 if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
1528 if (BOp->hasOneUse() &&
Chris Lattnerd2f9ee92006-10-27 21:54:23 +00001529 (BOp->getOpcode() == Instruction::And ||
Chris Lattner571e4342006-10-27 21:36:01 +00001530 BOp->getOpcode() == Instruction::Or)) {
1531 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, CurMBB, BOp->getOpcode());
Chris Lattner0ccb5002006-10-31 23:06:00 +00001532 // If the compares in later blocks need to use values not currently
1533 // exported from this block, export them now. This block should always
1534 // be the first entry.
1535 assert(SwitchCases[0].ThisBB == CurMBB && "Unexpected lowering!");
1536
Chris Lattnerdf19f272006-10-31 22:37:42 +00001537 // Allow some cases to be rejected.
1538 if (ShouldEmitAsBranches(SwitchCases)) {
Chris Lattnerdf19f272006-10-31 22:37:42 +00001539 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
1540 ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
1541 ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
1542 }
1543
1544 // Emit the branch for this block.
1545 visitSwitchCase(SwitchCases[0]);
1546 SwitchCases.erase(SwitchCases.begin());
1547 return;
Chris Lattner5a145f02006-10-29 18:23:37 +00001548 }
1549
Chris Lattner0ccb5002006-10-31 23:06:00 +00001550 // Okay, we decided not to do this, remove any inserted MBB's and clear
1551 // SwitchCases.
1552 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
1553 CurMBB->getParent()->getBasicBlockList().erase(SwitchCases[i].ThisBB);
1554
Chris Lattnerdf19f272006-10-31 22:37:42 +00001555 SwitchCases.clear();
Chris Lattner571e4342006-10-27 21:36:01 +00001556 }
1557 }
Chris Lattner24525952006-10-24 18:07:37 +00001558
1559 // Create a CaseBlock record representing this branch.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001560 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(),
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001561 NULL, Succ0MBB, Succ1MBB, CurMBB);
Chris Lattner24525952006-10-24 18:07:37 +00001562 // Use visitSwitchCase to actually insert the fast branch sequence for this
1563 // cond branch.
1564 visitSwitchCase(CB);
Chris Lattner1c08c712005-01-07 07:47:53 +00001565}
1566
Nate Begemanf15485a2006-03-27 01:32:24 +00001567/// visitSwitchCase - Emits the necessary code to represent a single node in
1568/// the binary search tree resulting from lowering a switch instruction.
1569void SelectionDAGLowering::visitSwitchCase(SelectionDAGISel::CaseBlock &CB) {
Chris Lattner57ab6592006-10-24 17:57:59 +00001570 SDOperand Cond;
1571 SDOperand CondLHS = getValue(CB.CmpLHS);
1572
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001573 // Build the setcc now.
1574 if (CB.CmpMHS == NULL) {
1575 // Fold "(X == true)" to X and "(X == false)" to !X to
1576 // handle common cases produced by branch lowering.
1577 if (CB.CmpRHS == ConstantInt::getTrue() && CB.CC == ISD::SETEQ)
1578 Cond = CondLHS;
1579 else if (CB.CmpRHS == ConstantInt::getFalse() && CB.CC == ISD::SETEQ) {
1580 SDOperand True = DAG.getConstant(1, CondLHS.getValueType());
1581 Cond = DAG.getNode(ISD::XOR, CondLHS.getValueType(), CondLHS, True);
1582 } else
1583 Cond = DAG.getSetCC(MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
1584 } else {
1585 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001586
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001587 uint64_t Low = cast<ConstantInt>(CB.CmpLHS)->getSExtValue();
1588 uint64_t High = cast<ConstantInt>(CB.CmpRHS)->getSExtValue();
1589
1590 SDOperand CmpOp = getValue(CB.CmpMHS);
Duncan Sands83ec4b62008-06-06 12:08:01 +00001591 MVT VT = CmpOp.getValueType();
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001592
1593 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
1594 Cond = DAG.getSetCC(MVT::i1, CmpOp, DAG.getConstant(High, VT), ISD::SETLE);
1595 } else {
1596 SDOperand SUB = DAG.getNode(ISD::SUB, VT, CmpOp, DAG.getConstant(Low, VT));
1597 Cond = DAG.getSetCC(MVT::i1, SUB,
1598 DAG.getConstant(High-Low, VT), ISD::SETULE);
1599 }
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001600 }
1601
Owen Anderson2d389e82008-06-07 00:00:23 +00001602 // Update successor info
1603 CurMBB->addSuccessor(CB.TrueBB);
1604 CurMBB->addSuccessor(CB.FalseBB);
1605
Nate Begemanf15485a2006-03-27 01:32:24 +00001606 // Set NextBlock to be the MBB immediately after the current one, if any.
1607 // This is used to avoid emitting unnecessary branches to the next block.
1608 MachineBasicBlock *NextBlock = 0;
1609 MachineFunction::iterator BBI = CurMBB;
1610 if (++BBI != CurMBB->getParent()->end())
1611 NextBlock = BBI;
1612
1613 // If the lhs block is the next block, invert the condition so that we can
1614 // fall through to the lhs instead of the rhs block.
Chris Lattner57ab6592006-10-24 17:57:59 +00001615 if (CB.TrueBB == NextBlock) {
1616 std::swap(CB.TrueBB, CB.FalseBB);
Nate Begemanf15485a2006-03-27 01:32:24 +00001617 SDOperand True = DAG.getConstant(1, Cond.getValueType());
1618 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
1619 }
Dan Gohman86e1ebf2008-03-27 19:56:19 +00001620 SDOperand BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, getControlRoot(), Cond,
Chris Lattner57ab6592006-10-24 17:57:59 +00001621 DAG.getBasicBlock(CB.TrueBB));
1622 if (CB.FalseBB == NextBlock)
Nate Begemanf15485a2006-03-27 01:32:24 +00001623 DAG.setRoot(BrCond);
1624 else
1625 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond,
Chris Lattner57ab6592006-10-24 17:57:59 +00001626 DAG.getBasicBlock(CB.FalseBB)));
Nate Begemanf15485a2006-03-27 01:32:24 +00001627}
1628
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001629/// visitJumpTable - Emit JumpTable node in the current MBB
Nate Begeman37efe672006-04-22 18:53:45 +00001630void SelectionDAGLowering::visitJumpTable(SelectionDAGISel::JumpTable &JT) {
Nate Begeman37efe672006-04-22 18:53:45 +00001631 // Emit the code for the jump table
Scott Michelf147a8d2007-04-24 01:24:20 +00001632 assert(JT.Reg != -1U && "Should lower JT Header first!");
Duncan Sands83ec4b62008-06-06 12:08:01 +00001633 MVT PTy = TLI.getPointerTy();
Dan Gohman86e1ebf2008-03-27 19:56:19 +00001634 SDOperand Index = DAG.getCopyFromReg(getControlRoot(), JT.Reg, PTy);
Evan Cheng3d4ce112006-10-30 08:00:44 +00001635 SDOperand Table = DAG.getJumpTable(JT.JTI, PTy);
1636 DAG.setRoot(DAG.getNode(ISD::BR_JT, MVT::Other, Index.getValue(1),
1637 Table, Index));
1638 return;
Nate Begeman37efe672006-04-22 18:53:45 +00001639}
1640
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001641/// visitJumpTableHeader - This function emits necessary code to produce index
1642/// in the JumpTable from switch case.
1643void SelectionDAGLowering::visitJumpTableHeader(SelectionDAGISel::JumpTable &JT,
1644 SelectionDAGISel::JumpTableHeader &JTH) {
1645 // Subtract the lowest switch case value from the value being switched on
1646 // and conditional branch to default mbb if the result is greater than the
1647 // difference between smallest and largest cases.
1648 SDOperand SwitchOp = getValue(JTH.SValue);
Duncan Sands83ec4b62008-06-06 12:08:01 +00001649 MVT VT = SwitchOp.getValueType();
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001650 SDOperand SUB = DAG.getNode(ISD::SUB, VT, SwitchOp,
1651 DAG.getConstant(JTH.First, VT));
1652
1653 // The SDNode we just created, which holds the value being switched on
1654 // minus the the smallest case value, needs to be copied to a virtual
1655 // register so it can be used as an index into the jump table in a
1656 // subsequent basic block. This value may be smaller or larger than the
1657 // target's pointer type, and therefore require extension or truncating.
Duncan Sands8e4eb092008-06-08 20:54:56 +00001658 if (VT.bitsGT(TLI.getPointerTy()))
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001659 SwitchOp = DAG.getNode(ISD::TRUNCATE, TLI.getPointerTy(), SUB);
1660 else
1661 SwitchOp = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(), SUB);
1662
1663 unsigned JumpTableReg = FuncInfo.MakeReg(TLI.getPointerTy());
Dan Gohman86e1ebf2008-03-27 19:56:19 +00001664 SDOperand CopyTo = DAG.getCopyToReg(getControlRoot(), JumpTableReg, SwitchOp);
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001665 JT.Reg = JumpTableReg;
1666
1667 // Emit the range check for the jump table, and branch to the default
1668 // block for the switch statement if the value being switched on exceeds
1669 // the largest case in the switch.
Scott Michel5b8f82e2008-03-10 15:42:14 +00001670 SDOperand CMP = DAG.getSetCC(TLI.getSetCCResultType(SUB), SUB,
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001671 DAG.getConstant(JTH.Last-JTH.First,VT),
1672 ISD::SETUGT);
1673
1674 // Set NextBlock to be the MBB immediately after the current one, if any.
1675 // This is used to avoid emitting unnecessary branches to the next block.
1676 MachineBasicBlock *NextBlock = 0;
1677 MachineFunction::iterator BBI = CurMBB;
1678 if (++BBI != CurMBB->getParent()->end())
1679 NextBlock = BBI;
1680
1681 SDOperand BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, CopyTo, CMP,
1682 DAG.getBasicBlock(JT.Default));
1683
1684 if (JT.MBB == NextBlock)
1685 DAG.setRoot(BrCond);
1686 else
1687 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond,
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001688 DAG.getBasicBlock(JT.MBB)));
1689
1690 return;
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001691}
1692
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001693/// visitBitTestHeader - This function emits necessary code to produce value
1694/// suitable for "bit tests"
1695void SelectionDAGLowering::visitBitTestHeader(SelectionDAGISel::BitTestBlock &B) {
1696 // Subtract the minimum value
1697 SDOperand SwitchOp = getValue(B.SValue);
Duncan Sands83ec4b62008-06-06 12:08:01 +00001698 MVT VT = SwitchOp.getValueType();
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001699 SDOperand SUB = DAG.getNode(ISD::SUB, VT, SwitchOp,
1700 DAG.getConstant(B.First, VT));
1701
1702 // Check range
Scott Michel5b8f82e2008-03-10 15:42:14 +00001703 SDOperand RangeCmp = DAG.getSetCC(TLI.getSetCCResultType(SUB), SUB,
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001704 DAG.getConstant(B.Range, VT),
1705 ISD::SETUGT);
1706
1707 SDOperand ShiftOp;
Duncan Sands8e4eb092008-06-08 20:54:56 +00001708 if (VT.bitsGT(TLI.getShiftAmountTy()))
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001709 ShiftOp = DAG.getNode(ISD::TRUNCATE, TLI.getShiftAmountTy(), SUB);
1710 else
1711 ShiftOp = DAG.getNode(ISD::ZERO_EXTEND, TLI.getShiftAmountTy(), SUB);
1712
1713 // Make desired shift
1714 SDOperand SwitchVal = DAG.getNode(ISD::SHL, TLI.getPointerTy(),
1715 DAG.getConstant(1, TLI.getPointerTy()),
1716 ShiftOp);
1717
1718 unsigned SwitchReg = FuncInfo.MakeReg(TLI.getPointerTy());
Dan Gohman86e1ebf2008-03-27 19:56:19 +00001719 SDOperand CopyTo = DAG.getCopyToReg(getControlRoot(), SwitchReg, SwitchVal);
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001720 B.Reg = SwitchReg;
1721
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001722 // Set NextBlock to be the MBB immediately after the current one, if any.
1723 // This is used to avoid emitting unnecessary branches to the next block.
1724 MachineBasicBlock *NextBlock = 0;
1725 MachineFunction::iterator BBI = CurMBB;
1726 if (++BBI != CurMBB->getParent()->end())
1727 NextBlock = BBI;
1728
1729 MachineBasicBlock* MBB = B.Cases[0].ThisBB;
Owen Anderson2d389e82008-06-07 00:00:23 +00001730
1731 CurMBB->addSuccessor(B.Default);
1732 CurMBB->addSuccessor(MBB);
1733
1734 SDOperand BrRange = DAG.getNode(ISD::BRCOND, MVT::Other, CopyTo, RangeCmp,
1735 DAG.getBasicBlock(B.Default));
1736
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001737 if (MBB == NextBlock)
1738 DAG.setRoot(BrRange);
1739 else
1740 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, CopyTo,
1741 DAG.getBasicBlock(MBB)));
1742
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001743 return;
1744}
1745
1746/// visitBitTestCase - this function produces one "bit test"
1747void SelectionDAGLowering::visitBitTestCase(MachineBasicBlock* NextMBB,
1748 unsigned Reg,
1749 SelectionDAGISel::BitTestCase &B) {
1750 // Emit bit tests and jumps
Dan Gohman86e1ebf2008-03-27 19:56:19 +00001751 SDOperand SwitchVal = DAG.getCopyFromReg(getControlRoot(), Reg, TLI.getPointerTy());
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001752
1753 SDOperand AndOp = DAG.getNode(ISD::AND, TLI.getPointerTy(),
1754 SwitchVal,
1755 DAG.getConstant(B.Mask,
1756 TLI.getPointerTy()));
Scott Michel5b8f82e2008-03-10 15:42:14 +00001757 SDOperand AndCmp = DAG.getSetCC(TLI.getSetCCResultType(AndOp), AndOp,
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001758 DAG.getConstant(0, TLI.getPointerTy()),
1759 ISD::SETNE);
Owen Anderson2d389e82008-06-07 00:00:23 +00001760
1761 CurMBB->addSuccessor(B.TargetBB);
1762 CurMBB->addSuccessor(NextMBB);
1763
Dan Gohman86e1ebf2008-03-27 19:56:19 +00001764 SDOperand BrAnd = DAG.getNode(ISD::BRCOND, MVT::Other, getControlRoot(),
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001765 AndCmp, DAG.getBasicBlock(B.TargetBB));
1766
1767 // Set NextBlock to be the MBB immediately after the current one, if any.
1768 // This is used to avoid emitting unnecessary branches to the next block.
1769 MachineBasicBlock *NextBlock = 0;
1770 MachineFunction::iterator BBI = CurMBB;
1771 if (++BBI != CurMBB->getParent()->end())
1772 NextBlock = BBI;
1773
1774 if (NextMBB == NextBlock)
1775 DAG.setRoot(BrAnd);
1776 else
1777 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrAnd,
1778 DAG.getBasicBlock(NextMBB)));
1779
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001780 return;
1781}
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001782
Jim Laskeyb180aa12007-02-21 22:53:45 +00001783void SelectionDAGLowering::visitInvoke(InvokeInst &I) {
1784 // Retrieve successors.
1785 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
Duncan Sandsf19f6bb2007-06-13 05:51:31 +00001786 MachineBasicBlock *LandingPad = FuncInfo.MBBMap[I.getSuccessor(1)];
Duncan Sands9fac0b52007-06-06 10:05:18 +00001787
Duncan Sandsfd7b3262007-12-17 18:08:19 +00001788 if (isa<InlineAsm>(I.getCalledValue()))
1789 visitInlineAsm(&I);
1790 else
Duncan Sands6f74b482007-12-19 09:48:52 +00001791 LowerCallTo(&I, getValue(I.getOperand(0)), false, LandingPad);
Duncan Sands9fac0b52007-06-06 10:05:18 +00001792
Duncan Sandsf19f6bb2007-06-13 05:51:31 +00001793 // If the value of the invoke is used outside of its defining block, make it
1794 // available as a virtual register.
1795 if (!I.use_empty()) {
1796 DenseMap<const Value*, unsigned>::iterator VMI = FuncInfo.ValueMap.find(&I);
1797 if (VMI != FuncInfo.ValueMap.end())
Dan Gohman86e1ebf2008-03-27 19:56:19 +00001798 CopyValueToVirtualRegister(&I, VMI->second);
Jim Laskey183f47f2007-02-25 21:43:59 +00001799 }
Duncan Sandsf19f6bb2007-06-13 05:51:31 +00001800
Duncan Sandsf19f6bb2007-06-13 05:51:31 +00001801 // Update successor info
1802 CurMBB->addSuccessor(Return);
1803 CurMBB->addSuccessor(LandingPad);
Owen Anderson2d389e82008-06-07 00:00:23 +00001804
1805 // Drop into normal successor.
1806 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getControlRoot(),
1807 DAG.getBasicBlock(Return)));
Jim Laskeyb180aa12007-02-21 22:53:45 +00001808}
1809
1810void SelectionDAGLowering::visitUnwind(UnwindInst &I) {
1811}
1812
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001813/// handleSmallSwitchCaseRange - Emit a series of specific tests (suitable for
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001814/// small case ranges).
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001815bool SelectionDAGLowering::handleSmallSwitchRange(CaseRec& CR,
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001816 CaseRecVector& WorkList,
1817 Value* SV,
1818 MachineBasicBlock* Default) {
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001819 Case& BackCase = *(CR.Range.second-1);
1820
1821 // Size is the number of Cases represented by this range.
1822 unsigned Size = CR.Range.second - CR.Range.first;
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001823 if (Size > 3)
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001824 return false;
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001825
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001826 // Get the MachineFunction which holds the current MBB. This is used when
1827 // inserting any additional MBBs necessary to represent the switch.
1828 MachineFunction *CurMF = CurMBB->getParent();
1829
1830 // Figure out which block is immediately after the current one.
1831 MachineBasicBlock *NextBlock = 0;
1832 MachineFunction::iterator BBI = CR.CaseBB;
1833
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001834 if (++BBI != CurMBB->getParent()->end())
1835 NextBlock = BBI;
1836
1837 // TODO: If any two of the cases has the same destination, and if one value
1838 // is the same as the other, but has one bit unset that the other has set,
1839 // use bit manipulation to do two compares at once. For example:
1840 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
1841
1842 // Rearrange the case blocks so that the last one falls through if possible.
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001843 if (NextBlock && Default != NextBlock && BackCase.BB != NextBlock) {
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001844 // The last case block won't fall through into 'NextBlock' if we emit the
1845 // branches in this order. See if rearranging a case value would help.
1846 for (CaseItr I = CR.Range.first, E = CR.Range.second-1; I != E; ++I) {
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001847 if (I->BB == NextBlock) {
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001848 std::swap(*I, BackCase);
1849 break;
1850 }
1851 }
1852 }
1853
1854 // Create a CaseBlock record representing a conditional branch to
1855 // the Case's target mbb if the value being switched on SV is equal
1856 // to C.
1857 MachineBasicBlock *CurBlock = CR.CaseBB;
1858 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I) {
1859 MachineBasicBlock *FallThrough;
1860 if (I != E-1) {
1861 FallThrough = new MachineBasicBlock(CurBlock->getBasicBlock());
1862 CurMF->getBasicBlockList().insert(BBI, FallThrough);
1863 } else {
1864 // If the last case doesn't match, go to the default block.
1865 FallThrough = Default;
1866 }
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001867
1868 Value *RHS, *LHS, *MHS;
1869 ISD::CondCode CC;
1870 if (I->High == I->Low) {
1871 // This is just small small case range :) containing exactly 1 case
1872 CC = ISD::SETEQ;
1873 LHS = SV; RHS = I->High; MHS = NULL;
1874 } else {
1875 CC = ISD::SETLE;
1876 LHS = I->Low; MHS = SV; RHS = I->High;
1877 }
1878 SelectionDAGISel::CaseBlock CB(CC, LHS, RHS, MHS,
1879 I->BB, FallThrough, CurBlock);
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001880
1881 // If emitting the first comparison, just call visitSwitchCase to emit the
1882 // code into the current block. Otherwise, push the CaseBlock onto the
1883 // vector to be later processed by SDISel, and insert the node's MBB
1884 // before the next MBB.
1885 if (CurBlock == CurMBB)
1886 visitSwitchCase(CB);
1887 else
1888 SwitchCases.push_back(CB);
1889
1890 CurBlock = FallThrough;
1891 }
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001892
1893 return true;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001894}
1895
Anton Korobeynikov7294b582007-05-09 20:07:08 +00001896static inline bool areJTsAllowed(const TargetLowering &TLI) {
1897 return (TLI.isOperationLegal(ISD::BR_JT, MVT::Other) ||
1898 TLI.isOperationLegal(ISD::BRIND, MVT::Other));
1899}
1900
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001901/// handleJTSwitchCase - Emit jumptable for current switch case range
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001902bool SelectionDAGLowering::handleJTSwitchCase(CaseRec& CR,
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001903 CaseRecVector& WorkList,
1904 Value* SV,
1905 MachineBasicBlock* Default) {
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001906 Case& FrontCase = *CR.Range.first;
1907 Case& BackCase = *(CR.Range.second-1);
1908
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001909 int64_t First = cast<ConstantInt>(FrontCase.Low)->getSExtValue();
1910 int64_t Last = cast<ConstantInt>(BackCase.High)->getSExtValue();
1911
1912 uint64_t TSize = 0;
1913 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1914 I!=E; ++I)
1915 TSize += I->size();
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001916
Anton Korobeynikov7294b582007-05-09 20:07:08 +00001917 if (!areJTsAllowed(TLI) || TSize <= 3)
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001918 return false;
1919
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001920 double Density = (double)TSize / (double)((Last - First) + 1ULL);
1921 if (Density < 0.4)
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001922 return false;
1923
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001924 DOUT << "Lowering jump table\n"
1925 << "First entry: " << First << ". Last entry: " << Last << "\n"
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001926 << "Size: " << TSize << ". Density: " << Density << "\n\n";
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001927
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001928 // Get the MachineFunction which holds the current MBB. This is used when
1929 // inserting any additional MBBs necessary to represent the switch.
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001930 MachineFunction *CurMF = CurMBB->getParent();
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001931
1932 // Figure out which block is immediately after the current one.
1933 MachineBasicBlock *NextBlock = 0;
1934 MachineFunction::iterator BBI = CR.CaseBB;
1935
1936 if (++BBI != CurMBB->getParent()->end())
1937 NextBlock = BBI;
1938
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001939 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1940
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001941 // Create a new basic block to hold the code for loading the address
1942 // of the jump table, and jumping to it. Update successor information;
1943 // we will either branch to the default case for the switch, or the jump
1944 // table.
1945 MachineBasicBlock *JumpTableBB = new MachineBasicBlock(LLVMBB);
1946 CurMF->getBasicBlockList().insert(BBI, JumpTableBB);
1947 CR.CaseBB->addSuccessor(Default);
1948 CR.CaseBB->addSuccessor(JumpTableBB);
1949
1950 // Build a vector of destination BBs, corresponding to each target
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001951 // of the jump table. If the value of the jump table slot corresponds to
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001952 // a case statement, push the case's BB onto the vector, otherwise, push
1953 // the default BB.
1954 std::vector<MachineBasicBlock*> DestBBs;
1955 int64_t TEI = First;
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001956 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++TEI) {
1957 int64_t Low = cast<ConstantInt>(I->Low)->getSExtValue();
1958 int64_t High = cast<ConstantInt>(I->High)->getSExtValue();
1959
1960 if ((Low <= TEI) && (TEI <= High)) {
1961 DestBBs.push_back(I->BB);
1962 if (TEI==High)
1963 ++I;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001964 } else {
1965 DestBBs.push_back(Default);
1966 }
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001967 }
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001968
1969 // Update successor info. Add one edge to each unique successor.
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001970 BitVector SuccsHandled(CR.CaseBB->getParent()->getNumBlockIDs());
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001971 for (std::vector<MachineBasicBlock*>::iterator I = DestBBs.begin(),
1972 E = DestBBs.end(); I != E; ++I) {
1973 if (!SuccsHandled[(*I)->getNumber()]) {
1974 SuccsHandled[(*I)->getNumber()] = true;
1975 JumpTableBB->addSuccessor(*I);
1976 }
1977 }
1978
1979 // Create a jump table index for this jump table, or return an existing
1980 // one.
1981 unsigned JTI = CurMF->getJumpTableInfo()->getJumpTableIndex(DestBBs);
1982
1983 // Set the jump table information so that we can codegen it as a second
1984 // MachineBasicBlock
Scott Michelf147a8d2007-04-24 01:24:20 +00001985 SelectionDAGISel::JumpTable JT(-1U, JTI, JumpTableBB, Default);
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001986 SelectionDAGISel::JumpTableHeader JTH(First, Last, SV, CR.CaseBB,
1987 (CR.CaseBB == CurMBB));
1988 if (CR.CaseBB == CurMBB)
1989 visitJumpTableHeader(JT, JTH);
1990
1991 JTCases.push_back(SelectionDAGISel::JumpTableBlock(JTH, JT));
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001992
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001993 return true;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001994}
1995
1996/// handleBTSplitSwitchCase - emit comparison and split binary search tree into
1997/// 2 subtrees.
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001998bool SelectionDAGLowering::handleBTSplitSwitchCase(CaseRec& CR,
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001999 CaseRecVector& WorkList,
2000 Value* SV,
2001 MachineBasicBlock* Default) {
2002 // Get the MachineFunction which holds the current MBB. This is used when
2003 // inserting any additional MBBs necessary to represent the switch.
2004 MachineFunction *CurMF = CurMBB->getParent();
2005
2006 // Figure out which block is immediately after the current one.
2007 MachineBasicBlock *NextBlock = 0;
2008 MachineFunction::iterator BBI = CR.CaseBB;
2009
2010 if (++BBI != CurMBB->getParent()->end())
2011 NextBlock = BBI;
2012
2013 Case& FrontCase = *CR.Range.first;
2014 Case& BackCase = *(CR.Range.second-1);
2015 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
2016
2017 // Size is the number of Cases represented by this range.
2018 unsigned Size = CR.Range.second - CR.Range.first;
2019
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002020 int64_t First = cast<ConstantInt>(FrontCase.Low)->getSExtValue();
2021 int64_t Last = cast<ConstantInt>(BackCase.High)->getSExtValue();
Anton Korobeynikov4198c582007-04-09 12:31:58 +00002022 double FMetric = 0;
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002023 CaseItr Pivot = CR.Range.first + Size/2;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00002024
2025 // Select optimal pivot, maximizing sum density of LHS and RHS. This will
2026 // (heuristically) allow us to emit JumpTable's later.
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002027 uint64_t TSize = 0;
2028 for (CaseItr I = CR.Range.first, E = CR.Range.second;
2029 I!=E; ++I)
2030 TSize += I->size();
2031
2032 uint64_t LSize = FrontCase.size();
2033 uint64_t RSize = TSize-LSize;
Anton Korobeynikov4198c582007-04-09 12:31:58 +00002034 DOUT << "Selecting best pivot: \n"
2035 << "First: " << First << ", Last: " << Last <<"\n"
2036 << "LSize: " << LSize << ", RSize: " << RSize << "\n";
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00002037 for (CaseItr I = CR.Range.first, J=I+1, E = CR.Range.second;
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002038 J!=E; ++I, ++J) {
2039 int64_t LEnd = cast<ConstantInt>(I->High)->getSExtValue();
2040 int64_t RBegin = cast<ConstantInt>(J->Low)->getSExtValue();
Anton Korobeynikov4198c582007-04-09 12:31:58 +00002041 assert((RBegin-LEnd>=1) && "Invalid case distance");
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00002042 double LDensity = (double)LSize / (double)((LEnd - First) + 1ULL);
2043 double RDensity = (double)RSize / (double)((Last - RBegin) + 1ULL);
Anton Korobeynikov54e2b142007-04-09 21:57:03 +00002044 double Metric = Log2_64(RBegin-LEnd)*(LDensity+RDensity);
Anton Korobeynikov4198c582007-04-09 12:31:58 +00002045 // Should always split in some non-trivial place
2046 DOUT <<"=>Step\n"
2047 << "LEnd: " << LEnd << ", RBegin: " << RBegin << "\n"
2048 << "LDensity: " << LDensity << ", RDensity: " << RDensity << "\n"
2049 << "Metric: " << Metric << "\n";
2050 if (FMetric < Metric) {
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00002051 Pivot = J;
Anton Korobeynikov4198c582007-04-09 12:31:58 +00002052 FMetric = Metric;
2053 DOUT << "Current metric set to: " << FMetric << "\n";
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00002054 }
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002055
2056 LSize += J->size();
2057 RSize -= J->size();
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00002058 }
Anton Korobeynikov7294b582007-05-09 20:07:08 +00002059 if (areJTsAllowed(TLI)) {
2060 // If our case is dense we *really* should handle it earlier!
2061 assert((FMetric > 0) && "Should handle dense range earlier!");
2062 } else {
2063 Pivot = CR.Range.first + Size/2;
2064 }
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00002065
2066 CaseRange LHSR(CR.Range.first, Pivot);
2067 CaseRange RHSR(Pivot, CR.Range.second);
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002068 Constant *C = Pivot->Low;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00002069 MachineBasicBlock *FalseBB = 0, *TrueBB = 0;
2070
2071 // We know that we branch to the LHS if the Value being switched on is
2072 // less than the Pivot value, C. We use this to optimize our binary
2073 // tree a bit, by recognizing that if SV is greater than or equal to the
2074 // LHS's Case Value, and that Case Value is exactly one less than the
2075 // Pivot's Value, then we can branch directly to the LHS's Target,
2076 // rather than creating a leaf node for it.
2077 if ((LHSR.second - LHSR.first) == 1 &&
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002078 LHSR.first->High == CR.GE &&
2079 cast<ConstantInt>(C)->getSExtValue() ==
2080 (cast<ConstantInt>(CR.GE)->getSExtValue() + 1LL)) {
2081 TrueBB = LHSR.first->BB;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00002082 } else {
2083 TrueBB = new MachineBasicBlock(LLVMBB);
2084 CurMF->getBasicBlockList().insert(BBI, TrueBB);
2085 WorkList.push_back(CaseRec(TrueBB, C, CR.GE, LHSR));
2086 }
2087
2088 // Similar to the optimization above, if the Value being switched on is
2089 // known to be less than the Constant CR.LT, and the current Case Value
2090 // is CR.LT - 1, then we can branch directly to the target block for
2091 // the current Case Value, rather than emitting a RHS leaf node for it.
2092 if ((RHSR.second - RHSR.first) == 1 && CR.LT &&
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002093 cast<ConstantInt>(RHSR.first->Low)->getSExtValue() ==
2094 (cast<ConstantInt>(CR.LT)->getSExtValue() - 1LL)) {
2095 FalseBB = RHSR.first->BB;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00002096 } else {
2097 FalseBB = new MachineBasicBlock(LLVMBB);
2098 CurMF->getBasicBlockList().insert(BBI, FalseBB);
2099 WorkList.push_back(CaseRec(FalseBB,CR.LT,C,RHSR));
2100 }
2101
2102 // Create a CaseBlock record representing a conditional branch to
2103 // the LHS node if the value being switched on SV is less than C.
2104 // Otherwise, branch to LHS.
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002105 SelectionDAGISel::CaseBlock CB(ISD::SETLT, SV, C, NULL,
2106 TrueBB, FalseBB, CR.CaseBB);
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00002107
2108 if (CR.CaseBB == CurMBB)
2109 visitSwitchCase(CB);
2110 else
2111 SwitchCases.push_back(CB);
Anton Korobeynikovdd433212007-03-27 12:05:48 +00002112
2113 return true;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00002114}
2115
Anton Korobeynikov4198c582007-04-09 12:31:58 +00002116/// handleBitTestsSwitchCase - if current case range has few destination and
2117/// range span less, than machine word bitwidth, encode case range into series
2118/// of masks and emit bit tests with these masks.
2119bool SelectionDAGLowering::handleBitTestsSwitchCase(CaseRec& CR,
2120 CaseRecVector& WorkList,
2121 Value* SV,
Chris Lattner3ff98172007-04-14 02:26:56 +00002122 MachineBasicBlock* Default){
Duncan Sands83ec4b62008-06-06 12:08:01 +00002123 unsigned IntPtrBits = TLI.getPointerTy().getSizeInBits();
Anton Korobeynikov4198c582007-04-09 12:31:58 +00002124
2125 Case& FrontCase = *CR.Range.first;
2126 Case& BackCase = *(CR.Range.second-1);
2127
2128 // Get the MachineFunction which holds the current MBB. This is used when
2129 // inserting any additional MBBs necessary to represent the switch.
2130 MachineFunction *CurMF = CurMBB->getParent();
2131
2132 unsigned numCmps = 0;
2133 for (CaseItr I = CR.Range.first, E = CR.Range.second;
2134 I!=E; ++I) {
2135 // Single case counts one, case range - two.
2136 if (I->Low == I->High)
2137 numCmps +=1;
2138 else
2139 numCmps +=2;
2140 }
2141
2142 // Count unique destinations
2143 SmallSet<MachineBasicBlock*, 4> Dests;
2144 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
2145 Dests.insert(I->BB);
2146 if (Dests.size() > 3)
2147 // Don't bother the code below, if there are too much unique destinations
2148 return false;
2149 }
2150 DOUT << "Total number of unique destinations: " << Dests.size() << "\n"
2151 << "Total number of comparisons: " << numCmps << "\n";
2152
2153 // Compute span of values.
2154 Constant* minValue = FrontCase.Low;
2155 Constant* maxValue = BackCase.High;
2156 uint64_t range = cast<ConstantInt>(maxValue)->getSExtValue() -
2157 cast<ConstantInt>(minValue)->getSExtValue();
2158 DOUT << "Compare range: " << range << "\n"
2159 << "Low bound: " << cast<ConstantInt>(minValue)->getSExtValue() << "\n"
2160 << "High bound: " << cast<ConstantInt>(maxValue)->getSExtValue() << "\n";
2161
Anton Korobeynikovab8fd402007-04-26 20:44:04 +00002162 if (range>=IntPtrBits ||
Anton Korobeynikov4198c582007-04-09 12:31:58 +00002163 (!(Dests.size() == 1 && numCmps >= 3) &&
2164 !(Dests.size() == 2 && numCmps >= 5) &&
2165 !(Dests.size() >= 3 && numCmps >= 6)))
2166 return false;
2167
2168 DOUT << "Emitting bit tests\n";
2169 int64_t lowBound = 0;
2170
2171 // Optimize the case where all the case values fit in a
2172 // word without having to subtract minValue. In this case,
2173 // we can optimize away the subtraction.
2174 if (cast<ConstantInt>(minValue)->getSExtValue() >= 0 &&
Anton Korobeynikove01017b2007-04-14 13:25:55 +00002175 cast<ConstantInt>(maxValue)->getSExtValue() < IntPtrBits) {
Anton Korobeynikov4198c582007-04-09 12:31:58 +00002176 range = cast<ConstantInt>(maxValue)->getSExtValue();
2177 } else {
2178 lowBound = cast<ConstantInt>(minValue)->getSExtValue();
2179 }
2180
2181 CaseBitsVector CasesBits;
2182 unsigned i, count = 0;
2183
2184 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
2185 MachineBasicBlock* Dest = I->BB;
2186 for (i = 0; i < count; ++i)
2187 if (Dest == CasesBits[i].BB)
2188 break;
2189
2190 if (i == count) {
2191 assert((count < 3) && "Too much destinations to test!");
2192 CasesBits.push_back(CaseBits(0, Dest, 0));
2193 count++;
2194 }
2195
2196 uint64_t lo = cast<ConstantInt>(I->Low)->getSExtValue() - lowBound;
2197 uint64_t hi = cast<ConstantInt>(I->High)->getSExtValue() - lowBound;
2198
2199 for (uint64_t j = lo; j <= hi; j++) {
Anton Korobeynikove01017b2007-04-14 13:25:55 +00002200 CasesBits[i].Mask |= 1ULL << j;
Anton Korobeynikov4198c582007-04-09 12:31:58 +00002201 CasesBits[i].Bits++;
2202 }
2203
2204 }
2205 std::sort(CasesBits.begin(), CasesBits.end(), CaseBitsCmp());
2206
2207 SelectionDAGISel::BitTestInfo BTC;
2208
2209 // Figure out which block is immediately after the current one.
2210 MachineFunction::iterator BBI = CR.CaseBB;
2211 ++BBI;
2212
2213 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
2214
2215 DOUT << "Cases:\n";
2216 for (unsigned i = 0, e = CasesBits.size(); i!=e; ++i) {
2217 DOUT << "Mask: " << CasesBits[i].Mask << ", Bits: " << CasesBits[i].Bits
2218 << ", BB: " << CasesBits[i].BB << "\n";
2219
2220 MachineBasicBlock *CaseBB = new MachineBasicBlock(LLVMBB);
2221 CurMF->getBasicBlockList().insert(BBI, CaseBB);
2222 BTC.push_back(SelectionDAGISel::BitTestCase(CasesBits[i].Mask,
2223 CaseBB,
2224 CasesBits[i].BB));
2225 }
2226
2227 SelectionDAGISel::BitTestBlock BTB(lowBound, range, SV,
Jeff Cohenefc36622007-04-09 14:32:59 +00002228 -1U, (CR.CaseBB == CurMBB),
Anton Korobeynikov4198c582007-04-09 12:31:58 +00002229 CR.CaseBB, Default, BTC);
2230
2231 if (CR.CaseBB == CurMBB)
2232 visitBitTestHeader(BTB);
2233
2234 BitTestCases.push_back(BTB);
2235
2236 return true;
2237}
2238
2239
Dan Gohman86e1ebf2008-03-27 19:56:19 +00002240/// Clusterify - Transform simple list of Cases into list of CaseRange's
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002241unsigned SelectionDAGLowering::Clusterify(CaseVector& Cases,
2242 const SwitchInst& SI) {
2243 unsigned numCmps = 0;
2244
2245 // Start with "simple" cases
2246 for (unsigned i = 1; i < SI.getNumSuccessors(); ++i) {
2247 MachineBasicBlock *SMBB = FuncInfo.MBBMap[SI.getSuccessor(i)];
2248 Cases.push_back(Case(SI.getSuccessorValue(i),
2249 SI.getSuccessorValue(i),
2250 SMBB));
2251 }
Chris Lattnerb3d9cdb2007-11-27 06:14:32 +00002252 std::sort(Cases.begin(), Cases.end(), CaseCmp());
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002253
2254 // Merge case into clusters
2255 if (Cases.size()>=2)
David Greenea2a48852007-06-29 03:42:23 +00002256 // Must recompute end() each iteration because it may be
2257 // invalidated by erase if we hold on to it
Chris Lattner27a6c732007-11-24 07:07:01 +00002258 for (CaseItr I=Cases.begin(), J=++(Cases.begin()); J!=Cases.end(); ) {
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002259 int64_t nextValue = cast<ConstantInt>(J->Low)->getSExtValue();
2260 int64_t currentValue = cast<ConstantInt>(I->High)->getSExtValue();
2261 MachineBasicBlock* nextBB = J->BB;
2262 MachineBasicBlock* currentBB = I->BB;
2263
2264 // If the two neighboring cases go to the same destination, merge them
2265 // into a single case.
2266 if ((nextValue-currentValue==1) && (currentBB == nextBB)) {
2267 I->High = J->High;
2268 J = Cases.erase(J);
2269 } else {
2270 I = J++;
2271 }
2272 }
2273
2274 for (CaseItr I=Cases.begin(), E=Cases.end(); I!=E; ++I, ++numCmps) {
2275 if (I->Low != I->High)
2276 // A range counts double, since it requires two compares.
2277 ++numCmps;
2278 }
2279
2280 return numCmps;
2281}
2282
2283void SelectionDAGLowering::visitSwitch(SwitchInst &SI) {
Nate Begemanf15485a2006-03-27 01:32:24 +00002284 // Figure out which block is immediately after the current one.
2285 MachineBasicBlock *NextBlock = 0;
2286 MachineFunction::iterator BBI = CurMBB;
Bill Wendlingc70ddad2006-10-19 21:46:38 +00002287
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002288 MachineBasicBlock *Default = FuncInfo.MBBMap[SI.getDefaultDest()];
Chris Lattnerd2c1d222006-10-22 21:36:53 +00002289
Nate Begemanf15485a2006-03-27 01:32:24 +00002290 // If there is only the default destination, branch to it if it is not the
2291 // next basic block. Otherwise, just fall through.
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002292 if (SI.getNumOperands() == 2) {
Nate Begemanf15485a2006-03-27 01:32:24 +00002293 // Update machine-CFG edges.
Bill Wendlingc70ddad2006-10-19 21:46:38 +00002294
Nate Begemanf15485a2006-03-27 01:32:24 +00002295 // If this is not a fall-through branch, emit the branch.
Owen Anderson2d389e82008-06-07 00:00:23 +00002296 CurMBB->addSuccessor(Default);
Chris Lattnerd2c1d222006-10-22 21:36:53 +00002297 if (Default != NextBlock)
Dan Gohman86e1ebf2008-03-27 19:56:19 +00002298 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getControlRoot(),
Chris Lattnerd2c1d222006-10-22 21:36:53 +00002299 DAG.getBasicBlock(Default)));
Owen Anderson2d389e82008-06-07 00:00:23 +00002300
Nate Begemanf15485a2006-03-27 01:32:24 +00002301 return;
2302 }
2303
2304 // If there are any non-default case statements, create a vector of Cases
2305 // representing each one, and sort the vector so that we can efficiently
2306 // create a binary search tree from them.
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002307 CaseVector Cases;
2308 unsigned numCmps = Clusterify(Cases, SI);
2309 DOUT << "Clusterify finished. Total clusters: " << Cases.size()
2310 << ". Total compares: " << numCmps << "\n";
Bill Wendlingc70ddad2006-10-19 21:46:38 +00002311
Nate Begemanf15485a2006-03-27 01:32:24 +00002312 // Get the Value to be switched on and default basic blocks, which will be
2313 // inserted into CaseBlock records, representing basic blocks in the binary
2314 // search tree.
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002315 Value *SV = SI.getOperand(0);
Nate Begeman37efe672006-04-22 18:53:45 +00002316
Nate Begemanf15485a2006-03-27 01:32:24 +00002317 // Push the initial CaseRec onto the worklist
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00002318 CaseRecVector WorkList;
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00002319 WorkList.push_back(CaseRec(CurMBB,0,0,CaseRange(Cases.begin(),Cases.end())));
2320
2321 while (!WorkList.empty()) {
Nate Begemanf15485a2006-03-27 01:32:24 +00002322 // Grab a record representing a case range to process off the worklist
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00002323 CaseRec CR = WorkList.back();
2324 WorkList.pop_back();
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00002325
Anton Korobeynikov4198c582007-04-09 12:31:58 +00002326 if (handleBitTestsSwitchCase(CR, WorkList, SV, Default))
2327 continue;
2328
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00002329 // If the range has few cases (two or less) emit a series of specific
2330 // tests.
Anton Korobeynikovdd433212007-03-27 12:05:48 +00002331 if (handleSmallSwitchRange(CR, WorkList, SV, Default))
2332 continue;
2333
Anton Korobeynikov4198c582007-04-09 12:31:58 +00002334 // If the switch has more than 5 blocks, and at least 40% dense, and the
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00002335 // target supports indirect branches, then emit a jump table rather than
2336 // lowering the switch to a binary tree of conditional branches.
Anton Korobeynikovdd433212007-03-27 12:05:48 +00002337 if (handleJTSwitchCase(CR, WorkList, SV, Default))
2338 continue;
2339
2340 // Emit binary tree. We need to pick a pivot, and push left and right ranges
2341 // onto the worklist. Leafs are handled via handleSmallSwitchRange() call.
2342 handleBTSplitSwitchCase(CR, WorkList, SV, Default);
Nate Begemanf15485a2006-03-27 01:32:24 +00002343 }
2344}
2345
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00002346
Chris Lattnerb9fccc42005-04-02 05:04:50 +00002347void SelectionDAGLowering::visitSub(User &I) {
2348 // -0.0 - X --> fneg
Reid Spencer24d6da52007-01-21 00:29:26 +00002349 const Type *Ty = I.getType();
Reid Spencer9d6565a2007-02-15 02:26:10 +00002350 if (isa<VectorType>(Ty)) {
Dan Gohman7f321562007-06-25 16:23:39 +00002351 if (ConstantVector *CV = dyn_cast<ConstantVector>(I.getOperand(0))) {
2352 const VectorType *DestTy = cast<VectorType>(I.getType());
2353 const Type *ElTy = DestTy->getElementType();
Evan Chengc45453f2007-06-29 21:44:35 +00002354 if (ElTy->isFloatingPoint()) {
2355 unsigned VL = DestTy->getNumElements();
Dale Johannesen9e3d3ab2007-09-14 22:26:36 +00002356 std::vector<Constant*> NZ(VL, ConstantFP::getNegativeZero(ElTy));
Evan Chengc45453f2007-06-29 21:44:35 +00002357 Constant *CNZ = ConstantVector::get(&NZ[0], NZ.size());
2358 if (CV == CNZ) {
2359 SDOperand Op2 = getValue(I.getOperand(1));
2360 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
2361 return;
2362 }
Dan Gohman7f321562007-06-25 16:23:39 +00002363 }
2364 }
2365 }
2366 if (Ty->isFloatingPoint()) {
Chris Lattner01b3d732005-09-28 22:28:18 +00002367 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
Dale Johannesen9e3d3ab2007-09-14 22:26:36 +00002368 if (CFP->isExactlyValue(ConstantFP::getNegativeZero(Ty)->getValueAPF())) {
Chris Lattner01b3d732005-09-28 22:28:18 +00002369 SDOperand Op2 = getValue(I.getOperand(1));
2370 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
2371 return;
2372 }
Dan Gohman7f321562007-06-25 16:23:39 +00002373 }
2374
2375 visitBinary(I, Ty->isFPOrFPVector() ? ISD::FSUB : ISD::SUB);
Chris Lattnerb9fccc42005-04-02 05:04:50 +00002376}
2377
Dan Gohman7f321562007-06-25 16:23:39 +00002378void SelectionDAGLowering::visitBinary(User &I, unsigned OpCode) {
Chris Lattner1c08c712005-01-07 07:47:53 +00002379 SDOperand Op1 = getValue(I.getOperand(0));
2380 SDOperand Op2 = getValue(I.getOperand(1));
Reid Spencer24d6da52007-01-21 00:29:26 +00002381
2382 setValue(&I, DAG.getNode(OpCode, Op1.getValueType(), Op1, Op2));
Reid Spencer1628cec2006-10-26 06:15:43 +00002383}
2384
Nate Begemane21ea612005-11-18 07:42:56 +00002385void SelectionDAGLowering::visitShift(User &I, unsigned Opcode) {
2386 SDOperand Op1 = getValue(I.getOperand(0));
2387 SDOperand Op2 = getValue(I.getOperand(1));
2388
Duncan Sands8e4eb092008-06-08 20:54:56 +00002389 if (TLI.getShiftAmountTy().bitsLT(Op2.getValueType()))
Reid Spencer832254e2007-02-02 02:16:23 +00002390 Op2 = DAG.getNode(ISD::TRUNCATE, TLI.getShiftAmountTy(), Op2);
Duncan Sands8e4eb092008-06-08 20:54:56 +00002391 else if (TLI.getShiftAmountTy().bitsGT(Op2.getValueType()))
Reid Spencer832254e2007-02-02 02:16:23 +00002392 Op2 = DAG.getNode(ISD::ANY_EXTEND, TLI.getShiftAmountTy(), Op2);
Nate Begemane21ea612005-11-18 07:42:56 +00002393
Chris Lattner1c08c712005-01-07 07:47:53 +00002394 setValue(&I, DAG.getNode(Opcode, Op1.getValueType(), Op1, Op2));
2395}
2396
Reid Spencer45fb3f32006-11-20 01:22:35 +00002397void SelectionDAGLowering::visitICmp(User &I) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002398 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
2399 if (ICmpInst *IC = dyn_cast<ICmpInst>(&I))
2400 predicate = IC->getPredicate();
2401 else if (ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
2402 predicate = ICmpInst::Predicate(IC->getPredicate());
2403 SDOperand Op1 = getValue(I.getOperand(0));
2404 SDOperand Op2 = getValue(I.getOperand(1));
Reid Spencer45fb3f32006-11-20 01:22:35 +00002405 ISD::CondCode Opcode;
Reid Spencere4d87aa2006-12-23 06:05:41 +00002406 switch (predicate) {
Reid Spencer45fb3f32006-11-20 01:22:35 +00002407 case ICmpInst::ICMP_EQ : Opcode = ISD::SETEQ; break;
2408 case ICmpInst::ICMP_NE : Opcode = ISD::SETNE; break;
2409 case ICmpInst::ICMP_UGT : Opcode = ISD::SETUGT; break;
2410 case ICmpInst::ICMP_UGE : Opcode = ISD::SETUGE; break;
2411 case ICmpInst::ICMP_ULT : Opcode = ISD::SETULT; break;
2412 case ICmpInst::ICMP_ULE : Opcode = ISD::SETULE; break;
2413 case ICmpInst::ICMP_SGT : Opcode = ISD::SETGT; break;
2414 case ICmpInst::ICMP_SGE : Opcode = ISD::SETGE; break;
2415 case ICmpInst::ICMP_SLT : Opcode = ISD::SETLT; break;
2416 case ICmpInst::ICMP_SLE : Opcode = ISD::SETLE; break;
2417 default:
2418 assert(!"Invalid ICmp predicate value");
2419 Opcode = ISD::SETEQ;
2420 break;
2421 }
2422 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Opcode));
2423}
2424
2425void SelectionDAGLowering::visitFCmp(User &I) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002426 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
2427 if (FCmpInst *FC = dyn_cast<FCmpInst>(&I))
2428 predicate = FC->getPredicate();
2429 else if (ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
2430 predicate = FCmpInst::Predicate(FC->getPredicate());
Chris Lattner1c08c712005-01-07 07:47:53 +00002431 SDOperand Op1 = getValue(I.getOperand(0));
2432 SDOperand Op2 = getValue(I.getOperand(1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00002433 ISD::CondCode Condition, FOC, FPC;
2434 switch (predicate) {
2435 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
2436 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
2437 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
2438 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
2439 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
2440 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
2441 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
Dan Gohmancba3b442008-05-01 23:40:44 +00002442 case FCmpInst::FCMP_ORD: FOC = FPC = ISD::SETO; break;
2443 case FCmpInst::FCMP_UNO: FOC = FPC = ISD::SETUO; break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00002444 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
2445 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
2446 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
2447 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
2448 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
2449 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
2450 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
2451 default:
2452 assert(!"Invalid FCmp predicate value");
2453 FOC = FPC = ISD::SETFALSE;
2454 break;
2455 }
2456 if (FiniteOnlyFPMath())
2457 Condition = FOC;
2458 else
2459 Condition = FPC;
2460 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Condition));
Chris Lattner1c08c712005-01-07 07:47:53 +00002461}
2462
Nate Begemanb43e9c12008-05-12 19:40:03 +00002463void SelectionDAGLowering::visitVICmp(User &I) {
2464 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
2465 if (VICmpInst *IC = dyn_cast<VICmpInst>(&I))
2466 predicate = IC->getPredicate();
2467 else if (ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
2468 predicate = ICmpInst::Predicate(IC->getPredicate());
2469 SDOperand Op1 = getValue(I.getOperand(0));
2470 SDOperand Op2 = getValue(I.getOperand(1));
2471 ISD::CondCode Opcode;
2472 switch (predicate) {
2473 case ICmpInst::ICMP_EQ : Opcode = ISD::SETEQ; break;
2474 case ICmpInst::ICMP_NE : Opcode = ISD::SETNE; break;
2475 case ICmpInst::ICMP_UGT : Opcode = ISD::SETUGT; break;
2476 case ICmpInst::ICMP_UGE : Opcode = ISD::SETUGE; break;
2477 case ICmpInst::ICMP_ULT : Opcode = ISD::SETULT; break;
2478 case ICmpInst::ICMP_ULE : Opcode = ISD::SETULE; break;
2479 case ICmpInst::ICMP_SGT : Opcode = ISD::SETGT; break;
2480 case ICmpInst::ICMP_SGE : Opcode = ISD::SETGE; break;
2481 case ICmpInst::ICMP_SLT : Opcode = ISD::SETLT; break;
2482 case ICmpInst::ICMP_SLE : Opcode = ISD::SETLE; break;
2483 default:
2484 assert(!"Invalid ICmp predicate value");
2485 Opcode = ISD::SETEQ;
2486 break;
2487 }
2488 setValue(&I, DAG.getVSetCC(Op1.getValueType(), Op1, Op2, Opcode));
2489}
2490
2491void SelectionDAGLowering::visitVFCmp(User &I) {
2492 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
2493 if (VFCmpInst *FC = dyn_cast<VFCmpInst>(&I))
2494 predicate = FC->getPredicate();
2495 else if (ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
2496 predicate = FCmpInst::Predicate(FC->getPredicate());
2497 SDOperand Op1 = getValue(I.getOperand(0));
2498 SDOperand Op2 = getValue(I.getOperand(1));
2499 ISD::CondCode Condition, FOC, FPC;
2500 switch (predicate) {
2501 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
2502 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
2503 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
2504 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
2505 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
2506 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
2507 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
2508 case FCmpInst::FCMP_ORD: FOC = FPC = ISD::SETO; break;
2509 case FCmpInst::FCMP_UNO: FOC = FPC = ISD::SETUO; break;
2510 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
2511 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
2512 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
2513 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
2514 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
2515 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
2516 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
2517 default:
2518 assert(!"Invalid VFCmp predicate value");
2519 FOC = FPC = ISD::SETFALSE;
2520 break;
2521 }
2522 if (FiniteOnlyFPMath())
2523 Condition = FOC;
2524 else
2525 Condition = FPC;
2526
Duncan Sands83ec4b62008-06-06 12:08:01 +00002527 MVT DestVT = TLI.getValueType(I.getType());
Nate Begemanb43e9c12008-05-12 19:40:03 +00002528
2529 setValue(&I, DAG.getVSetCC(DestVT, Op1, Op2, Condition));
2530}
2531
Chris Lattner1c08c712005-01-07 07:47:53 +00002532void SelectionDAGLowering::visitSelect(User &I) {
2533 SDOperand Cond = getValue(I.getOperand(0));
2534 SDOperand TrueVal = getValue(I.getOperand(1));
2535 SDOperand FalseVal = getValue(I.getOperand(2));
Dan Gohman7f321562007-06-25 16:23:39 +00002536 setValue(&I, DAG.getNode(ISD::SELECT, TrueVal.getValueType(), Cond,
2537 TrueVal, FalseVal));
Chris Lattner1c08c712005-01-07 07:47:53 +00002538}
2539
Reid Spencer3da59db2006-11-27 01:05:10 +00002540
2541void SelectionDAGLowering::visitTrunc(User &I) {
2542 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
2543 SDOperand N = getValue(I.getOperand(0));
Duncan Sands83ec4b62008-06-06 12:08:01 +00002544 MVT DestVT = TLI.getValueType(I.getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00002545 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
2546}
2547
2548void SelectionDAGLowering::visitZExt(User &I) {
2549 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2550 // ZExt also can't be a cast to bool for same reason. So, nothing much to do
2551 SDOperand N = getValue(I.getOperand(0));
Duncan Sands83ec4b62008-06-06 12:08:01 +00002552 MVT DestVT = TLI.getValueType(I.getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00002553 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
2554}
2555
2556void SelectionDAGLowering::visitSExt(User &I) {
2557 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2558 // SExt also can't be a cast to bool for same reason. So, nothing much to do
2559 SDOperand N = getValue(I.getOperand(0));
Duncan Sands83ec4b62008-06-06 12:08:01 +00002560 MVT DestVT = TLI.getValueType(I.getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00002561 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, DestVT, N));
2562}
2563
2564void SelectionDAGLowering::visitFPTrunc(User &I) {
2565 // FPTrunc is never a no-op cast, no need to check
2566 SDOperand N = getValue(I.getOperand(0));
Duncan Sands83ec4b62008-06-06 12:08:01 +00002567 MVT DestVT = TLI.getValueType(I.getType());
Chris Lattner0bd48932008-01-17 07:00:52 +00002568 setValue(&I, DAG.getNode(ISD::FP_ROUND, DestVT, N, DAG.getIntPtrConstant(0)));
Reid Spencer3da59db2006-11-27 01:05:10 +00002569}
2570
2571void SelectionDAGLowering::visitFPExt(User &I){
2572 // FPTrunc is never a no-op cast, no need to check
2573 SDOperand N = getValue(I.getOperand(0));
Duncan Sands83ec4b62008-06-06 12:08:01 +00002574 MVT DestVT = TLI.getValueType(I.getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00002575 setValue(&I, DAG.getNode(ISD::FP_EXTEND, DestVT, N));
2576}
2577
2578void SelectionDAGLowering::visitFPToUI(User &I) {
2579 // FPToUI is never a no-op cast, no need to check
2580 SDOperand N = getValue(I.getOperand(0));
Duncan Sands83ec4b62008-06-06 12:08:01 +00002581 MVT DestVT = TLI.getValueType(I.getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00002582 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, DestVT, N));
2583}
2584
2585void SelectionDAGLowering::visitFPToSI(User &I) {
2586 // FPToSI is never a no-op cast, no need to check
2587 SDOperand N = getValue(I.getOperand(0));
Duncan Sands83ec4b62008-06-06 12:08:01 +00002588 MVT DestVT = TLI.getValueType(I.getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00002589 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, DestVT, N));
2590}
2591
2592void SelectionDAGLowering::visitUIToFP(User &I) {
2593 // UIToFP is never a no-op cast, no need to check
2594 SDOperand N = getValue(I.getOperand(0));
Duncan Sands83ec4b62008-06-06 12:08:01 +00002595 MVT DestVT = TLI.getValueType(I.getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00002596 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, DestVT, N));
2597}
2598
2599void SelectionDAGLowering::visitSIToFP(User &I){
2600 // UIToFP is never a no-op cast, no need to check
2601 SDOperand N = getValue(I.getOperand(0));
Duncan Sands83ec4b62008-06-06 12:08:01 +00002602 MVT DestVT = TLI.getValueType(I.getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00002603 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, DestVT, N));
2604}
2605
2606void SelectionDAGLowering::visitPtrToInt(User &I) {
2607 // What to do depends on the size of the integer and the size of the pointer.
2608 // We can either truncate, zero extend, or no-op, accordingly.
Chris Lattner1c08c712005-01-07 07:47:53 +00002609 SDOperand N = getValue(I.getOperand(0));
Duncan Sands83ec4b62008-06-06 12:08:01 +00002610 MVT SrcVT = N.getValueType();
2611 MVT DestVT = TLI.getValueType(I.getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00002612 SDOperand Result;
Duncan Sands8e4eb092008-06-08 20:54:56 +00002613 if (DestVT.bitsLT(SrcVT))
Reid Spencer3da59db2006-11-27 01:05:10 +00002614 Result = DAG.getNode(ISD::TRUNCATE, DestVT, N);
2615 else
2616 // Note: ZERO_EXTEND can handle cases where the sizes are equal too
2617 Result = DAG.getNode(ISD::ZERO_EXTEND, DestVT, N);
2618 setValue(&I, Result);
2619}
Chris Lattner1c08c712005-01-07 07:47:53 +00002620
Reid Spencer3da59db2006-11-27 01:05:10 +00002621void SelectionDAGLowering::visitIntToPtr(User &I) {
2622 // What to do depends on the size of the integer and the size of the pointer.
2623 // We can either truncate, zero extend, or no-op, accordingly.
2624 SDOperand N = getValue(I.getOperand(0));
Duncan Sands83ec4b62008-06-06 12:08:01 +00002625 MVT SrcVT = N.getValueType();
2626 MVT DestVT = TLI.getValueType(I.getType());
Duncan Sands8e4eb092008-06-08 20:54:56 +00002627 if (DestVT.bitsLT(SrcVT))
Reid Spencer3da59db2006-11-27 01:05:10 +00002628 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
2629 else
2630 // Note: ZERO_EXTEND can handle cases where the sizes are equal too
2631 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
2632}
2633
2634void SelectionDAGLowering::visitBitCast(User &I) {
2635 SDOperand N = getValue(I.getOperand(0));
Duncan Sands83ec4b62008-06-06 12:08:01 +00002636 MVT DestVT = TLI.getValueType(I.getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00002637
2638 // BitCast assures us that source and destination are the same size so this
2639 // is either a BIT_CONVERT or a no-op.
2640 if (DestVT != N.getValueType())
2641 setValue(&I, DAG.getNode(ISD::BIT_CONVERT, DestVT, N)); // convert types
2642 else
2643 setValue(&I, N); // noop cast.
Chris Lattner1c08c712005-01-07 07:47:53 +00002644}
2645
Chris Lattner2bbd8102006-03-29 00:11:43 +00002646void SelectionDAGLowering::visitInsertElement(User &I) {
Chris Lattnerc7029802006-03-18 01:44:44 +00002647 SDOperand InVec = getValue(I.getOperand(0));
2648 SDOperand InVal = getValue(I.getOperand(1));
2649 SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
2650 getValue(I.getOperand(2)));
2651
Dan Gohman7f321562007-06-25 16:23:39 +00002652 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT,
2653 TLI.getValueType(I.getType()),
2654 InVec, InVal, InIdx));
Chris Lattnerc7029802006-03-18 01:44:44 +00002655}
2656
Chris Lattner2bbd8102006-03-29 00:11:43 +00002657void SelectionDAGLowering::visitExtractElement(User &I) {
Chris Lattner384504c2006-03-21 20:44:12 +00002658 SDOperand InVec = getValue(I.getOperand(0));
2659 SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
2660 getValue(I.getOperand(1)));
Dan Gohman7f321562007-06-25 16:23:39 +00002661 setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
Chris Lattner384504c2006-03-21 20:44:12 +00002662 TLI.getValueType(I.getType()), InVec, InIdx));
2663}
Chris Lattnerc7029802006-03-18 01:44:44 +00002664
Chris Lattner3e104b12006-04-08 04:15:24 +00002665void SelectionDAGLowering::visitShuffleVector(User &I) {
2666 SDOperand V1 = getValue(I.getOperand(0));
2667 SDOperand V2 = getValue(I.getOperand(1));
2668 SDOperand Mask = getValue(I.getOperand(2));
2669
Dan Gohman7f321562007-06-25 16:23:39 +00002670 setValue(&I, DAG.getNode(ISD::VECTOR_SHUFFLE,
2671 TLI.getValueType(I.getType()),
2672 V1, V2, Mask));
Chris Lattner3e104b12006-04-08 04:15:24 +00002673}
2674
Dan Gohman1d685a42008-06-07 02:02:36 +00002675void SelectionDAGLowering::visitInsertValue(InsertValueInst &I) {
2676 const Value *Op0 = I.getOperand(0);
2677 const Value *Op1 = I.getOperand(1);
2678 const Type *AggTy = I.getType();
2679 const Type *ValTy = Op1->getType();
2680 bool IntoUndef = isa<UndefValue>(Op0);
2681 bool FromUndef = isa<UndefValue>(Op1);
2682
2683 unsigned LinearIndex = ComputeLinearIndex(TLI, AggTy,
2684 I.idx_begin(), I.idx_end());
2685
2686 SmallVector<MVT, 4> AggValueVTs;
2687 ComputeValueVTs(TLI, AggTy, AggValueVTs);
2688 SmallVector<MVT, 4> ValValueVTs;
2689 ComputeValueVTs(TLI, ValTy, ValValueVTs);
2690
2691 unsigned NumAggValues = AggValueVTs.size();
2692 unsigned NumValValues = ValValueVTs.size();
2693 SmallVector<SDOperand, 4> Values(NumAggValues);
2694
2695 SDOperand Agg = getValue(Op0);
2696 SDOperand Val = getValue(Op1);
2697 unsigned i = 0;
2698 // Copy the beginning value(s) from the original aggregate.
2699 for (; i != LinearIndex; ++i)
2700 Values[i] = IntoUndef ? DAG.getNode(ISD::UNDEF, AggValueVTs[i]) :
2701 SDOperand(Agg.Val, Agg.ResNo + i);
2702 // Copy values from the inserted value(s).
2703 for (; i != LinearIndex + NumValValues; ++i)
2704 Values[i] = FromUndef ? DAG.getNode(ISD::UNDEF, AggValueVTs[i]) :
2705 SDOperand(Val.Val, Val.ResNo + i - LinearIndex);
2706 // Copy remaining value(s) from the original aggregate.
2707 for (; i != NumAggValues; ++i)
2708 Values[i] = IntoUndef ? DAG.getNode(ISD::UNDEF, AggValueVTs[i]) :
2709 SDOperand(Agg.Val, Agg.ResNo + i);
2710
2711 setValue(&I, DAG.getNode(ISD::MERGE_VALUES,
2712 DAG.getVTList(&AggValueVTs[0], NumAggValues),
2713 &Values[0], NumAggValues));
Dan Gohman041e2eb2008-05-15 19:50:34 +00002714}
2715
Dan Gohman1d685a42008-06-07 02:02:36 +00002716void SelectionDAGLowering::visitExtractValue(ExtractValueInst &I) {
2717 const Value *Op0 = I.getOperand(0);
2718 const Type *AggTy = Op0->getType();
2719 const Type *ValTy = I.getType();
2720 bool OutOfUndef = isa<UndefValue>(Op0);
2721
2722 unsigned LinearIndex = ComputeLinearIndex(TLI, AggTy,
2723 I.idx_begin(), I.idx_end());
2724
2725 SmallVector<MVT, 4> ValValueVTs;
2726 ComputeValueVTs(TLI, ValTy, ValValueVTs);
2727
2728 unsigned NumValValues = ValValueVTs.size();
2729 SmallVector<SDOperand, 4> Values(NumValValues);
2730
2731 SDOperand Agg = getValue(Op0);
2732 // Copy out the selected value(s).
2733 for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
2734 Values[i - LinearIndex] =
2735 OutOfUndef ? DAG.getNode(ISD::UNDEF, Agg.Val->getValueType(i)) :
2736 SDOperand(Agg.Val, Agg.ResNo + i - LinearIndex);
2737
2738 setValue(&I, DAG.getNode(ISD::MERGE_VALUES,
2739 DAG.getVTList(&ValValueVTs[0], NumValValues),
2740 &Values[0], NumValValues));
Dan Gohman041e2eb2008-05-15 19:50:34 +00002741}
2742
Chris Lattner3e104b12006-04-08 04:15:24 +00002743
Chris Lattner1c08c712005-01-07 07:47:53 +00002744void SelectionDAGLowering::visitGetElementPtr(User &I) {
2745 SDOperand N = getValue(I.getOperand(0));
2746 const Type *Ty = I.getOperand(0)->getType();
Chris Lattner1c08c712005-01-07 07:47:53 +00002747
2748 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
2749 OI != E; ++OI) {
2750 Value *Idx = *OI;
Chris Lattnerc88d8e92005-12-05 07:10:48 +00002751 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002752 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
Chris Lattner1c08c712005-01-07 07:47:53 +00002753 if (Field) {
2754 // N = N + Offset
Chris Lattnerb1919e22007-02-10 19:55:17 +00002755 uint64_t Offset = TD->getStructLayout(StTy)->getElementOffset(Field);
Chris Lattner1c08c712005-01-07 07:47:53 +00002756 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
Chris Lattner0bd48932008-01-17 07:00:52 +00002757 DAG.getIntPtrConstant(Offset));
Chris Lattner1c08c712005-01-07 07:47:53 +00002758 }
2759 Ty = StTy->getElementType(Field);
2760 } else {
2761 Ty = cast<SequentialType>(Ty)->getElementType();
Chris Lattner7cc47772005-01-07 21:56:57 +00002762
Chris Lattner7c0104b2005-11-09 04:45:33 +00002763 // If this is a constant subscript, handle it quickly.
2764 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002765 if (CI->getZExtValue() == 0) continue;
Reid Spencer47857812006-12-31 05:55:36 +00002766 uint64_t Offs =
Dale Johannesena7ac2bd2007-10-01 23:08:35 +00002767 TD->getABITypeSize(Ty)*cast<ConstantInt>(CI)->getSExtValue();
Chris Lattner0bd48932008-01-17 07:00:52 +00002768 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
2769 DAG.getIntPtrConstant(Offs));
Chris Lattner7c0104b2005-11-09 04:45:33 +00002770 continue;
Chris Lattner1c08c712005-01-07 07:47:53 +00002771 }
Chris Lattner7c0104b2005-11-09 04:45:33 +00002772
2773 // N = N + Idx * ElementSize;
Dale Johannesena7ac2bd2007-10-01 23:08:35 +00002774 uint64_t ElementSize = TD->getABITypeSize(Ty);
Chris Lattner7c0104b2005-11-09 04:45:33 +00002775 SDOperand IdxN = getValue(Idx);
2776
2777 // If the index is smaller or larger than intptr_t, truncate or extend
2778 // it.
Duncan Sands8e4eb092008-06-08 20:54:56 +00002779 if (IdxN.getValueType().bitsLT(N.getValueType())) {
Reid Spencer47857812006-12-31 05:55:36 +00002780 IdxN = DAG.getNode(ISD::SIGN_EXTEND, N.getValueType(), IdxN);
Duncan Sands8e4eb092008-06-08 20:54:56 +00002781 } else if (IdxN.getValueType().bitsGT(N.getValueType()))
Chris Lattner7c0104b2005-11-09 04:45:33 +00002782 IdxN = DAG.getNode(ISD::TRUNCATE, N.getValueType(), IdxN);
2783
2784 // If this is a multiply by a power of two, turn it into a shl
2785 // immediately. This is a very common case.
2786 if (isPowerOf2_64(ElementSize)) {
2787 unsigned Amt = Log2_64(ElementSize);
2788 IdxN = DAG.getNode(ISD::SHL, N.getValueType(), IdxN,
Chris Lattner6b2d6962005-11-09 16:50:40 +00002789 DAG.getConstant(Amt, TLI.getShiftAmountTy()));
Chris Lattner7c0104b2005-11-09 04:45:33 +00002790 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
2791 continue;
2792 }
2793
Chris Lattner0bd48932008-01-17 07:00:52 +00002794 SDOperand Scale = DAG.getIntPtrConstant(ElementSize);
Chris Lattner7c0104b2005-11-09 04:45:33 +00002795 IdxN = DAG.getNode(ISD::MUL, N.getValueType(), IdxN, Scale);
2796 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
Chris Lattner1c08c712005-01-07 07:47:53 +00002797 }
2798 }
2799 setValue(&I, N);
2800}
2801
2802void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
2803 // If this is a fixed sized alloca in the entry block of the function,
2804 // allocate it statically on the stack.
2805 if (FuncInfo.StaticAllocaMap.count(&I))
2806 return; // getValue will auto-populate this.
2807
2808 const Type *Ty = I.getAllocatedType();
Duncan Sands514ab342007-11-01 20:53:16 +00002809 uint64_t TySize = TLI.getTargetData()->getABITypeSize(Ty);
Chris Lattner58092e32007-01-20 22:35:55 +00002810 unsigned Align =
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00002811 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
Chris Lattner58092e32007-01-20 22:35:55 +00002812 I.getAlignment());
Chris Lattner1c08c712005-01-07 07:47:53 +00002813
2814 SDOperand AllocSize = getValue(I.getArraySize());
Duncan Sands83ec4b62008-06-06 12:08:01 +00002815 MVT IntPtr = TLI.getPointerTy();
Duncan Sands8e4eb092008-06-08 20:54:56 +00002816 if (IntPtr.bitsLT(AllocSize.getValueType()))
Chris Lattner68cd65e2005-01-22 23:04:37 +00002817 AllocSize = DAG.getNode(ISD::TRUNCATE, IntPtr, AllocSize);
Duncan Sands8e4eb092008-06-08 20:54:56 +00002818 else if (IntPtr.bitsGT(AllocSize.getValueType()))
Chris Lattner68cd65e2005-01-22 23:04:37 +00002819 AllocSize = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, AllocSize);
Chris Lattner1c08c712005-01-07 07:47:53 +00002820
Chris Lattner68cd65e2005-01-22 23:04:37 +00002821 AllocSize = DAG.getNode(ISD::MUL, IntPtr, AllocSize,
Chris Lattner0bd48932008-01-17 07:00:52 +00002822 DAG.getIntPtrConstant(TySize));
Chris Lattner1c08c712005-01-07 07:47:53 +00002823
Evan Cheng45157792007-08-16 23:46:29 +00002824 // Handle alignment. If the requested alignment is less than or equal to
2825 // the stack alignment, ignore it. If the size is greater than or equal to
2826 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
Chris Lattner1c08c712005-01-07 07:47:53 +00002827 unsigned StackAlign =
2828 TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
Evan Cheng45157792007-08-16 23:46:29 +00002829 if (Align <= StackAlign)
Chris Lattner1c08c712005-01-07 07:47:53 +00002830 Align = 0;
Evan Cheng45157792007-08-16 23:46:29 +00002831
2832 // Round the size of the allocation up to the stack alignment size
2833 // by add SA-1 to the size.
2834 AllocSize = DAG.getNode(ISD::ADD, AllocSize.getValueType(), AllocSize,
Chris Lattner0bd48932008-01-17 07:00:52 +00002835 DAG.getIntPtrConstant(StackAlign-1));
Evan Cheng45157792007-08-16 23:46:29 +00002836 // Mask out the low bits for alignment purposes.
2837 AllocSize = DAG.getNode(ISD::AND, AllocSize.getValueType(), AllocSize,
Chris Lattner0bd48932008-01-17 07:00:52 +00002838 DAG.getIntPtrConstant(~(uint64_t)(StackAlign-1)));
Chris Lattner1c08c712005-01-07 07:47:53 +00002839
Chris Lattner0bd48932008-01-17 07:00:52 +00002840 SDOperand Ops[] = { getRoot(), AllocSize, DAG.getIntPtrConstant(Align) };
Duncan Sands83ec4b62008-06-06 12:08:01 +00002841 const MVT *VTs = DAG.getNodeValueTypes(AllocSize.getValueType(),
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00002842 MVT::Other);
2843 SDOperand DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, VTs, 2, Ops, 3);
Chris Lattner0da331f2007-02-04 01:31:47 +00002844 setValue(&I, DSA);
2845 DAG.setRoot(DSA.getValue(1));
Chris Lattner1c08c712005-01-07 07:47:53 +00002846
2847 // Inform the Frame Information that we have just allocated a variable-sized
2848 // object.
2849 CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
2850}
2851
Chris Lattner1c08c712005-01-07 07:47:53 +00002852void SelectionDAGLowering::visitLoad(LoadInst &I) {
Dan Gohman8a6ccb52008-06-09 15:21:47 +00002853 const Value *SV = I.getOperand(0);
2854 SDOperand Ptr = getValue(SV);
2855
2856 const Type *Ty = I.getType();
2857 bool isVolatile = I.isVolatile();
2858 unsigned Alignment = I.getAlignment();
2859
2860 SmallVector<MVT, 4> ValueVTs;
2861 SmallVector<uint64_t, 4> Offsets;
2862 ComputeValueVTs(TLI, Ty, ValueVTs, &Offsets);
2863 unsigned NumValues = ValueVTs.size();
2864 if (NumValues == 0)
2865 return;
Misha Brukmanedf128a2005-04-21 22:36:52 +00002866
Chris Lattnerd3948112005-01-17 22:19:26 +00002867 SDOperand Root;
2868 if (I.isVolatile())
2869 Root = getRoot();
2870 else {
2871 // Do not serialize non-volatile loads against each other.
2872 Root = DAG.getRoot();
2873 }
Chris Lattner28b5b1c2006-03-15 22:19:46 +00002874
Dan Gohman1d685a42008-06-07 02:02:36 +00002875 SmallVector<SDOperand, 4> Values(NumValues);
2876 SmallVector<SDOperand, 4> Chains(NumValues);
2877 MVT PtrVT = Ptr.getValueType();
2878 for (unsigned i = 0; i != NumValues; ++i) {
2879 SDOperand L = DAG.getLoad(ValueVTs[i], Root,
2880 DAG.getNode(ISD::ADD, PtrVT, Ptr,
2881 DAG.getConstant(Offsets[i], PtrVT)),
2882 SV, Offsets[i],
2883 isVolatile, Alignment);
2884 Values[i] = L;
2885 Chains[i] = L.getValue(1);
2886 }
Chris Lattner28b5b1c2006-03-15 22:19:46 +00002887
Dan Gohman1d685a42008-06-07 02:02:36 +00002888 SDOperand Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
2889 &Chains[0], NumValues);
2890 if (isVolatile)
2891 DAG.setRoot(Chain);
2892 else
2893 PendingLoads.push_back(Chain);
2894
Dan Gohman8a6ccb52008-06-09 15:21:47 +00002895 setValue(&I, DAG.getNode(ISD::MERGE_VALUES,
2896 DAG.getVTList(&ValueVTs[0], NumValues),
2897 &Values[0], NumValues));
Chris Lattner1c08c712005-01-07 07:47:53 +00002898}
2899
2900
2901void SelectionDAGLowering::visitStore(StoreInst &I) {
2902 Value *SrcV = I.getOperand(0);
2903 SDOperand Src = getValue(SrcV);
Dan Gohman1d685a42008-06-07 02:02:36 +00002904 Value *PtrV = I.getOperand(1);
2905 SDOperand Ptr = getValue(PtrV);
2906
2907 SmallVector<MVT, 4> ValueVTs;
2908 SmallVector<uint64_t, 4> Offsets;
2909 ComputeValueVTs(TLI, SrcV->getType(), ValueVTs, &Offsets);
2910 unsigned NumValues = ValueVTs.size();
Dan Gohman8a6ccb52008-06-09 15:21:47 +00002911 if (NumValues == 0)
2912 return;
Dan Gohman1d685a42008-06-07 02:02:36 +00002913
2914 SDOperand Root = getRoot();
2915 SmallVector<SDOperand, 4> Chains(NumValues);
2916 MVT PtrVT = Ptr.getValueType();
2917 bool isVolatile = I.isVolatile();
2918 unsigned Alignment = I.getAlignment();
2919 for (unsigned i = 0; i != NumValues; ++i)
2920 Chains[i] = DAG.getStore(Root, SDOperand(Src.Val, Src.ResNo + i),
2921 DAG.getNode(ISD::ADD, PtrVT, Ptr,
2922 DAG.getConstant(Offsets[i], PtrVT)),
2923 PtrV, Offsets[i],
2924 isVolatile, Alignment);
2925
2926 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other, &Chains[0], NumValues));
Chris Lattner1c08c712005-01-07 07:47:53 +00002927}
2928
Chris Lattner0eade312006-03-24 02:22:33 +00002929/// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
2930/// node.
2931void SelectionDAGLowering::visitTargetIntrinsic(CallInst &I,
2932 unsigned Intrinsic) {
Duncan Sandsa3355ff2007-12-03 20:06:50 +00002933 bool HasChain = !I.doesNotAccessMemory();
2934 bool OnlyLoad = HasChain && I.onlyReadsMemory();
2935
Chris Lattner0eade312006-03-24 02:22:33 +00002936 // Build the operand list.
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002937 SmallVector<SDOperand, 8> Ops;
Chris Lattnere58a7802006-04-02 03:41:14 +00002938 if (HasChain) { // If this intrinsic has side-effects, chainify it.
2939 if (OnlyLoad) {
2940 // We don't need to serialize loads against other loads.
2941 Ops.push_back(DAG.getRoot());
2942 } else {
2943 Ops.push_back(getRoot());
2944 }
2945 }
Chris Lattner0eade312006-03-24 02:22:33 +00002946
2947 // Add the intrinsic ID as an integer operand.
2948 Ops.push_back(DAG.getConstant(Intrinsic, TLI.getPointerTy()));
2949
2950 // Add all operands of the call to the operand list.
2951 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
2952 SDOperand Op = getValue(I.getOperand(i));
Chris Lattner0eade312006-03-24 02:22:33 +00002953 assert(TLI.isTypeLegal(Op.getValueType()) &&
2954 "Intrinsic uses a non-legal type?");
2955 Ops.push_back(Op);
2956 }
2957
Duncan Sands83ec4b62008-06-06 12:08:01 +00002958 std::vector<MVT> VTs;
Chris Lattner0eade312006-03-24 02:22:33 +00002959 if (I.getType() != Type::VoidTy) {
Duncan Sands83ec4b62008-06-06 12:08:01 +00002960 MVT VT = TLI.getValueType(I.getType());
2961 if (VT.isVector()) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00002962 const VectorType *DestTy = cast<VectorType>(I.getType());
Duncan Sands83ec4b62008-06-06 12:08:01 +00002963 MVT EltVT = TLI.getValueType(DestTy->getElementType());
Chris Lattner0eade312006-03-24 02:22:33 +00002964
Duncan Sands83ec4b62008-06-06 12:08:01 +00002965 VT = MVT::getVectorVT(EltVT, DestTy->getNumElements());
Chris Lattner0eade312006-03-24 02:22:33 +00002966 assert(VT != MVT::Other && "Intrinsic uses a non-legal type?");
2967 }
2968
2969 assert(TLI.isTypeLegal(VT) && "Intrinsic uses a non-legal type?");
2970 VTs.push_back(VT);
2971 }
2972 if (HasChain)
2973 VTs.push_back(MVT::Other);
2974
Duncan Sands83ec4b62008-06-06 12:08:01 +00002975 const MVT *VTList = DAG.getNodeValueTypes(VTs);
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00002976
Chris Lattner0eade312006-03-24 02:22:33 +00002977 // Create the node.
Chris Lattner48b61a72006-03-28 00:40:33 +00002978 SDOperand Result;
2979 if (!HasChain)
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00002980 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VTList, VTs.size(),
2981 &Ops[0], Ops.size());
Chris Lattner48b61a72006-03-28 00:40:33 +00002982 else if (I.getType() != Type::VoidTy)
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00002983 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, VTList, VTs.size(),
2984 &Ops[0], Ops.size());
Chris Lattner48b61a72006-03-28 00:40:33 +00002985 else
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00002986 Result = DAG.getNode(ISD::INTRINSIC_VOID, VTList, VTs.size(),
2987 &Ops[0], Ops.size());
Chris Lattner48b61a72006-03-28 00:40:33 +00002988
Chris Lattnere58a7802006-04-02 03:41:14 +00002989 if (HasChain) {
2990 SDOperand Chain = Result.getValue(Result.Val->getNumValues()-1);
2991 if (OnlyLoad)
2992 PendingLoads.push_back(Chain);
2993 else
2994 DAG.setRoot(Chain);
2995 }
Chris Lattner0eade312006-03-24 02:22:33 +00002996 if (I.getType() != Type::VoidTy) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00002997 if (const VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
Duncan Sands83ec4b62008-06-06 12:08:01 +00002998 MVT VT = TLI.getValueType(PTy);
Dan Gohman7f321562007-06-25 16:23:39 +00002999 Result = DAG.getNode(ISD::BIT_CONVERT, VT, Result);
Chris Lattner0eade312006-03-24 02:22:33 +00003000 }
3001 setValue(&I, Result);
3002 }
3003}
3004
Duncan Sandsb4fd45e2007-07-06 09:10:03 +00003005/// ExtractTypeInfo - Returns the type info, possibly bitcast, encoded in V.
Duncan Sandscf26d7c2007-07-04 20:52:51 +00003006static GlobalVariable *ExtractTypeInfo (Value *V) {
Anton Korobeynikov0b12ecf2008-05-07 22:54:15 +00003007 V = V->stripPointerCasts();
Duncan Sandsb4fd45e2007-07-06 09:10:03 +00003008 GlobalVariable *GV = dyn_cast<GlobalVariable>(V);
Anton Korobeynikov4c71dfe2008-02-20 11:10:28 +00003009 assert ((GV || isa<ConstantPointerNull>(V)) &&
Duncan Sandscf26d7c2007-07-04 20:52:51 +00003010 "TypeInfo must be a global variable or NULL");
3011 return GV;
3012}
3013
Duncan Sandsf4070822007-06-15 19:04:19 +00003014/// addCatchInfo - Extract the personality and type infos from an eh.selector
Duncan Sandscf26d7c2007-07-04 20:52:51 +00003015/// call, and add them to the specified machine basic block.
Duncan Sandsf4070822007-06-15 19:04:19 +00003016static void addCatchInfo(CallInst &I, MachineModuleInfo *MMI,
3017 MachineBasicBlock *MBB) {
3018 // Inform the MachineModuleInfo of the personality for this landing pad.
3019 ConstantExpr *CE = cast<ConstantExpr>(I.getOperand(2));
3020 assert(CE->getOpcode() == Instruction::BitCast &&
3021 isa<Function>(CE->getOperand(0)) &&
3022 "Personality should be a function");
3023 MMI->addPersonality(MBB, cast<Function>(CE->getOperand(0)));
3024
3025 // Gather all the type infos for this landing pad and pass them along to
3026 // MachineModuleInfo.
3027 std::vector<GlobalVariable *> TyInfo;
Duncan Sandscf26d7c2007-07-04 20:52:51 +00003028 unsigned N = I.getNumOperands();
3029
3030 for (unsigned i = N - 1; i > 2; --i) {
3031 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(i))) {
3032 unsigned FilterLength = CI->getZExtValue();
Duncan Sands6590b042007-08-27 15:47:50 +00003033 unsigned FirstCatch = i + FilterLength + !FilterLength;
Duncan Sandscf26d7c2007-07-04 20:52:51 +00003034 assert (FirstCatch <= N && "Invalid filter length");
3035
3036 if (FirstCatch < N) {
3037 TyInfo.reserve(N - FirstCatch);
3038 for (unsigned j = FirstCatch; j < N; ++j)
3039 TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
3040 MMI->addCatchTypeInfo(MBB, TyInfo);
3041 TyInfo.clear();
3042 }
3043
Duncan Sands6590b042007-08-27 15:47:50 +00003044 if (!FilterLength) {
3045 // Cleanup.
3046 MMI->addCleanup(MBB);
3047 } else {
3048 // Filter.
3049 TyInfo.reserve(FilterLength - 1);
3050 for (unsigned j = i + 1; j < FirstCatch; ++j)
3051 TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
3052 MMI->addFilterTypeInfo(MBB, TyInfo);
3053 TyInfo.clear();
3054 }
Duncan Sandscf26d7c2007-07-04 20:52:51 +00003055
3056 N = i;
3057 }
Duncan Sandsf4070822007-06-15 19:04:19 +00003058 }
Duncan Sandscf26d7c2007-07-04 20:52:51 +00003059
3060 if (N > 3) {
3061 TyInfo.reserve(N - 3);
3062 for (unsigned j = 3; j < N; ++j)
3063 TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
Duncan Sandsf4070822007-06-15 19:04:19 +00003064 MMI->addCatchTypeInfo(MBB, TyInfo);
Duncan Sandscf26d7c2007-07-04 20:52:51 +00003065 }
Duncan Sandsf4070822007-06-15 19:04:19 +00003066}
3067
Mon P Wang63307c32008-05-05 19:05:59 +00003068
3069/// Inlined utility function to implement binary input atomic intrinsics for
3070// visitIntrinsicCall: I is a call instruction
3071// Op is the associated NodeType for I
3072const char *
3073SelectionDAGLowering::implVisitBinaryAtomic(CallInst& I, ISD::NodeType Op) {
3074 SDOperand Root = getRoot();
3075 SDOperand O2 = getValue(I.getOperand(2));
3076 SDOperand L = DAG.getAtomic(Op, Root,
3077 getValue(I.getOperand(1)),
3078 O2, O2.getValueType());
3079 setValue(&I, L);
3080 DAG.setRoot(L.getValue(1));
3081 return 0;
3082}
3083
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003084/// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
3085/// we want to emit this as a call to a named external function, return the name
3086/// otherwise lower it and return null.
3087const char *
3088SelectionDAGLowering::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
3089 switch (Intrinsic) {
Chris Lattner0eade312006-03-24 02:22:33 +00003090 default:
3091 // By default, turn this into a target intrinsic node.
3092 visitTargetIntrinsic(I, Intrinsic);
3093 return 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003094 case Intrinsic::vastart: visitVAStart(I); return 0;
3095 case Intrinsic::vaend: visitVAEnd(I); return 0;
3096 case Intrinsic::vacopy: visitVACopy(I); return 0;
Nate Begemanbcc5f362007-01-29 22:58:52 +00003097 case Intrinsic::returnaddress:
3098 setValue(&I, DAG.getNode(ISD::RETURNADDR, TLI.getPointerTy(),
3099 getValue(I.getOperand(1))));
3100 return 0;
3101 case Intrinsic::frameaddress:
3102 setValue(&I, DAG.getNode(ISD::FRAMEADDR, TLI.getPointerTy(),
3103 getValue(I.getOperand(1))));
3104 return 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003105 case Intrinsic::setjmp:
Anton Korobeynikovd27a2582006-12-10 23:12:42 +00003106 return "_setjmp"+!TLI.usesUnderscoreSetJmp();
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003107 break;
3108 case Intrinsic::longjmp:
Anton Korobeynikovd27a2582006-12-10 23:12:42 +00003109 return "_longjmp"+!TLI.usesUnderscoreLongJmp();
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003110 break;
Chris Lattner03dd4652006-03-03 00:00:25 +00003111 case Intrinsic::memcpy_i32:
Dan Gohman707e0182008-04-12 04:36:06 +00003112 case Intrinsic::memcpy_i64: {
3113 SDOperand Op1 = getValue(I.getOperand(1));
3114 SDOperand Op2 = getValue(I.getOperand(2));
3115 SDOperand Op3 = getValue(I.getOperand(3));
3116 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
3117 DAG.setRoot(DAG.getMemcpy(getRoot(), Op1, Op2, Op3, Align, false,
3118 I.getOperand(1), 0, I.getOperand(2), 0));
Chris Lattner03dd4652006-03-03 00:00:25 +00003119 return 0;
Dan Gohman707e0182008-04-12 04:36:06 +00003120 }
Chris Lattner03dd4652006-03-03 00:00:25 +00003121 case Intrinsic::memset_i32:
Dan Gohman707e0182008-04-12 04:36:06 +00003122 case Intrinsic::memset_i64: {
3123 SDOperand Op1 = getValue(I.getOperand(1));
3124 SDOperand Op2 = getValue(I.getOperand(2));
3125 SDOperand Op3 = getValue(I.getOperand(3));
3126 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
3127 DAG.setRoot(DAG.getMemset(getRoot(), Op1, Op2, Op3, Align,
3128 I.getOperand(1), 0));
Chris Lattner03dd4652006-03-03 00:00:25 +00003129 return 0;
Dan Gohman707e0182008-04-12 04:36:06 +00003130 }
Chris Lattner03dd4652006-03-03 00:00:25 +00003131 case Intrinsic::memmove_i32:
Dan Gohman707e0182008-04-12 04:36:06 +00003132 case Intrinsic::memmove_i64: {
3133 SDOperand Op1 = getValue(I.getOperand(1));
3134 SDOperand Op2 = getValue(I.getOperand(2));
3135 SDOperand Op3 = getValue(I.getOperand(3));
3136 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
3137
3138 // If the source and destination are known to not be aliases, we can
3139 // lower memmove as memcpy.
3140 uint64_t Size = -1ULL;
3141 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op3))
3142 Size = C->getValue();
3143 if (AA.alias(I.getOperand(1), Size, I.getOperand(2), Size) ==
3144 AliasAnalysis::NoAlias) {
3145 DAG.setRoot(DAG.getMemcpy(getRoot(), Op1, Op2, Op3, Align, false,
3146 I.getOperand(1), 0, I.getOperand(2), 0));
3147 return 0;
3148 }
3149
3150 DAG.setRoot(DAG.getMemmove(getRoot(), Op1, Op2, Op3, Align,
3151 I.getOperand(1), 0, I.getOperand(2), 0));
Chris Lattner03dd4652006-03-03 00:00:25 +00003152 return 0;
Dan Gohman707e0182008-04-12 04:36:06 +00003153 }
Chris Lattner86cb6432005-12-13 17:40:33 +00003154 case Intrinsic::dbg_stoppoint: {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00003155 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskey43970fe2006-03-23 18:06:46 +00003156 DbgStopPointInst &SPI = cast<DbgStopPointInst>(I);
Jim Laskey44c3b9f2007-01-26 21:22:28 +00003157 if (MMI && SPI.getContext() && MMI->Verify(SPI.getContext())) {
Chris Lattnerbd564bf2006-08-08 02:23:42 +00003158 SDOperand Ops[5];
Chris Lattner36ce6912005-11-29 06:21:05 +00003159
Chris Lattnerbd564bf2006-08-08 02:23:42 +00003160 Ops[0] = getRoot();
3161 Ops[1] = getValue(SPI.getLineValue());
3162 Ops[2] = getValue(SPI.getColumnValue());
Chris Lattner36ce6912005-11-29 06:21:05 +00003163
Jim Laskey44c3b9f2007-01-26 21:22:28 +00003164 DebugInfoDesc *DD = MMI->getDescFor(SPI.getContext());
Jim Laskeyce72b172006-02-11 01:01:30 +00003165 assert(DD && "Not a debug information descriptor");
Jim Laskey43970fe2006-03-23 18:06:46 +00003166 CompileUnitDesc *CompileUnit = cast<CompileUnitDesc>(DD);
3167
Chris Lattnerbd564bf2006-08-08 02:23:42 +00003168 Ops[3] = DAG.getString(CompileUnit->getFileName());
3169 Ops[4] = DAG.getString(CompileUnit->getDirectory());
Jim Laskeyce72b172006-02-11 01:01:30 +00003170
Chris Lattnerbd564bf2006-08-08 02:23:42 +00003171 DAG.setRoot(DAG.getNode(ISD::LOCATION, MVT::Other, Ops, 5));
Chris Lattner86cb6432005-12-13 17:40:33 +00003172 }
Jim Laskey43970fe2006-03-23 18:06:46 +00003173
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +00003174 return 0;
Chris Lattner36ce6912005-11-29 06:21:05 +00003175 }
Jim Laskey43970fe2006-03-23 18:06:46 +00003176 case Intrinsic::dbg_region_start: {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00003177 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskey43970fe2006-03-23 18:06:46 +00003178 DbgRegionStartInst &RSI = cast<DbgRegionStartInst>(I);
Jim Laskey44c3b9f2007-01-26 21:22:28 +00003179 if (MMI && RSI.getContext() && MMI->Verify(RSI.getContext())) {
3180 unsigned LabelID = MMI->RecordRegionStart(RSI.getContext());
Jim Laskey1ee29252007-01-26 14:34:52 +00003181 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, getRoot(),
Evan Chengbb81d972008-01-31 09:59:15 +00003182 DAG.getConstant(LabelID, MVT::i32),
3183 DAG.getConstant(0, MVT::i32)));
Jim Laskey43970fe2006-03-23 18:06:46 +00003184 }
3185
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +00003186 return 0;
Jim Laskey43970fe2006-03-23 18:06:46 +00003187 }
3188 case Intrinsic::dbg_region_end: {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00003189 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskey43970fe2006-03-23 18:06:46 +00003190 DbgRegionEndInst &REI = cast<DbgRegionEndInst>(I);
Jim Laskey44c3b9f2007-01-26 21:22:28 +00003191 if (MMI && REI.getContext() && MMI->Verify(REI.getContext())) {
3192 unsigned LabelID = MMI->RecordRegionEnd(REI.getContext());
Evan Chengbb81d972008-01-31 09:59:15 +00003193 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, getRoot(),
3194 DAG.getConstant(LabelID, MVT::i32),
3195 DAG.getConstant(0, MVT::i32)));
Jim Laskey43970fe2006-03-23 18:06:46 +00003196 }
3197
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +00003198 return 0;
Jim Laskey43970fe2006-03-23 18:06:46 +00003199 }
3200 case Intrinsic::dbg_func_start: {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00003201 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Evan Cheng1b08bbc2008-02-01 09:10:45 +00003202 if (!MMI) return 0;
Jim Laskey43970fe2006-03-23 18:06:46 +00003203 DbgFuncStartInst &FSI = cast<DbgFuncStartInst>(I);
Evan Cheng1b08bbc2008-02-01 09:10:45 +00003204 Value *SP = FSI.getSubprogram();
3205 if (SP && MMI->Verify(SP)) {
3206 // llvm.dbg.func.start implicitly defines a dbg_stoppoint which is
3207 // what (most?) gdb expects.
3208 DebugInfoDesc *DD = MMI->getDescFor(SP);
3209 assert(DD && "Not a debug information descriptor");
3210 SubprogramDesc *Subprogram = cast<SubprogramDesc>(DD);
3211 const CompileUnitDesc *CompileUnit = Subprogram->getFile();
3212 unsigned SrcFile = MMI->RecordSource(CompileUnit->getDirectory(),
3213 CompileUnit->getFileName());
3214 // Record the source line but does create a label. It will be emitted
3215 // at asm emission time.
3216 MMI->RecordSourceLine(Subprogram->getLine(), 0, SrcFile);
Jim Laskey43970fe2006-03-23 18:06:46 +00003217 }
3218
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +00003219 return 0;
Jim Laskey43970fe2006-03-23 18:06:46 +00003220 }
3221 case Intrinsic::dbg_declare: {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00003222 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskey43970fe2006-03-23 18:06:46 +00003223 DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
Evan Chenga844bde2008-02-02 04:07:54 +00003224 Value *Variable = DI.getVariable();
3225 if (MMI && Variable && MMI->Verify(Variable))
3226 DAG.setRoot(DAG.getNode(ISD::DECLARE, MVT::Other, getRoot(),
3227 getValue(DI.getAddress()), getValue(Variable)));
Jim Laskey43970fe2006-03-23 18:06:46 +00003228 return 0;
3229 }
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003230
Jim Laskeyb180aa12007-02-21 22:53:45 +00003231 case Intrinsic::eh_exception: {
Dale Johannesen1532f3d2008-04-02 00:25:04 +00003232 if (!CurMBB->isLandingPad()) {
3233 // FIXME: Mark exception register as live in. Hack for PR1508.
3234 unsigned Reg = TLI.getExceptionAddressRegister();
3235 if (Reg) CurMBB->addLiveIn(Reg);
Jim Laskey735b6f82007-02-22 15:38:06 +00003236 }
Dale Johannesen1532f3d2008-04-02 00:25:04 +00003237 // Insert the EXCEPTIONADDR instruction.
3238 SDVTList VTs = DAG.getVTList(TLI.getPointerTy(), MVT::Other);
3239 SDOperand Ops[1];
3240 Ops[0] = DAG.getRoot();
3241 SDOperand Op = DAG.getNode(ISD::EXCEPTIONADDR, VTs, Ops, 1);
3242 setValue(&I, Op);
3243 DAG.setRoot(Op.getValue(1));
Jim Laskeyb180aa12007-02-21 22:53:45 +00003244 return 0;
3245 }
3246
Anton Korobeynikov8806c7b2007-09-07 11:39:35 +00003247 case Intrinsic::eh_selector_i32:
3248 case Intrinsic::eh_selector_i64: {
Jim Laskeyb180aa12007-02-21 22:53:45 +00003249 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Duncan Sands83ec4b62008-06-06 12:08:01 +00003250 MVT VT = (Intrinsic == Intrinsic::eh_selector_i32 ?
Anton Korobeynikov8806c7b2007-09-07 11:39:35 +00003251 MVT::i32 : MVT::i64);
3252
Dale Johannesen1532f3d2008-04-02 00:25:04 +00003253 if (MMI) {
Duncan Sandsf4070822007-06-15 19:04:19 +00003254 if (CurMBB->isLandingPad())
3255 addCatchInfo(I, MMI, CurMBB);
Evan Chenge47c3332007-06-27 18:45:32 +00003256 else {
Duncan Sandsf4070822007-06-15 19:04:19 +00003257#ifndef NDEBUG
Duncan Sandsf4070822007-06-15 19:04:19 +00003258 FuncInfo.CatchInfoLost.insert(&I);
3259#endif
Duncan Sands90291952007-07-06 09:18:59 +00003260 // FIXME: Mark exception selector register as live in. Hack for PR1508.
3261 unsigned Reg = TLI.getExceptionSelectorRegister();
3262 if (Reg) CurMBB->addLiveIn(Reg);
Evan Chenge47c3332007-06-27 18:45:32 +00003263 }
Jim Laskey735b6f82007-02-22 15:38:06 +00003264
3265 // Insert the EHSELECTION instruction.
Anton Korobeynikov8806c7b2007-09-07 11:39:35 +00003266 SDVTList VTs = DAG.getVTList(VT, MVT::Other);
Jim Laskey735b6f82007-02-22 15:38:06 +00003267 SDOperand Ops[2];
3268 Ops[0] = getValue(I.getOperand(1));
3269 Ops[1] = getRoot();
3270 SDOperand Op = DAG.getNode(ISD::EHSELECTION, VTs, Ops, 2);
3271 setValue(&I, Op);
3272 DAG.setRoot(Op.getValue(1));
Jim Laskey7a1de982007-02-24 09:45:44 +00003273 } else {
Anton Korobeynikov8806c7b2007-09-07 11:39:35 +00003274 setValue(&I, DAG.getConstant(0, VT));
Jim Laskey735b6f82007-02-22 15:38:06 +00003275 }
Jim Laskeyb180aa12007-02-21 22:53:45 +00003276
3277 return 0;
3278 }
Anton Korobeynikov8806c7b2007-09-07 11:39:35 +00003279
3280 case Intrinsic::eh_typeid_for_i32:
3281 case Intrinsic::eh_typeid_for_i64: {
Jim Laskeyb180aa12007-02-21 22:53:45 +00003282 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Duncan Sands83ec4b62008-06-06 12:08:01 +00003283 MVT VT = (Intrinsic == Intrinsic::eh_typeid_for_i32 ?
Anton Korobeynikov8806c7b2007-09-07 11:39:35 +00003284 MVT::i32 : MVT::i64);
Jim Laskeyb180aa12007-02-21 22:53:45 +00003285
Jim Laskey735b6f82007-02-22 15:38:06 +00003286 if (MMI) {
3287 // Find the type id for the given typeinfo.
Duncan Sandscf26d7c2007-07-04 20:52:51 +00003288 GlobalVariable *GV = ExtractTypeInfo(I.getOperand(1));
Duncan Sands3b346362007-05-04 17:12:26 +00003289
Jim Laskey735b6f82007-02-22 15:38:06 +00003290 unsigned TypeID = MMI->getTypeIDFor(GV);
Anton Korobeynikov8806c7b2007-09-07 11:39:35 +00003291 setValue(&I, DAG.getConstant(TypeID, VT));
Jim Laskey7a1de982007-02-24 09:45:44 +00003292 } else {
Duncan Sandsf664e412007-07-06 14:46:23 +00003293 // Return something different to eh_selector.
Anton Korobeynikov8806c7b2007-09-07 11:39:35 +00003294 setValue(&I, DAG.getConstant(1, VT));
Jim Laskey735b6f82007-02-22 15:38:06 +00003295 }
Jim Laskeyb180aa12007-02-21 22:53:45 +00003296
3297 return 0;
3298 }
3299
Anton Korobeynikov2365f512007-07-14 14:06:15 +00003300 case Intrinsic::eh_return: {
3301 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3302
Dale Johannesen1532f3d2008-04-02 00:25:04 +00003303 if (MMI) {
Anton Korobeynikov2365f512007-07-14 14:06:15 +00003304 MMI->setCallsEHReturn(true);
3305 DAG.setRoot(DAG.getNode(ISD::EH_RETURN,
3306 MVT::Other,
Dan Gohman86e1ebf2008-03-27 19:56:19 +00003307 getControlRoot(),
Anton Korobeynikov2365f512007-07-14 14:06:15 +00003308 getValue(I.getOperand(1)),
3309 getValue(I.getOperand(2))));
3310 } else {
3311 setValue(&I, DAG.getConstant(0, TLI.getPointerTy()));
3312 }
3313
3314 return 0;
3315 }
3316
3317 case Intrinsic::eh_unwind_init: {
3318 if (MachineModuleInfo *MMI = DAG.getMachineModuleInfo()) {
3319 MMI->setCallsUnwindInit(true);
3320 }
3321
3322 return 0;
3323 }
3324
3325 case Intrinsic::eh_dwarf_cfa: {
Duncan Sands83ec4b62008-06-06 12:08:01 +00003326 MVT VT = getValue(I.getOperand(1)).getValueType();
Dale Johannesen1532f3d2008-04-02 00:25:04 +00003327 SDOperand CfaArg;
Duncan Sands8e4eb092008-06-08 20:54:56 +00003328 if (VT.bitsGT(TLI.getPointerTy()))
Dale Johannesen1532f3d2008-04-02 00:25:04 +00003329 CfaArg = DAG.getNode(ISD::TRUNCATE,
3330 TLI.getPointerTy(), getValue(I.getOperand(1)));
3331 else
3332 CfaArg = DAG.getNode(ISD::SIGN_EXTEND,
3333 TLI.getPointerTy(), getValue(I.getOperand(1)));
Anton Korobeynikov2365f512007-07-14 14:06:15 +00003334
Dale Johannesen1532f3d2008-04-02 00:25:04 +00003335 SDOperand Offset = DAG.getNode(ISD::ADD,
3336 TLI.getPointerTy(),
3337 DAG.getNode(ISD::FRAME_TO_ARGS_OFFSET,
3338 TLI.getPointerTy()),
3339 CfaArg);
3340 setValue(&I, DAG.getNode(ISD::ADD,
3341 TLI.getPointerTy(),
3342 DAG.getNode(ISD::FRAMEADDR,
3343 TLI.getPointerTy(),
3344 DAG.getConstant(0,
3345 TLI.getPointerTy())),
3346 Offset));
Anton Korobeynikov2365f512007-07-14 14:06:15 +00003347 return 0;
3348 }
3349
Dale Johannesen9ab7fb32007-10-02 17:43:59 +00003350 case Intrinsic::sqrt:
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003351 setValue(&I, DAG.getNode(ISD::FSQRT,
3352 getValue(I.getOperand(1)).getValueType(),
3353 getValue(I.getOperand(1))));
3354 return 0;
Dale Johannesen9ab7fb32007-10-02 17:43:59 +00003355 case Intrinsic::powi:
Chris Lattner6ddf8ed2006-09-09 06:03:30 +00003356 setValue(&I, DAG.getNode(ISD::FPOWI,
3357 getValue(I.getOperand(1)).getValueType(),
3358 getValue(I.getOperand(1)),
3359 getValue(I.getOperand(2))));
3360 return 0;
Dan Gohmanac9385a2007-10-12 00:01:22 +00003361 case Intrinsic::sin:
3362 setValue(&I, DAG.getNode(ISD::FSIN,
3363 getValue(I.getOperand(1)).getValueType(),
3364 getValue(I.getOperand(1))));
3365 return 0;
3366 case Intrinsic::cos:
3367 setValue(&I, DAG.getNode(ISD::FCOS,
3368 getValue(I.getOperand(1)).getValueType(),
3369 getValue(I.getOperand(1))));
3370 return 0;
3371 case Intrinsic::pow:
3372 setValue(&I, DAG.getNode(ISD::FPOW,
3373 getValue(I.getOperand(1)).getValueType(),
3374 getValue(I.getOperand(1)),
3375 getValue(I.getOperand(2))));
3376 return 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003377 case Intrinsic::pcmarker: {
3378 SDOperand Tmp = getValue(I.getOperand(1));
3379 DAG.setRoot(DAG.getNode(ISD::PCMARKER, MVT::Other, getRoot(), Tmp));
3380 return 0;
3381 }
Andrew Lenharth8b91c772005-11-11 22:48:54 +00003382 case Intrinsic::readcyclecounter: {
Chris Lattnerbd564bf2006-08-08 02:23:42 +00003383 SDOperand Op = getRoot();
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00003384 SDOperand Tmp = DAG.getNode(ISD::READCYCLECOUNTER,
3385 DAG.getNodeValueTypes(MVT::i64, MVT::Other), 2,
3386 &Op, 1);
Andrew Lenharth8b91c772005-11-11 22:48:54 +00003387 setValue(&I, Tmp);
3388 DAG.setRoot(Tmp.getValue(1));
Andrew Lenharth51b8d542005-11-11 16:47:30 +00003389 return 0;
Andrew Lenharth8b91c772005-11-11 22:48:54 +00003390 }
Chris Lattnerc6eb6d72007-04-10 03:20:39 +00003391 case Intrinsic::part_select: {
Reid Spencer3f108cb2007-04-05 01:20:18 +00003392 // Currently not implemented: just abort
Reid Spencerf75b8742007-04-12 02:48:46 +00003393 assert(0 && "part_select intrinsic not implemented");
3394 abort();
3395 }
3396 case Intrinsic::part_set: {
3397 // Currently not implemented: just abort
3398 assert(0 && "part_set intrinsic not implemented");
Reid Spencer3f108cb2007-04-05 01:20:18 +00003399 abort();
Reid Spenceraddd11d2007-04-04 23:48:25 +00003400 }
Reid Spencera4f9c4d2007-04-01 07:34:11 +00003401 case Intrinsic::bswap:
Nate Begemand88fc032006-01-14 03:14:10 +00003402 setValue(&I, DAG.getNode(ISD::BSWAP,
3403 getValue(I.getOperand(1)).getValueType(),
3404 getValue(I.getOperand(1))));
3405 return 0;
Reid Spencera4f9c4d2007-04-01 07:34:11 +00003406 case Intrinsic::cttz: {
3407 SDOperand Arg = getValue(I.getOperand(1));
Duncan Sands83ec4b62008-06-06 12:08:01 +00003408 MVT Ty = Arg.getValueType();
Reid Spencera4f9c4d2007-04-01 07:34:11 +00003409 SDOperand result = DAG.getNode(ISD::CTTZ, Ty, Arg);
Reid Spencera4f9c4d2007-04-01 07:34:11 +00003410 setValue(&I, result);
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003411 return 0;
Reid Spencera4f9c4d2007-04-01 07:34:11 +00003412 }
3413 case Intrinsic::ctlz: {
3414 SDOperand Arg = getValue(I.getOperand(1));
Duncan Sands83ec4b62008-06-06 12:08:01 +00003415 MVT Ty = Arg.getValueType();
Reid Spencera4f9c4d2007-04-01 07:34:11 +00003416 SDOperand result = DAG.getNode(ISD::CTLZ, Ty, Arg);
Reid Spencera4f9c4d2007-04-01 07:34:11 +00003417 setValue(&I, result);
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003418 return 0;
Reid Spencera4f9c4d2007-04-01 07:34:11 +00003419 }
3420 case Intrinsic::ctpop: {
3421 SDOperand Arg = getValue(I.getOperand(1));
Duncan Sands83ec4b62008-06-06 12:08:01 +00003422 MVT Ty = Arg.getValueType();
Reid Spencera4f9c4d2007-04-01 07:34:11 +00003423 SDOperand result = DAG.getNode(ISD::CTPOP, Ty, Arg);
Reid Spencera4f9c4d2007-04-01 07:34:11 +00003424 setValue(&I, result);
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003425 return 0;
Reid Spencera4f9c4d2007-04-01 07:34:11 +00003426 }
Chris Lattner140d53c2006-01-13 02:50:02 +00003427 case Intrinsic::stacksave: {
Chris Lattnerbd564bf2006-08-08 02:23:42 +00003428 SDOperand Op = getRoot();
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00003429 SDOperand Tmp = DAG.getNode(ISD::STACKSAVE,
3430 DAG.getNodeValueTypes(TLI.getPointerTy(), MVT::Other), 2, &Op, 1);
Chris Lattner140d53c2006-01-13 02:50:02 +00003431 setValue(&I, Tmp);
3432 DAG.setRoot(Tmp.getValue(1));
3433 return 0;
3434 }
Chris Lattner39a17dd2006-01-23 05:22:07 +00003435 case Intrinsic::stackrestore: {
3436 SDOperand Tmp = getValue(I.getOperand(1));
3437 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, MVT::Other, getRoot(), Tmp));
Chris Lattner140d53c2006-01-13 02:50:02 +00003438 return 0;
Chris Lattner39a17dd2006-01-23 05:22:07 +00003439 }
Tanya Lattner24e5aad2007-06-15 22:26:58 +00003440 case Intrinsic::var_annotation:
3441 // Discard annotate attributes
3442 return 0;
Duncan Sands36397f52007-07-27 12:58:54 +00003443
Duncan Sands36397f52007-07-27 12:58:54 +00003444 case Intrinsic::init_trampoline: {
Anton Korobeynikov0b12ecf2008-05-07 22:54:15 +00003445 const Function *F = cast<Function>(I.getOperand(2)->stripPointerCasts());
Duncan Sands36397f52007-07-27 12:58:54 +00003446
3447 SDOperand Ops[6];
3448 Ops[0] = getRoot();
3449 Ops[1] = getValue(I.getOperand(1));
3450 Ops[2] = getValue(I.getOperand(2));
3451 Ops[3] = getValue(I.getOperand(3));
3452 Ops[4] = DAG.getSrcValue(I.getOperand(1));
3453 Ops[5] = DAG.getSrcValue(F);
3454
Duncan Sandsf7331b32007-09-11 14:10:23 +00003455 SDOperand Tmp = DAG.getNode(ISD::TRAMPOLINE,
3456 DAG.getNodeValueTypes(TLI.getPointerTy(),
3457 MVT::Other), 2,
3458 Ops, 6);
3459
3460 setValue(&I, Tmp);
3461 DAG.setRoot(Tmp.getValue(1));
Duncan Sands36397f52007-07-27 12:58:54 +00003462 return 0;
3463 }
Gordon Henriksence224772008-01-07 01:30:38 +00003464
3465 case Intrinsic::gcroot:
3466 if (GCI) {
3467 Value *Alloca = I.getOperand(1);
3468 Constant *TypeMap = cast<Constant>(I.getOperand(2));
3469
3470 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).Val);
3471 GCI->addStackRoot(FI->getIndex(), TypeMap);
3472 }
3473 return 0;
3474
3475 case Intrinsic::gcread:
3476 case Intrinsic::gcwrite:
3477 assert(0 && "Collector failed to lower gcread/gcwrite intrinsics!");
3478 return 0;
3479
Anton Korobeynikov917c2a62007-11-15 23:25:33 +00003480 case Intrinsic::flt_rounds: {
Dan Gohman1a024862008-01-31 00:41:03 +00003481 setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, MVT::i32));
Anton Korobeynikov917c2a62007-11-15 23:25:33 +00003482 return 0;
3483 }
Anton Korobeynikov66fac792008-01-15 07:02:33 +00003484
3485 case Intrinsic::trap: {
3486 DAG.setRoot(DAG.getNode(ISD::TRAP, MVT::Other, getRoot()));
3487 return 0;
3488 }
Evan Cheng27b7db52008-03-08 00:58:38 +00003489 case Intrinsic::prefetch: {
3490 SDOperand Ops[4];
3491 Ops[0] = getRoot();
3492 Ops[1] = getValue(I.getOperand(1));
3493 Ops[2] = getValue(I.getOperand(2));
3494 Ops[3] = getValue(I.getOperand(3));
3495 DAG.setRoot(DAG.getNode(ISD::PREFETCH, MVT::Other, &Ops[0], 4));
3496 return 0;
3497 }
3498
Andrew Lenharth22c5c1b2008-02-16 01:24:58 +00003499 case Intrinsic::memory_barrier: {
3500 SDOperand Ops[6];
3501 Ops[0] = getRoot();
3502 for (int x = 1; x < 6; ++x)
3503 Ops[x] = getValue(I.getOperand(x));
3504
3505 DAG.setRoot(DAG.getNode(ISD::MEMBARRIER, MVT::Other, &Ops[0], 6));
3506 return 0;
3507 }
Andrew Lenharthab0b9492008-02-21 06:45:13 +00003508 case Intrinsic::atomic_lcs: {
3509 SDOperand Root = getRoot();
3510 SDOperand O3 = getValue(I.getOperand(3));
3511 SDOperand L = DAG.getAtomic(ISD::ATOMIC_LCS, Root,
3512 getValue(I.getOperand(1)),
3513 getValue(I.getOperand(2)),
3514 O3, O3.getValueType());
3515 setValue(&I, L);
3516 DAG.setRoot(L.getValue(1));
3517 return 0;
3518 }
Mon P Wang63307c32008-05-05 19:05:59 +00003519 case Intrinsic::atomic_las:
3520 return implVisitBinaryAtomic(I, ISD::ATOMIC_LAS);
3521 case Intrinsic::atomic_lss:
3522 return implVisitBinaryAtomic(I, ISD::ATOMIC_LSS);
3523 case Intrinsic::atomic_load_and:
3524 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_AND);
3525 case Intrinsic::atomic_load_or:
3526 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_OR);
3527 case Intrinsic::atomic_load_xor:
3528 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_XOR);
3529 case Intrinsic::atomic_load_min:
3530 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MIN);
3531 case Intrinsic::atomic_load_max:
3532 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MAX);
3533 case Intrinsic::atomic_load_umin:
3534 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMIN);
3535 case Intrinsic::atomic_load_umax:
3536 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMAX);
3537 case Intrinsic::atomic_swap:
3538 return implVisitBinaryAtomic(I, ISD::ATOMIC_SWAP);
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003539 }
3540}
3541
3542
Duncan Sands6f74b482007-12-19 09:48:52 +00003543void SelectionDAGLowering::LowerCallTo(CallSite CS, SDOperand Callee,
Jim Laskey1da20a72007-02-23 21:45:01 +00003544 bool IsTailCall,
Anton Korobeynikov070280e2007-05-23 11:08:31 +00003545 MachineBasicBlock *LandingPad) {
Duncan Sands6f74b482007-12-19 09:48:52 +00003546 const PointerType *PT = cast<PointerType>(CS.getCalledValue()->getType());
Jim Laskey735b6f82007-02-22 15:38:06 +00003547 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
Anton Korobeynikov070280e2007-05-23 11:08:31 +00003548 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3549 unsigned BeginLabel = 0, EndLabel = 0;
Duncan Sands6f74b482007-12-19 09:48:52 +00003550
Jim Laskey735b6f82007-02-22 15:38:06 +00003551 TargetLowering::ArgListTy Args;
3552 TargetLowering::ArgListEntry Entry;
Duncan Sands6f74b482007-12-19 09:48:52 +00003553 Args.reserve(CS.arg_size());
3554 for (CallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
3555 i != e; ++i) {
3556 SDOperand ArgNode = getValue(*i);
3557 Entry.Node = ArgNode; Entry.Ty = (*i)->getType();
Duncan Sands4fee7032007-05-07 20:49:28 +00003558
Duncan Sands6f74b482007-12-19 09:48:52 +00003559 unsigned attrInd = i - CS.arg_begin() + 1;
3560 Entry.isSExt = CS.paramHasAttr(attrInd, ParamAttr::SExt);
3561 Entry.isZExt = CS.paramHasAttr(attrInd, ParamAttr::ZExt);
3562 Entry.isInReg = CS.paramHasAttr(attrInd, ParamAttr::InReg);
3563 Entry.isSRet = CS.paramHasAttr(attrInd, ParamAttr::StructRet);
3564 Entry.isNest = CS.paramHasAttr(attrInd, ParamAttr::Nest);
3565 Entry.isByVal = CS.paramHasAttr(attrInd, ParamAttr::ByVal);
Dale Johannesen08e78b12008-02-22 17:49:45 +00003566 Entry.Alignment = CS.getParamAlignment(attrInd);
Jim Laskey735b6f82007-02-22 15:38:06 +00003567 Args.push_back(Entry);
3568 }
3569
Dale Johannesen1532f3d2008-04-02 00:25:04 +00003570 if (LandingPad && MMI) {
Anton Korobeynikov070280e2007-05-23 11:08:31 +00003571 // Insert a label before the invoke call to mark the try range. This can be
3572 // used to detect deletion of the invoke via the MachineModuleInfo.
3573 BeginLabel = MMI->NextLabelID();
Dale Johannesena4091d32008-04-04 23:48:31 +00003574 // Both PendingLoads and PendingExports must be flushed here;
3575 // this call might not return.
3576 (void)getRoot();
3577 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, getControlRoot(),
Evan Chengbb81d972008-01-31 09:59:15 +00003578 DAG.getConstant(BeginLabel, MVT::i32),
3579 DAG.getConstant(1, MVT::i32)));
Anton Korobeynikov070280e2007-05-23 11:08:31 +00003580 }
Duncan Sands6f74b482007-12-19 09:48:52 +00003581
Jim Laskey735b6f82007-02-22 15:38:06 +00003582 std::pair<SDOperand,SDOperand> Result =
Duncan Sands6f74b482007-12-19 09:48:52 +00003583 TLI.LowerCallTo(getRoot(), CS.getType(),
3584 CS.paramHasAttr(0, ParamAttr::SExt),
Duncan Sands00fee652008-02-14 17:28:50 +00003585 CS.paramHasAttr(0, ParamAttr::ZExt),
Duncan Sands6f74b482007-12-19 09:48:52 +00003586 FTy->isVarArg(), CS.getCallingConv(), IsTailCall,
Jim Laskey735b6f82007-02-22 15:38:06 +00003587 Callee, Args, DAG);
Duncan Sands6f74b482007-12-19 09:48:52 +00003588 if (CS.getType() != Type::VoidTy)
3589 setValue(CS.getInstruction(), Result.first);
Jim Laskey735b6f82007-02-22 15:38:06 +00003590 DAG.setRoot(Result.second);
Anton Korobeynikov070280e2007-05-23 11:08:31 +00003591
Dale Johannesen1532f3d2008-04-02 00:25:04 +00003592 if (LandingPad && MMI) {
Anton Korobeynikov070280e2007-05-23 11:08:31 +00003593 // Insert a label at the end of the invoke call to mark the try range. This
3594 // can be used to detect deletion of the invoke via the MachineModuleInfo.
3595 EndLabel = MMI->NextLabelID();
3596 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, getRoot(),
Evan Chengbb81d972008-01-31 09:59:15 +00003597 DAG.getConstant(EndLabel, MVT::i32),
3598 DAG.getConstant(1, MVT::i32)));
Anton Korobeynikov070280e2007-05-23 11:08:31 +00003599
Duncan Sands6f74b482007-12-19 09:48:52 +00003600 // Inform MachineModuleInfo of range.
Anton Korobeynikov070280e2007-05-23 11:08:31 +00003601 MMI->addInvoke(LandingPad, BeginLabel, EndLabel);
3602 }
Jim Laskey735b6f82007-02-22 15:38:06 +00003603}
3604
3605
Chris Lattner1c08c712005-01-07 07:47:53 +00003606void SelectionDAGLowering::visitCall(CallInst &I) {
Chris Lattner64e14b12005-01-08 22:48:57 +00003607 const char *RenameFn = 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003608 if (Function *F = I.getCalledFunction()) {
Chris Lattner87b51bc2007-09-10 21:15:22 +00003609 if (F->isDeclaration()) {
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003610 if (unsigned IID = F->getIntrinsicID()) {
3611 RenameFn = visitIntrinsicCall(I, IID);
3612 if (!RenameFn)
3613 return;
Chris Lattner87b51bc2007-09-10 21:15:22 +00003614 }
3615 }
3616
3617 // Check for well-known libc/libm calls. If the function is internal, it
3618 // can't be a library call.
3619 unsigned NameLen = F->getNameLen();
3620 if (!F->hasInternalLinkage() && NameLen) {
3621 const char *NameStr = F->getNameStart();
3622 if (NameStr[0] == 'c' &&
3623 ((NameLen == 8 && !strcmp(NameStr, "copysign")) ||
3624 (NameLen == 9 && !strcmp(NameStr, "copysignf")))) {
3625 if (I.getNumOperands() == 3 && // Basic sanity checks.
3626 I.getOperand(1)->getType()->isFloatingPoint() &&
3627 I.getType() == I.getOperand(1)->getType() &&
3628 I.getType() == I.getOperand(2)->getType()) {
3629 SDOperand LHS = getValue(I.getOperand(1));
3630 SDOperand RHS = getValue(I.getOperand(2));
3631 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, LHS.getValueType(),
3632 LHS, RHS));
3633 return;
3634 }
3635 } else if (NameStr[0] == 'f' &&
3636 ((NameLen == 4 && !strcmp(NameStr, "fabs")) ||
Dale Johannesen2f429012007-09-26 21:10:55 +00003637 (NameLen == 5 && !strcmp(NameStr, "fabsf")) ||
3638 (NameLen == 5 && !strcmp(NameStr, "fabsl")))) {
Chris Lattner87b51bc2007-09-10 21:15:22 +00003639 if (I.getNumOperands() == 2 && // Basic sanity checks.
3640 I.getOperand(1)->getType()->isFloatingPoint() &&
3641 I.getType() == I.getOperand(1)->getType()) {
3642 SDOperand Tmp = getValue(I.getOperand(1));
3643 setValue(&I, DAG.getNode(ISD::FABS, Tmp.getValueType(), Tmp));
3644 return;
3645 }
3646 } else if (NameStr[0] == 's' &&
3647 ((NameLen == 3 && !strcmp(NameStr, "sin")) ||
Dale Johannesen2f429012007-09-26 21:10:55 +00003648 (NameLen == 4 && !strcmp(NameStr, "sinf")) ||
3649 (NameLen == 4 && !strcmp(NameStr, "sinl")))) {
Chris Lattner87b51bc2007-09-10 21:15:22 +00003650 if (I.getNumOperands() == 2 && // Basic sanity checks.
3651 I.getOperand(1)->getType()->isFloatingPoint() &&
3652 I.getType() == I.getOperand(1)->getType()) {
3653 SDOperand Tmp = getValue(I.getOperand(1));
3654 setValue(&I, DAG.getNode(ISD::FSIN, Tmp.getValueType(), Tmp));
3655 return;
3656 }
3657 } else if (NameStr[0] == 'c' &&
3658 ((NameLen == 3 && !strcmp(NameStr, "cos")) ||
Dale Johannesen2f429012007-09-26 21:10:55 +00003659 (NameLen == 4 && !strcmp(NameStr, "cosf")) ||
3660 (NameLen == 4 && !strcmp(NameStr, "cosl")))) {
Chris Lattner87b51bc2007-09-10 21:15:22 +00003661 if (I.getNumOperands() == 2 && // Basic sanity checks.
3662 I.getOperand(1)->getType()->isFloatingPoint() &&
3663 I.getType() == I.getOperand(1)->getType()) {
3664 SDOperand Tmp = getValue(I.getOperand(1));
3665 setValue(&I, DAG.getNode(ISD::FCOS, Tmp.getValueType(), Tmp));
3666 return;
Chris Lattnerf76e7dc2005-04-30 04:43:14 +00003667 }
Chris Lattner1ca85d52005-05-14 13:56:55 +00003668 }
Chris Lattner87b51bc2007-09-10 21:15:22 +00003669 }
Chris Lattnerce7518c2006-01-26 22:24:51 +00003670 } else if (isa<InlineAsm>(I.getOperand(0))) {
Duncan Sandsfd7b3262007-12-17 18:08:19 +00003671 visitInlineAsm(&I);
Chris Lattnerce7518c2006-01-26 22:24:51 +00003672 return;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003673 }
Misha Brukmanedf128a2005-04-21 22:36:52 +00003674
Chris Lattner64e14b12005-01-08 22:48:57 +00003675 SDOperand Callee;
3676 if (!RenameFn)
3677 Callee = getValue(I.getOperand(0));
3678 else
3679 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
Anton Korobeynikov070280e2007-05-23 11:08:31 +00003680
Duncan Sands6f74b482007-12-19 09:48:52 +00003681 LowerCallTo(&I, Callee, I.isTailCall());
Chris Lattner1c08c712005-01-07 07:47:53 +00003682}
3683
Jim Laskey735b6f82007-02-22 15:38:06 +00003684
Dan Gohmanef5d1942008-03-11 21:11:25 +00003685void SelectionDAGLowering::visitGetResult(GetResultInst &I) {
Dan Gohman67780f12008-04-23 20:25:16 +00003686 if (isa<UndefValue>(I.getOperand(0))) {
Dan Gohman3dc34f62008-04-23 20:21:29 +00003687 SDOperand Undef = DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType()));
3688 setValue(&I, Undef);
Chris Lattner6833b062008-04-28 07:16:35 +00003689 return;
Dan Gohman3dc34f62008-04-23 20:21:29 +00003690 }
Chris Lattner6833b062008-04-28 07:16:35 +00003691
3692 // To add support for individual return values with aggregate types,
3693 // we'd need a way to take a getresult index and determine which
3694 // values of the Call SDNode are associated with it.
3695 assert(TLI.getValueType(I.getType(), true) != MVT::Other &&
3696 "Individual return values must not be aggregates!");
3697
3698 SDOperand Call = getValue(I.getOperand(0));
3699 setValue(&I, SDOperand(Call.Val, I.getIndex()));
Dan Gohmanef5d1942008-03-11 21:11:25 +00003700}
3701
3702
Dan Gohmanb6f5b002007-06-28 23:29:44 +00003703/// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
3704/// this value and returns the result as a ValueVT value. This uses
3705/// Chain/Flag as the input and updates them for the output Chain/Flag.
3706/// If the Flag pointer is NULL, no flag is used.
3707SDOperand RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
Chris Lattner6833b062008-04-28 07:16:35 +00003708 SDOperand &Chain,
3709 SDOperand *Flag) const {
Dan Gohman23ce5022008-04-25 18:27:55 +00003710 // Assemble the legal parts into the final values.
3711 SmallVector<SDOperand, 4> Values(ValueVTs.size());
Chris Lattner6833b062008-04-28 07:16:35 +00003712 SmallVector<SDOperand, 8> Parts;
3713 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
Dan Gohman23ce5022008-04-25 18:27:55 +00003714 // Copy the legal parts from the registers.
Duncan Sands83ec4b62008-06-06 12:08:01 +00003715 MVT ValueVT = ValueVTs[Value];
Dan Gohman23ce5022008-04-25 18:27:55 +00003716 unsigned NumRegs = TLI->getNumRegisters(ValueVT);
Duncan Sands83ec4b62008-06-06 12:08:01 +00003717 MVT RegisterVT = RegVTs[Value];
Dan Gohman23ce5022008-04-25 18:27:55 +00003718
Chris Lattner6833b062008-04-28 07:16:35 +00003719 Parts.resize(NumRegs);
Dan Gohman23ce5022008-04-25 18:27:55 +00003720 for (unsigned i = 0; i != NumRegs; ++i) {
Chris Lattner6833b062008-04-28 07:16:35 +00003721 SDOperand P;
3722 if (Flag == 0)
3723 P = DAG.getCopyFromReg(Chain, Regs[Part+i], RegisterVT);
3724 else {
3725 P = DAG.getCopyFromReg(Chain, Regs[Part+i], RegisterVT, *Flag);
Dan Gohman23ce5022008-04-25 18:27:55 +00003726 *Flag = P.getValue(2);
Chris Lattner6833b062008-04-28 07:16:35 +00003727 }
3728 Chain = P.getValue(1);
Dan Gohman23ce5022008-04-25 18:27:55 +00003729 Parts[Part+i] = P;
3730 }
Chris Lattner5df99b32007-03-25 05:00:54 +00003731
Dan Gohman23ce5022008-04-25 18:27:55 +00003732 Values[Value] = getCopyFromParts(DAG, &Parts[Part], NumRegs, RegisterVT,
3733 ValueVT);
3734 Part += NumRegs;
3735 }
Chris Lattner6833b062008-04-28 07:16:35 +00003736
3737 if (ValueVTs.size() == 1)
3738 return Values[0];
3739
Dan Gohman23ce5022008-04-25 18:27:55 +00003740 return DAG.getNode(ISD::MERGE_VALUES,
3741 DAG.getVTList(&ValueVTs[0], ValueVTs.size()),
3742 &Values[0], ValueVTs.size());
Chris Lattner864635a2006-02-22 22:37:12 +00003743}
3744
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00003745/// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
3746/// specified value into the registers specified by this object. This uses
3747/// Chain/Flag as the input and updates them for the output Chain/Flag.
Dan Gohmanb6f5b002007-06-28 23:29:44 +00003748/// If the Flag pointer is NULL, no flag is used.
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00003749void RegsForValue::getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
Dan Gohmanb6f5b002007-06-28 23:29:44 +00003750 SDOperand &Chain, SDOperand *Flag) const {
Dan Gohmanb6f5b002007-06-28 23:29:44 +00003751 // Get the list of the values's legal parts.
Dan Gohman23ce5022008-04-25 18:27:55 +00003752 unsigned NumRegs = Regs.size();
3753 SmallVector<SDOperand, 8> Parts(NumRegs);
Chris Lattner6833b062008-04-28 07:16:35 +00003754 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
Duncan Sands83ec4b62008-06-06 12:08:01 +00003755 MVT ValueVT = ValueVTs[Value];
Dan Gohman23ce5022008-04-25 18:27:55 +00003756 unsigned NumParts = TLI->getNumRegisters(ValueVT);
Duncan Sands83ec4b62008-06-06 12:08:01 +00003757 MVT RegisterVT = RegVTs[Value];
Dan Gohman23ce5022008-04-25 18:27:55 +00003758
3759 getCopyToParts(DAG, Val.getValue(Val.ResNo + Value),
3760 &Parts[Part], NumParts, RegisterVT);
3761 Part += NumParts;
3762 }
Dan Gohmanb6f5b002007-06-28 23:29:44 +00003763
3764 // Copy the parts into the registers.
Dan Gohman23ce5022008-04-25 18:27:55 +00003765 SmallVector<SDOperand, 8> Chains(NumRegs);
3766 for (unsigned i = 0; i != NumRegs; ++i) {
Chris Lattner6833b062008-04-28 07:16:35 +00003767 SDOperand Part;
3768 if (Flag == 0)
3769 Part = DAG.getCopyToReg(Chain, Regs[i], Parts[i]);
3770 else {
3771 Part = DAG.getCopyToReg(Chain, Regs[i], Parts[i], *Flag);
Dan Gohmanb6f5b002007-06-28 23:29:44 +00003772 *Flag = Part.getValue(1);
Chris Lattner6833b062008-04-28 07:16:35 +00003773 }
3774 Chains[i] = Part.getValue(0);
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00003775 }
Chris Lattner6833b062008-04-28 07:16:35 +00003776
Evan Cheng33bf38a2008-04-28 22:07:13 +00003777 if (NumRegs == 1 || Flag)
3778 // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is
3779 // flagged to it. That is the CopyToReg nodes and the user are considered
3780 // a single scheduling unit. If we create a TokenFactor and return it as
3781 // chain, then the TokenFactor is both a predecessor (operand) of the
3782 // user as well as a successor (the TF operands are flagged to the user).
3783 // c1, f1 = CopyToReg
3784 // c2, f2 = CopyToReg
3785 // c3 = TokenFactor c1, c2
3786 // ...
3787 // = op c3, ..., f2
3788 Chain = Chains[NumRegs-1];
Chris Lattner6833b062008-04-28 07:16:35 +00003789 else
3790 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other, &Chains[0], NumRegs);
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00003791}
Chris Lattner864635a2006-02-22 22:37:12 +00003792
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00003793/// AddInlineAsmOperands - Add this value to the specified inlineasm node
3794/// operand list. This adds the code marker and includes the number of
3795/// values added into it.
3796void RegsForValue::AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
Chris Lattner9f6637d2006-02-23 20:06:57 +00003797 std::vector<SDOperand> &Ops) const {
Duncan Sands83ec4b62008-06-06 12:08:01 +00003798 MVT IntPtrTy = DAG.getTargetLoweringInfo().getPointerTy();
Chris Lattner4b993b12007-04-09 00:33:58 +00003799 Ops.push_back(DAG.getTargetConstant(Code | (Regs.size() << 3), IntPtrTy));
Chris Lattner6833b062008-04-28 07:16:35 +00003800 for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
3801 unsigned NumRegs = TLI->getNumRegisters(ValueVTs[Value]);
Duncan Sands83ec4b62008-06-06 12:08:01 +00003802 MVT RegisterVT = RegVTs[Value];
Chris Lattner6833b062008-04-28 07:16:35 +00003803 for (unsigned i = 0; i != NumRegs; ++i)
3804 Ops.push_back(DAG.getRegister(Regs[Reg++], RegisterVT));
Dan Gohman23ce5022008-04-25 18:27:55 +00003805 }
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00003806}
Chris Lattner864635a2006-02-22 22:37:12 +00003807
3808/// isAllocatableRegister - If the specified register is safe to allocate,
3809/// i.e. it isn't a stack pointer or some other special register, return the
3810/// register class for the register. Otherwise, return null.
3811static const TargetRegisterClass *
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00003812isAllocatableRegister(unsigned Reg, MachineFunction &MF,
Dan Gohman6f0d0242008-02-10 18:45:23 +00003813 const TargetLowering &TLI,
3814 const TargetRegisterInfo *TRI) {
Duncan Sands83ec4b62008-06-06 12:08:01 +00003815 MVT FoundVT = MVT::Other;
Chris Lattnerf8814cf2006-04-02 00:24:45 +00003816 const TargetRegisterClass *FoundRC = 0;
Dan Gohman6f0d0242008-02-10 18:45:23 +00003817 for (TargetRegisterInfo::regclass_iterator RCI = TRI->regclass_begin(),
3818 E = TRI->regclass_end(); RCI != E; ++RCI) {
Duncan Sands83ec4b62008-06-06 12:08:01 +00003819 MVT ThisVT = MVT::Other;
Chris Lattnerf8814cf2006-04-02 00:24:45 +00003820
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00003821 const TargetRegisterClass *RC = *RCI;
3822 // If none of the the value types for this register class are valid, we
3823 // can't use it. For example, 64-bit reg classes on 32-bit targets.
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00003824 for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
3825 I != E; ++I) {
3826 if (TLI.isTypeLegal(*I)) {
Chris Lattnerf8814cf2006-04-02 00:24:45 +00003827 // If we have already found this register in a different register class,
3828 // choose the one with the largest VT specified. For example, on
3829 // PowerPC, we favor f64 register classes over f32.
Duncan Sands8e4eb092008-06-08 20:54:56 +00003830 if (FoundVT == MVT::Other || FoundVT.bitsLT(*I)) {
Chris Lattnerf8814cf2006-04-02 00:24:45 +00003831 ThisVT = *I;
3832 break;
3833 }
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00003834 }
3835 }
3836
Chris Lattnerf8814cf2006-04-02 00:24:45 +00003837 if (ThisVT == MVT::Other) continue;
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00003838
Chris Lattner864635a2006-02-22 22:37:12 +00003839 // NOTE: This isn't ideal. In particular, this might allocate the
3840 // frame pointer in functions that need it (due to them not being taken
3841 // out of allocation, because a variable sized allocation hasn't been seen
3842 // yet). This is a slight code pessimization, but should still work.
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00003843 for (TargetRegisterClass::iterator I = RC->allocation_order_begin(MF),
3844 E = RC->allocation_order_end(MF); I != E; ++I)
Chris Lattnerf8814cf2006-04-02 00:24:45 +00003845 if (*I == Reg) {
3846 // We found a matching register class. Keep looking at others in case
3847 // we find one with larger registers that this physreg is also in.
3848 FoundRC = RC;
3849 FoundVT = ThisVT;
3850 break;
3851 }
Chris Lattner4e4b5762006-02-01 18:59:47 +00003852 }
Chris Lattnerf8814cf2006-04-02 00:24:45 +00003853 return FoundRC;
Chris Lattner864635a2006-02-22 22:37:12 +00003854}
3855
Chris Lattner4e4b5762006-02-01 18:59:47 +00003856
Chris Lattner0c583402007-04-28 20:49:53 +00003857namespace {
3858/// AsmOperandInfo - This contains information for each constraint that we are
3859/// lowering.
Evan Cheng5c807602008-02-26 02:33:44 +00003860struct SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo {
3861 /// CallOperand - If this is the result output operand or a clobber
3862 /// this is null, otherwise it is the incoming operand to the CallInst.
3863 /// This gets modified as the asm is processed.
Chris Lattner0c583402007-04-28 20:49:53 +00003864 SDOperand CallOperand;
Evan Cheng5c807602008-02-26 02:33:44 +00003865
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003866 /// AssignedRegs - If this is a register or register class operand, this
3867 /// contains the set of register corresponding to the operand.
3868 RegsForValue AssignedRegs;
3869
Dan Gohman23ce5022008-04-25 18:27:55 +00003870 explicit SDISelAsmOperandInfo(const InlineAsm::ConstraintInfo &info)
Evan Cheng5c807602008-02-26 02:33:44 +00003871 : TargetLowering::AsmOperandInfo(info), CallOperand(0,0) {
Chris Lattner0c583402007-04-28 20:49:53 +00003872 }
Chris Lattner3ff90dc2007-04-30 17:16:27 +00003873
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003874 /// MarkAllocatedRegs - Once AssignedRegs is set, mark the assigned registers
3875 /// busy in OutputRegs/InputRegs.
3876 void MarkAllocatedRegs(bool isOutReg, bool isInReg,
3877 std::set<unsigned> &OutputRegs,
Chris Lattner7cbeb242008-02-21 04:55:52 +00003878 std::set<unsigned> &InputRegs,
3879 const TargetRegisterInfo &TRI) const {
3880 if (isOutReg) {
3881 for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i)
3882 MarkRegAndAliases(AssignedRegs.Regs[i], OutputRegs, TRI);
3883 }
3884 if (isInReg) {
3885 for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i)
3886 MarkRegAndAliases(AssignedRegs.Regs[i], InputRegs, TRI);
3887 }
3888 }
3889
3890private:
3891 /// MarkRegAndAliases - Mark the specified register and all aliases in the
3892 /// specified set.
3893 static void MarkRegAndAliases(unsigned Reg, std::set<unsigned> &Regs,
3894 const TargetRegisterInfo &TRI) {
3895 assert(TargetRegisterInfo::isPhysicalRegister(Reg) && "Isn't a physreg");
3896 Regs.insert(Reg);
3897 if (const unsigned *Aliases = TRI.getAliasSet(Reg))
3898 for (; *Aliases; ++Aliases)
3899 Regs.insert(*Aliases);
3900 }
Chris Lattner0c583402007-04-28 20:49:53 +00003901};
3902} // end anon namespace.
Chris Lattner864635a2006-02-22 22:37:12 +00003903
Chris Lattner3ff90dc2007-04-30 17:16:27 +00003904
Chris Lattner0fe71e92008-02-21 19:43:13 +00003905/// GetRegistersForValue - Assign registers (virtual or physical) for the
3906/// specified operand. We prefer to assign virtual registers, to allow the
3907/// register allocator handle the assignment process. However, if the asm uses
3908/// features that we can't model on machineinstrs, we have SDISel do the
3909/// allocation. This produces generally horrible, but correct, code.
3910///
3911/// OpInfo describes the operand.
3912/// HasEarlyClobber is true if there are any early clobber constraints (=&r)
3913/// or any explicitly clobbered registers.
3914/// Input and OutputRegs are the set of already allocated physical registers.
3915///
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003916void SelectionDAGLowering::
Evan Cheng5c807602008-02-26 02:33:44 +00003917GetRegistersForValue(SDISelAsmOperandInfo &OpInfo, bool HasEarlyClobber,
Chris Lattnerbf996f12007-04-30 17:29:31 +00003918 std::set<unsigned> &OutputRegs,
3919 std::set<unsigned> &InputRegs) {
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003920 // Compute whether this value requires an input register, an output register,
3921 // or both.
3922 bool isOutReg = false;
3923 bool isInReg = false;
3924 switch (OpInfo.Type) {
3925 case InlineAsm::isOutput:
3926 isOutReg = true;
3927
3928 // If this is an early-clobber output, or if there is an input
3929 // constraint that matches this, we need to reserve the input register
3930 // so no other inputs allocate to it.
3931 isInReg = OpInfo.isEarlyClobber || OpInfo.hasMatchingInput;
3932 break;
3933 case InlineAsm::isInput:
3934 isInReg = true;
3935 isOutReg = false;
3936 break;
3937 case InlineAsm::isClobber:
3938 isOutReg = true;
3939 isInReg = true;
3940 break;
3941 }
3942
3943
3944 MachineFunction &MF = DAG.getMachineFunction();
Chris Lattnerb606dba2008-04-28 06:44:42 +00003945 SmallVector<unsigned, 4> Regs;
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003946
3947 // If this is a constraint for a single physreg, or a constraint for a
3948 // register class, find it.
3949 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
3950 TLI.getRegForInlineAsmConstraint(OpInfo.ConstraintCode,
3951 OpInfo.ConstraintVT);
Chris Lattnerbf996f12007-04-30 17:29:31 +00003952
3953 unsigned NumRegs = 1;
3954 if (OpInfo.ConstraintVT != MVT::Other)
Dan Gohmanb9f10192007-06-21 14:42:22 +00003955 NumRegs = TLI.getNumRegisters(OpInfo.ConstraintVT);
Duncan Sands83ec4b62008-06-06 12:08:01 +00003956 MVT RegVT;
3957 MVT ValueVT = OpInfo.ConstraintVT;
Chris Lattnerbf996f12007-04-30 17:29:31 +00003958
Chris Lattnerbf996f12007-04-30 17:29:31 +00003959
3960 // If this is a constraint for a specific physical register, like {r17},
3961 // assign it now.
3962 if (PhysReg.first) {
3963 if (OpInfo.ConstraintVT == MVT::Other)
3964 ValueVT = *PhysReg.second->vt_begin();
3965
3966 // Get the actual register value type. This is important, because the user
3967 // may have asked for (e.g.) the AX register in i32 type. We need to
3968 // remember that AX is actually i16 to get the right extension.
3969 RegVT = *PhysReg.second->vt_begin();
3970
3971 // This is a explicit reference to a physical register.
3972 Regs.push_back(PhysReg.first);
3973
3974 // If this is an expanded reference, add the rest of the regs to Regs.
3975 if (NumRegs != 1) {
3976 TargetRegisterClass::iterator I = PhysReg.second->begin();
Chris Lattnerbf996f12007-04-30 17:29:31 +00003977 for (; *I != PhysReg.first; ++I)
Evan Cheng50871242008-05-14 20:07:51 +00003978 assert(I != PhysReg.second->end() && "Didn't find reg!");
Chris Lattnerbf996f12007-04-30 17:29:31 +00003979
3980 // Already added the first reg.
3981 --NumRegs; ++I;
3982 for (; NumRegs; --NumRegs, ++I) {
Evan Cheng50871242008-05-14 20:07:51 +00003983 assert(I != PhysReg.second->end() && "Ran out of registers to allocate!");
Chris Lattnerbf996f12007-04-30 17:29:31 +00003984 Regs.push_back(*I);
3985 }
3986 }
Dan Gohman23ce5022008-04-25 18:27:55 +00003987 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, RegVT, ValueVT);
Chris Lattner7cbeb242008-02-21 04:55:52 +00003988 const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
3989 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TRI);
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003990 return;
Chris Lattnerbf996f12007-04-30 17:29:31 +00003991 }
3992
3993 // Otherwise, if this was a reference to an LLVM register class, create vregs
3994 // for this reference.
3995 std::vector<unsigned> RegClassRegs;
Chris Lattnerc2c28fc2007-06-15 19:11:01 +00003996 const TargetRegisterClass *RC = PhysReg.second;
3997 if (RC) {
Chris Lattnerbf996f12007-04-30 17:29:31 +00003998 // If this is an early clobber or tied register, our regalloc doesn't know
3999 // how to maintain the constraint. If it isn't, go ahead and create vreg
4000 // and let the regalloc do the right thing.
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004001 if (!OpInfo.hasMatchingInput && !OpInfo.isEarlyClobber &&
4002 // If there is some other early clobber and this is an input register,
4003 // then we are forced to pre-allocate the input reg so it doesn't
4004 // conflict with the earlyclobber.
4005 !(OpInfo.Type == InlineAsm::isInput && HasEarlyClobber)) {
Chris Lattnerbf996f12007-04-30 17:29:31 +00004006 RegVT = *PhysReg.second->vt_begin();
4007
4008 if (OpInfo.ConstraintVT == MVT::Other)
4009 ValueVT = RegVT;
4010
4011 // Create the appropriate number of virtual registers.
Chris Lattner84bc5422007-12-31 04:13:23 +00004012 MachineRegisterInfo &RegInfo = MF.getRegInfo();
Chris Lattnerbf996f12007-04-30 17:29:31 +00004013 for (; NumRegs; --NumRegs)
Chris Lattner84bc5422007-12-31 04:13:23 +00004014 Regs.push_back(RegInfo.createVirtualRegister(PhysReg.second));
Chris Lattnerbf996f12007-04-30 17:29:31 +00004015
Dan Gohman23ce5022008-04-25 18:27:55 +00004016 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, RegVT, ValueVT);
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004017 return;
Chris Lattnerbf996f12007-04-30 17:29:31 +00004018 }
4019
4020 // Otherwise, we can't allocate it. Let the code below figure out how to
4021 // maintain these constraints.
4022 RegClassRegs.assign(PhysReg.second->begin(), PhysReg.second->end());
4023
4024 } else {
4025 // This is a reference to a register class that doesn't directly correspond
4026 // to an LLVM register class. Allocate NumRegs consecutive, available,
4027 // registers from the class.
4028 RegClassRegs = TLI.getRegClassForInlineAsmConstraint(OpInfo.ConstraintCode,
4029 OpInfo.ConstraintVT);
4030 }
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004031
Dan Gohman6f0d0242008-02-10 18:45:23 +00004032 const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
Chris Lattnerbf996f12007-04-30 17:29:31 +00004033 unsigned NumAllocated = 0;
4034 for (unsigned i = 0, e = RegClassRegs.size(); i != e; ++i) {
4035 unsigned Reg = RegClassRegs[i];
4036 // See if this register is available.
4037 if ((isOutReg && OutputRegs.count(Reg)) || // Already used.
4038 (isInReg && InputRegs.count(Reg))) { // Already used.
4039 // Make sure we find consecutive registers.
4040 NumAllocated = 0;
4041 continue;
4042 }
4043
4044 // Check to see if this register is allocatable (i.e. don't give out the
4045 // stack pointer).
Chris Lattnerc2c28fc2007-06-15 19:11:01 +00004046 if (RC == 0) {
Dan Gohman6f0d0242008-02-10 18:45:23 +00004047 RC = isAllocatableRegister(Reg, MF, TLI, TRI);
Chris Lattnerc2c28fc2007-06-15 19:11:01 +00004048 if (!RC) { // Couldn't allocate this register.
4049 // Reset NumAllocated to make sure we return consecutive registers.
4050 NumAllocated = 0;
4051 continue;
4052 }
Chris Lattnerbf996f12007-04-30 17:29:31 +00004053 }
4054
4055 // Okay, this register is good, we can use it.
4056 ++NumAllocated;
4057
4058 // If we allocated enough consecutive registers, succeed.
4059 if (NumAllocated == NumRegs) {
4060 unsigned RegStart = (i-NumAllocated)+1;
4061 unsigned RegEnd = i+1;
4062 // Mark all of the allocated registers used.
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004063 for (unsigned i = RegStart; i != RegEnd; ++i)
4064 Regs.push_back(RegClassRegs[i]);
Chris Lattnerbf996f12007-04-30 17:29:31 +00004065
Dan Gohman23ce5022008-04-25 18:27:55 +00004066 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, *RC->vt_begin(),
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004067 OpInfo.ConstraintVT);
Chris Lattner7cbeb242008-02-21 04:55:52 +00004068 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TRI);
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004069 return;
Chris Lattnerbf996f12007-04-30 17:29:31 +00004070 }
4071 }
4072
4073 // Otherwise, we couldn't allocate enough registers for this.
Chris Lattnerbf996f12007-04-30 17:29:31 +00004074}
4075
4076
Chris Lattnerce7518c2006-01-26 22:24:51 +00004077/// visitInlineAsm - Handle a call to an InlineAsm object.
4078///
Duncan Sandsfd7b3262007-12-17 18:08:19 +00004079void SelectionDAGLowering::visitInlineAsm(CallSite CS) {
4080 InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
Chris Lattnerce7518c2006-01-26 22:24:51 +00004081
Chris Lattner0c583402007-04-28 20:49:53 +00004082 /// ConstraintOperands - Information about all of the constraints.
Evan Cheng5c807602008-02-26 02:33:44 +00004083 std::vector<SDISelAsmOperandInfo> ConstraintOperands;
Chris Lattnerce7518c2006-01-26 22:24:51 +00004084
4085 SDOperand Chain = getRoot();
4086 SDOperand Flag;
4087
Chris Lattner4e4b5762006-02-01 18:59:47 +00004088 std::set<unsigned> OutputRegs, InputRegs;
Chris Lattner1efa40f2006-02-22 00:56:39 +00004089
Chris Lattner0c583402007-04-28 20:49:53 +00004090 // Do a prepass over the constraints, canonicalizing them, and building up the
4091 // ConstraintOperands list.
4092 std::vector<InlineAsm::ConstraintInfo>
4093 ConstraintInfos = IA->ParseConstraints();
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004094
4095 // SawEarlyClobber - Keep track of whether we saw an earlyclobber output
4096 // constraint. If so, we can't let the register allocator allocate any input
4097 // registers, because it will not know to avoid the earlyclobbered output reg.
4098 bool SawEarlyClobber = false;
4099
Duncan Sandsfd7b3262007-12-17 18:08:19 +00004100 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst.
Chris Lattneracf8b012008-04-27 23:44:28 +00004101 unsigned ResNo = 0; // ResNo - The result number of the next output.
Chris Lattner0c583402007-04-28 20:49:53 +00004102 for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) {
Evan Cheng5c807602008-02-26 02:33:44 +00004103 ConstraintOperands.push_back(SDISelAsmOperandInfo(ConstraintInfos[i]));
4104 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
Chris Lattner0c583402007-04-28 20:49:53 +00004105
Duncan Sands83ec4b62008-06-06 12:08:01 +00004106 MVT OpVT = MVT::Other;
Chris Lattner0c583402007-04-28 20:49:53 +00004107
4108 // Compute the value type for each operand.
4109 switch (OpInfo.Type) {
Chris Lattner1efa40f2006-02-22 00:56:39 +00004110 case InlineAsm::isOutput:
Chris Lattneracf8b012008-04-27 23:44:28 +00004111 // Indirect outputs just consume an argument.
4112 if (OpInfo.isIndirect) {
Duncan Sandsfd7b3262007-12-17 18:08:19 +00004113 OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
Chris Lattneracf8b012008-04-27 23:44:28 +00004114 break;
Chris Lattner1efa40f2006-02-22 00:56:39 +00004115 }
Chris Lattneracf8b012008-04-27 23:44:28 +00004116 // The return value of the call is this value. As such, there is no
4117 // corresponding argument.
4118 assert(CS.getType() != Type::VoidTy && "Bad inline asm!");
4119 if (const StructType *STy = dyn_cast<StructType>(CS.getType())) {
4120 OpVT = TLI.getValueType(STy->getElementType(ResNo));
4121 } else {
4122 assert(ResNo == 0 && "Asm only has one result!");
4123 OpVT = TLI.getValueType(CS.getType());
4124 }
4125 ++ResNo;
Chris Lattner1efa40f2006-02-22 00:56:39 +00004126 break;
4127 case InlineAsm::isInput:
Duncan Sandsfd7b3262007-12-17 18:08:19 +00004128 OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
Chris Lattner1efa40f2006-02-22 00:56:39 +00004129 break;
4130 case InlineAsm::isClobber:
Chris Lattner0c583402007-04-28 20:49:53 +00004131 // Nothing to do.
Chris Lattner1efa40f2006-02-22 00:56:39 +00004132 break;
4133 }
Chris Lattner1efa40f2006-02-22 00:56:39 +00004134
Chris Lattner0c583402007-04-28 20:49:53 +00004135 // If this is an input or an indirect output, process the call argument.
Dale Johanneseneb57ea72007-11-05 21:20:28 +00004136 // BasicBlocks are labels, currently appearing only in asm's.
Chris Lattner0c583402007-04-28 20:49:53 +00004137 if (OpInfo.CallOperandVal) {
Chris Lattner507ffd22008-04-27 00:16:18 +00004138 if (BasicBlock *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal))
4139 OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
Dale Johanneseneb57ea72007-11-05 21:20:28 +00004140 else {
4141 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
4142 const Type *OpTy = OpInfo.CallOperandVal->getType();
4143 // If this is an indirect operand, the operand is a pointer to the
4144 // accessed type.
4145 if (OpInfo.isIndirect)
4146 OpTy = cast<PointerType>(OpTy)->getElementType();
4147
Dan Gohman4fa2a3f2008-05-23 00:34:04 +00004148 // If OpTy is not a single value, it may be a struct/union that we
Dale Johanneseneb57ea72007-11-05 21:20:28 +00004149 // can tile with integers.
Dan Gohman4fa2a3f2008-05-23 00:34:04 +00004150 if (!OpTy->isSingleValueType() && OpTy->isSized()) {
Dale Johanneseneb57ea72007-11-05 21:20:28 +00004151 unsigned BitSize = TD->getTypeSizeInBits(OpTy);
4152 switch (BitSize) {
4153 default: break;
4154 case 1:
4155 case 8:
4156 case 16:
4157 case 32:
4158 case 64:
4159 OpTy = IntegerType::get(BitSize);
4160 break;
4161 }
Chris Lattner6995cf62007-04-29 18:58:03 +00004162 }
Dale Johanneseneb57ea72007-11-05 21:20:28 +00004163
4164 OpVT = TLI.getValueType(OpTy, true);
Chris Lattner0c583402007-04-28 20:49:53 +00004165 }
4166 }
4167
4168 OpInfo.ConstraintVT = OpVT;
Chris Lattner2a600be2007-04-28 21:01:43 +00004169
Chris Lattner3ff90dc2007-04-30 17:16:27 +00004170 // Compute the constraint code and ConstraintType to use.
Chris Lattner5a096902008-04-27 00:37:18 +00004171 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
Chris Lattner0c583402007-04-28 20:49:53 +00004172
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004173 // Keep track of whether we see an earlyclobber.
4174 SawEarlyClobber |= OpInfo.isEarlyClobber;
Chris Lattner09e4b7e2007-04-28 21:12:06 +00004175
Chris Lattner0fe71e92008-02-21 19:43:13 +00004176 // If we see a clobber of a register, it is an early clobber.
Chris Lattner69e6a8d2008-02-21 20:54:31 +00004177 if (!SawEarlyClobber &&
4178 OpInfo.Type == InlineAsm::isClobber &&
4179 OpInfo.ConstraintType == TargetLowering::C_Register) {
4180 // Note that we want to ignore things that we don't trick here, like
4181 // dirflag, fpsr, flags, etc.
4182 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
4183 TLI.getRegForInlineAsmConstraint(OpInfo.ConstraintCode,
4184 OpInfo.ConstraintVT);
4185 if (PhysReg.first || PhysReg.second) {
4186 // This is a register we know of.
4187 SawEarlyClobber = true;
4188 }
4189 }
Chris Lattner0fe71e92008-02-21 19:43:13 +00004190
Chris Lattner09e4b7e2007-04-28 21:12:06 +00004191 // If this is a memory input, and if the operand is not indirect, do what we
4192 // need to to provide an address for the memory input.
4193 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
4194 !OpInfo.isIndirect) {
4195 assert(OpInfo.Type == InlineAsm::isInput &&
4196 "Can only indirectify direct input operands!");
4197
4198 // Memory operands really want the address of the value. If we don't have
4199 // an indirect input, put it in the constpool if we can, otherwise spill
4200 // it to a stack slot.
4201
4202 // If the operand is a float, integer, or vector constant, spill to a
4203 // constant pool entry to get its address.
4204 Value *OpVal = OpInfo.CallOperandVal;
4205 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
4206 isa<ConstantVector>(OpVal)) {
4207 OpInfo.CallOperand = DAG.getConstantPool(cast<Constant>(OpVal),
4208 TLI.getPointerTy());
4209 } else {
4210 // Otherwise, create a stack slot and emit a store to it before the
4211 // asm.
4212 const Type *Ty = OpVal->getType();
Duncan Sands514ab342007-11-01 20:53:16 +00004213 uint64_t TySize = TLI.getTargetData()->getABITypeSize(Ty);
Chris Lattner09e4b7e2007-04-28 21:12:06 +00004214 unsigned Align = TLI.getTargetData()->getPrefTypeAlignment(Ty);
4215 MachineFunction &MF = DAG.getMachineFunction();
4216 int SSFI = MF.getFrameInfo()->CreateStackObject(TySize, Align);
4217 SDOperand StackSlot = DAG.getFrameIndex(SSFI, TLI.getPointerTy());
4218 Chain = DAG.getStore(Chain, OpInfo.CallOperand, StackSlot, NULL, 0);
4219 OpInfo.CallOperand = StackSlot;
4220 }
4221
4222 // There is no longer a Value* corresponding to this operand.
4223 OpInfo.CallOperandVal = 0;
4224 // It is now an indirect operand.
4225 OpInfo.isIndirect = true;
4226 }
4227
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004228 // If this constraint is for a specific register, allocate it before
4229 // anything else.
4230 if (OpInfo.ConstraintType == TargetLowering::C_Register)
4231 GetRegistersForValue(OpInfo, SawEarlyClobber, OutputRegs, InputRegs);
Chris Lattner0c583402007-04-28 20:49:53 +00004232 }
Chris Lattner0c583402007-04-28 20:49:53 +00004233 ConstraintInfos.clear();
4234
4235
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004236 // Second pass - Loop over all of the operands, assigning virtual or physregs
4237 // to registerclass operands.
4238 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
Evan Cheng5c807602008-02-26 02:33:44 +00004239 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004240
4241 // C_Register operands have already been allocated, Other/Memory don't need
4242 // to be.
4243 if (OpInfo.ConstraintType == TargetLowering::C_RegisterClass)
4244 GetRegistersForValue(OpInfo, SawEarlyClobber, OutputRegs, InputRegs);
4245 }
4246
Chris Lattner0c583402007-04-28 20:49:53 +00004247 // AsmNodeOperands - The operands for the ISD::INLINEASM node.
4248 std::vector<SDOperand> AsmNodeOperands;
4249 AsmNodeOperands.push_back(SDOperand()); // reserve space for input chain
4250 AsmNodeOperands.push_back(
4251 DAG.getTargetExternalSymbol(IA->getAsmString().c_str(), MVT::Other));
4252
Chris Lattner2cc2f662006-02-01 01:28:23 +00004253
Chris Lattner0f0b7d42006-02-21 23:12:12 +00004254 // Loop over all of the inputs, copying the operand values into the
4255 // appropriate registers and processing the output regs.
Chris Lattner864635a2006-02-22 22:37:12 +00004256 RegsForValue RetValRegs;
Chris Lattner41f62592008-04-29 04:29:54 +00004257
Chris Lattner0c583402007-04-28 20:49:53 +00004258 // IndirectStoresToEmit - The set of stores to emit after the inline asm node.
4259 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
4260
4261 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
Evan Cheng5c807602008-02-26 02:33:44 +00004262 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
Chris Lattner1efa40f2006-02-22 00:56:39 +00004263
Chris Lattner0c583402007-04-28 20:49:53 +00004264 switch (OpInfo.Type) {
Chris Lattner2cc2f662006-02-01 01:28:23 +00004265 case InlineAsm::isOutput: {
Chris Lattnerc83994e2007-04-28 21:03:16 +00004266 if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass &&
4267 OpInfo.ConstraintType != TargetLowering::C_Register) {
Chris Lattnerf2f3cd52007-04-28 06:08:13 +00004268 // Memory output, or 'other' output (e.g. 'X' constraint).
Chris Lattner09e4b7e2007-04-28 21:12:06 +00004269 assert(OpInfo.isIndirect && "Memory output must be indirect operand");
Chris Lattner22873462006-02-27 23:45:39 +00004270
Chris Lattner22873462006-02-27 23:45:39 +00004271 // Add information to the INLINEASM node to know about this output.
4272 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
Chris Lattnerc90233b2007-05-15 01:33:58 +00004273 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
4274 TLI.getPointerTy()));
Chris Lattner09e4b7e2007-04-28 21:12:06 +00004275 AsmNodeOperands.push_back(OpInfo.CallOperand);
Chris Lattner22873462006-02-27 23:45:39 +00004276 break;
4277 }
4278
Chris Lattner2a600be2007-04-28 21:01:43 +00004279 // Otherwise, this is a register or register class output.
Chris Lattner22873462006-02-27 23:45:39 +00004280
Chris Lattner864635a2006-02-22 22:37:12 +00004281 // Copy the output from the appropriate register. Find a register that
Chris Lattner1efa40f2006-02-22 00:56:39 +00004282 // we can use.
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004283 if (OpInfo.AssignedRegs.Regs.empty()) {
Bill Wendling832171c2006-12-07 20:04:42 +00004284 cerr << "Couldn't allocate output reg for contraint '"
Chris Lattner0c583402007-04-28 20:49:53 +00004285 << OpInfo.ConstraintCode << "'!\n";
Chris Lattnerd03f1582006-10-31 07:33:13 +00004286 exit(1);
4287 }
Chris Lattner1efa40f2006-02-22 00:56:39 +00004288
Chris Lattner41f62592008-04-29 04:29:54 +00004289 // If this is an indirect operand, store through the pointer after the
4290 // asm.
4291 if (OpInfo.isIndirect) {
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004292 IndirectStoresToEmit.push_back(std::make_pair(OpInfo.AssignedRegs,
Chris Lattner0c583402007-04-28 20:49:53 +00004293 OpInfo.CallOperandVal));
Chris Lattner41f62592008-04-29 04:29:54 +00004294 } else {
4295 // This is the result value of the call.
4296 assert(CS.getType() != Type::VoidTy && "Bad inline asm!");
4297 // Concatenate this output onto the outputs list.
4298 RetValRegs.append(OpInfo.AssignedRegs);
Chris Lattner2cc2f662006-02-01 01:28:23 +00004299 }
Chris Lattner6656dd12006-01-31 02:03:41 +00004300
4301 // Add information to the INLINEASM node to know that this register is
4302 // set.
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004303 OpInfo.AssignedRegs.AddInlineAsmOperands(2 /*REGDEF*/, DAG,
4304 AsmNodeOperands);
Chris Lattner6656dd12006-01-31 02:03:41 +00004305 break;
4306 }
4307 case InlineAsm::isInput: {
Chris Lattner0c583402007-04-28 20:49:53 +00004308 SDOperand InOperandVal = OpInfo.CallOperand;
Chris Lattner3d81fee2006-02-04 02:16:44 +00004309
Chris Lattner0c583402007-04-28 20:49:53 +00004310 if (isdigit(OpInfo.ConstraintCode[0])) { // Matching constraint?
Chris Lattner2223aea2006-02-02 00:25:23 +00004311 // If this is required to match an output register we have already set,
4312 // just use its register.
Chris Lattner0c583402007-04-28 20:49:53 +00004313 unsigned OperandNo = atoi(OpInfo.ConstraintCode.c_str());
Chris Lattner3d81fee2006-02-04 02:16:44 +00004314
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00004315 // Scan until we find the definition we already emitted of this operand.
4316 // When we find it, create a RegsForValue operand.
4317 unsigned CurOp = 2; // The first operand.
4318 for (; OperandNo; --OperandNo) {
4319 // Advance to the next operand.
4320 unsigned NumOps =
4321 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
Chris Lattnera15cf702006-07-20 19:02:21 +00004322 assert(((NumOps & 7) == 2 /*REGDEF*/ ||
4323 (NumOps & 7) == 4 /*MEM*/) &&
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00004324 "Skipped past definitions?");
4325 CurOp += (NumOps>>3)+1;
4326 }
4327
4328 unsigned NumOps =
4329 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
Chris Lattner527fae12007-02-01 01:21:12 +00004330 if ((NumOps & 7) == 2 /*REGDEF*/) {
4331 // Add NumOps>>3 registers to MatchedRegs.
4332 RegsForValue MatchedRegs;
Dan Gohman23ce5022008-04-25 18:27:55 +00004333 MatchedRegs.TLI = &TLI;
Dan Gohman1fa850b2008-05-02 00:03:54 +00004334 MatchedRegs.ValueVTs.push_back(InOperandVal.getValueType());
4335 MatchedRegs.RegVTs.push_back(AsmNodeOperands[CurOp+1].getValueType());
Chris Lattner527fae12007-02-01 01:21:12 +00004336 for (unsigned i = 0, e = NumOps>>3; i != e; ++i) {
4337 unsigned Reg =
4338 cast<RegisterSDNode>(AsmNodeOperands[++CurOp])->getReg();
4339 MatchedRegs.Regs.push_back(Reg);
4340 }
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00004341
Chris Lattner527fae12007-02-01 01:21:12 +00004342 // Use the produced MatchedRegs object to
Dan Gohmanb6f5b002007-06-28 23:29:44 +00004343 MatchedRegs.getCopyToRegs(InOperandVal, DAG, Chain, &Flag);
Chris Lattner527fae12007-02-01 01:21:12 +00004344 MatchedRegs.AddInlineAsmOperands(1 /*REGUSE*/, DAG, AsmNodeOperands);
4345 break;
4346 } else {
4347 assert((NumOps & 7) == 4/*MEM*/ && "Unknown matching constraint!");
Chris Lattnerf9853bc2008-02-21 05:27:19 +00004348 assert((NumOps >> 3) == 1 && "Unexpected number of operands");
4349 // Add information to the INLINEASM node to know about this input.
4350 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
4351 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
4352 TLI.getPointerTy()));
4353 AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
4354 break;
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00004355 }
Chris Lattner2223aea2006-02-02 00:25:23 +00004356 }
Chris Lattner87bc3bd2006-02-24 01:11:24 +00004357
Chris Lattner2a600be2007-04-28 21:01:43 +00004358 if (OpInfo.ConstraintType == TargetLowering::C_Other) {
Chris Lattner0c583402007-04-28 20:49:53 +00004359 assert(!OpInfo.isIndirect &&
Chris Lattner44b2c502007-04-28 06:42:38 +00004360 "Don't know how to handle indirect other inputs yet!");
4361
Chris Lattner48884cd2007-08-25 00:47:38 +00004362 std::vector<SDOperand> Ops;
4363 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode[0],
4364 Ops, DAG);
4365 if (Ops.empty()) {
Bill Wendling832171c2006-12-07 20:04:42 +00004366 cerr << "Invalid operand for inline asm constraint '"
Chris Lattner0c583402007-04-28 20:49:53 +00004367 << OpInfo.ConstraintCode << "'!\n";
Chris Lattner53069fb2006-10-31 19:41:18 +00004368 exit(1);
4369 }
Chris Lattner87bc3bd2006-02-24 01:11:24 +00004370
4371 // Add information to the INLINEASM node to know about this input.
Chris Lattner48884cd2007-08-25 00:47:38 +00004372 unsigned ResOpType = 3 /*IMM*/ | (Ops.size() << 3);
Chris Lattnerc90233b2007-05-15 01:33:58 +00004373 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
4374 TLI.getPointerTy()));
Chris Lattner48884cd2007-08-25 00:47:38 +00004375 AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end());
Chris Lattner87bc3bd2006-02-24 01:11:24 +00004376 break;
Chris Lattner2a600be2007-04-28 21:01:43 +00004377 } else if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
Chris Lattner09e4b7e2007-04-28 21:12:06 +00004378 assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
Chris Lattner44b2c502007-04-28 06:42:38 +00004379 assert(InOperandVal.getValueType() == TLI.getPointerTy() &&
4380 "Memory operands expect pointer values");
4381
Chris Lattner87bc3bd2006-02-24 01:11:24 +00004382 // Add information to the INLINEASM node to know about this input.
4383 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
Chris Lattnerc90233b2007-05-15 01:33:58 +00004384 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
4385 TLI.getPointerTy()));
Chris Lattner87bc3bd2006-02-24 01:11:24 +00004386 AsmNodeOperands.push_back(InOperandVal);
4387 break;
4388 }
4389
Chris Lattner2a600be2007-04-28 21:01:43 +00004390 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
4391 OpInfo.ConstraintType == TargetLowering::C_Register) &&
4392 "Unknown constraint type!");
Chris Lattner0c583402007-04-28 20:49:53 +00004393 assert(!OpInfo.isIndirect &&
Chris Lattner44b2c502007-04-28 06:42:38 +00004394 "Don't know how to handle indirect register inputs yet!");
Chris Lattner87bc3bd2006-02-24 01:11:24 +00004395
4396 // Copy the input into the appropriate registers.
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004397 assert(!OpInfo.AssignedRegs.Regs.empty() &&
4398 "Couldn't allocate input reg!");
Chris Lattner87bc3bd2006-02-24 01:11:24 +00004399
Dan Gohmanb6f5b002007-06-28 23:29:44 +00004400 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, Chain, &Flag);
Chris Lattner87bc3bd2006-02-24 01:11:24 +00004401
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004402 OpInfo.AssignedRegs.AddInlineAsmOperands(1/*REGUSE*/, DAG,
4403 AsmNodeOperands);
Chris Lattner6656dd12006-01-31 02:03:41 +00004404 break;
4405 }
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00004406 case InlineAsm::isClobber: {
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00004407 // Add the clobbered value to the operand list, so that the register
4408 // allocator is aware that the physreg got clobbered.
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004409 if (!OpInfo.AssignedRegs.Regs.empty())
4410 OpInfo.AssignedRegs.AddInlineAsmOperands(2/*REGDEF*/, DAG,
4411 AsmNodeOperands);
Chris Lattner6656dd12006-01-31 02:03:41 +00004412 break;
4413 }
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00004414 }
Chris Lattner6656dd12006-01-31 02:03:41 +00004415 }
Chris Lattnerce7518c2006-01-26 22:24:51 +00004416
4417 // Finish up input operands.
4418 AsmNodeOperands[0] = Chain;
4419 if (Flag.Val) AsmNodeOperands.push_back(Flag);
4420
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00004421 Chain = DAG.getNode(ISD::INLINEASM,
4422 DAG.getNodeValueTypes(MVT::Other, MVT::Flag), 2,
Chris Lattnerbd564bf2006-08-08 02:23:42 +00004423 &AsmNodeOperands[0], AsmNodeOperands.size());
Chris Lattnerce7518c2006-01-26 22:24:51 +00004424 Flag = Chain.getValue(1);
4425
Chris Lattner6656dd12006-01-31 02:03:41 +00004426 // If this asm returns a register value, copy the result from that register
4427 // and set it as the value of the call.
Chris Lattner3a508c92007-04-12 06:00:20 +00004428 if (!RetValRegs.Regs.empty()) {
Dan Gohmanb6f5b002007-06-28 23:29:44 +00004429 SDOperand Val = RetValRegs.getCopyFromRegs(DAG, Chain, &Flag);
Chris Lattner3fb29682008-04-29 04:48:56 +00004430
4431 // If any of the results of the inline asm is a vector, it may have the
4432 // wrong width/num elts. This can happen for register classes that can
4433 // contain multiple different value types. The preg or vreg allocated may
4434 // not have the same VT as was expected. Convert it to the right type with
Dan Gohman7f321562007-06-25 16:23:39 +00004435 // bit_convert.
Chris Lattner3fb29682008-04-29 04:48:56 +00004436 if (const StructType *ResSTy = dyn_cast<StructType>(CS.getType())) {
4437 for (unsigned i = 0, e = ResSTy->getNumElements(); i != e; ++i) {
Duncan Sands83ec4b62008-06-06 12:08:01 +00004438 if (Val.Val->getValueType(i).isVector())
Chris Lattner3fb29682008-04-29 04:48:56 +00004439 Val = DAG.getNode(ISD::BIT_CONVERT,
4440 TLI.getValueType(ResSTy->getElementType(i)), Val);
4441 }
4442 } else {
Duncan Sands83ec4b62008-06-06 12:08:01 +00004443 if (Val.getValueType().isVector())
Chris Lattner3fb29682008-04-29 04:48:56 +00004444 Val = DAG.getNode(ISD::BIT_CONVERT, TLI.getValueType(CS.getType()),
4445 Val);
Chris Lattner3a508c92007-04-12 06:00:20 +00004446 }
Chris Lattner3fb29682008-04-29 04:48:56 +00004447
Duncan Sandsfd7b3262007-12-17 18:08:19 +00004448 setValue(CS.getInstruction(), Val);
Chris Lattner3a508c92007-04-12 06:00:20 +00004449 }
Chris Lattnerce7518c2006-01-26 22:24:51 +00004450
Chris Lattner6656dd12006-01-31 02:03:41 +00004451 std::vector<std::pair<SDOperand, Value*> > StoresToEmit;
4452
4453 // Process indirect outputs, first output all of the flagged copies out of
4454 // physregs.
4455 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
Chris Lattner864635a2006-02-22 22:37:12 +00004456 RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
Chris Lattner6656dd12006-01-31 02:03:41 +00004457 Value *Ptr = IndirectStoresToEmit[i].second;
Dan Gohmanb6f5b002007-06-28 23:29:44 +00004458 SDOperand OutVal = OutRegs.getCopyFromRegs(DAG, Chain, &Flag);
Chris Lattner864635a2006-02-22 22:37:12 +00004459 StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
Chris Lattner6656dd12006-01-31 02:03:41 +00004460 }
4461
4462 // Emit the non-flagged stores from the physregs.
Chris Lattnerbd564bf2006-08-08 02:23:42 +00004463 SmallVector<SDOperand, 8> OutChains;
Chris Lattner6656dd12006-01-31 02:03:41 +00004464 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i)
Chris Lattner0c583402007-04-28 20:49:53 +00004465 OutChains.push_back(DAG.getStore(Chain, StoresToEmit[i].first,
Chris Lattner6656dd12006-01-31 02:03:41 +00004466 getValue(StoresToEmit[i].second),
Evan Cheng8b2794a2006-10-13 21:14:26 +00004467 StoresToEmit[i].second, 0));
Chris Lattner6656dd12006-01-31 02:03:41 +00004468 if (!OutChains.empty())
Chris Lattnerbd564bf2006-08-08 02:23:42 +00004469 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
4470 &OutChains[0], OutChains.size());
Chris Lattnerce7518c2006-01-26 22:24:51 +00004471 DAG.setRoot(Chain);
4472}
4473
4474
Chris Lattner1c08c712005-01-07 07:47:53 +00004475void SelectionDAGLowering::visitMalloc(MallocInst &I) {
4476 SDOperand Src = getValue(I.getOperand(0));
4477
Duncan Sands83ec4b62008-06-06 12:08:01 +00004478 MVT IntPtr = TLI.getPointerTy();
Chris Lattner68cd65e2005-01-22 23:04:37 +00004479
Duncan Sands8e4eb092008-06-08 20:54:56 +00004480 if (IntPtr.bitsLT(Src.getValueType()))
Chris Lattner68cd65e2005-01-22 23:04:37 +00004481 Src = DAG.getNode(ISD::TRUNCATE, IntPtr, Src);
Duncan Sands8e4eb092008-06-08 20:54:56 +00004482 else if (IntPtr.bitsGT(Src.getValueType()))
Chris Lattner68cd65e2005-01-22 23:04:37 +00004483 Src = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, Src);
Chris Lattner1c08c712005-01-07 07:47:53 +00004484
4485 // Scale the source by the type size.
Duncan Sands514ab342007-11-01 20:53:16 +00004486 uint64_t ElementSize = TD->getABITypeSize(I.getType()->getElementType());
Chris Lattner1c08c712005-01-07 07:47:53 +00004487 Src = DAG.getNode(ISD::MUL, Src.getValueType(),
Chris Lattner0bd48932008-01-17 07:00:52 +00004488 Src, DAG.getIntPtrConstant(ElementSize));
Chris Lattner1c08c712005-01-07 07:47:53 +00004489
Reid Spencer47857812006-12-31 05:55:36 +00004490 TargetLowering::ArgListTy Args;
4491 TargetLowering::ArgListEntry Entry;
4492 Entry.Node = Src;
4493 Entry.Ty = TLI.getTargetData()->getIntPtrType();
Reid Spencer47857812006-12-31 05:55:36 +00004494 Args.push_back(Entry);
Chris Lattnercf5734d2005-01-08 19:26:18 +00004495
4496 std::pair<SDOperand,SDOperand> Result =
Duncan Sands00fee652008-02-14 17:28:50 +00004497 TLI.LowerCallTo(getRoot(), I.getType(), false, false, false, CallingConv::C,
4498 true, DAG.getExternalSymbol("malloc", IntPtr), Args, DAG);
Chris Lattnercf5734d2005-01-08 19:26:18 +00004499 setValue(&I, Result.first); // Pointers always fit in registers
4500 DAG.setRoot(Result.second);
Chris Lattner1c08c712005-01-07 07:47:53 +00004501}
4502
4503void SelectionDAGLowering::visitFree(FreeInst &I) {
Reid Spencer47857812006-12-31 05:55:36 +00004504 TargetLowering::ArgListTy Args;
4505 TargetLowering::ArgListEntry Entry;
4506 Entry.Node = getValue(I.getOperand(0));
4507 Entry.Ty = TLI.getTargetData()->getIntPtrType();
Reid Spencer47857812006-12-31 05:55:36 +00004508 Args.push_back(Entry);
Duncan Sands83ec4b62008-06-06 12:08:01 +00004509 MVT IntPtr = TLI.getPointerTy();
Chris Lattnercf5734d2005-01-08 19:26:18 +00004510 std::pair<SDOperand,SDOperand> Result =
Duncan Sands00fee652008-02-14 17:28:50 +00004511 TLI.LowerCallTo(getRoot(), Type::VoidTy, false, false, false,
4512 CallingConv::C, true,
Chris Lattnercf5734d2005-01-08 19:26:18 +00004513 DAG.getExternalSymbol("free", IntPtr), Args, DAG);
4514 DAG.setRoot(Result.second);
Chris Lattner1c08c712005-01-07 07:47:53 +00004515}
4516
Evan Chengff9b3732008-01-30 18:18:23 +00004517// EmitInstrWithCustomInserter - This method should be implemented by targets
4518// that mark instructions with the 'usesCustomDAGSchedInserter' flag. These
Chris Lattner025c39b2005-08-26 20:54:47 +00004519// instructions are special in various ways, which require special support to
4520// insert. The specified MachineInstr is created but not inserted into any
4521// basic blocks, and the scheduler passes ownership of it to this method.
Evan Chengff9b3732008-01-30 18:18:23 +00004522MachineBasicBlock *TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
Chris Lattner025c39b2005-08-26 20:54:47 +00004523 MachineBasicBlock *MBB) {
Bill Wendling832171c2006-12-07 20:04:42 +00004524 cerr << "If a target marks an instruction with "
4525 << "'usesCustomDAGSchedInserter', it must implement "
Evan Chengff9b3732008-01-30 18:18:23 +00004526 << "TargetLowering::EmitInstrWithCustomInserter!\n";
Chris Lattner025c39b2005-08-26 20:54:47 +00004527 abort();
4528 return 0;
4529}
4530
Chris Lattner39ae3622005-01-09 00:00:49 +00004531void SelectionDAGLowering::visitVAStart(CallInst &I) {
Nate Begemanacc398c2006-01-25 18:21:52 +00004532 DAG.setRoot(DAG.getNode(ISD::VASTART, MVT::Other, getRoot(),
4533 getValue(I.getOperand(1)),
4534 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner39ae3622005-01-09 00:00:49 +00004535}
4536
4537void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
Nate Begemanacc398c2006-01-25 18:21:52 +00004538 SDOperand V = DAG.getVAArg(TLI.getValueType(I.getType()), getRoot(),
4539 getValue(I.getOperand(0)),
4540 DAG.getSrcValue(I.getOperand(0)));
4541 setValue(&I, V);
4542 DAG.setRoot(V.getValue(1));
Chris Lattner1c08c712005-01-07 07:47:53 +00004543}
4544
4545void SelectionDAGLowering::visitVAEnd(CallInst &I) {
Nate Begemanacc398c2006-01-25 18:21:52 +00004546 DAG.setRoot(DAG.getNode(ISD::VAEND, MVT::Other, getRoot(),
4547 getValue(I.getOperand(1)),
4548 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner1c08c712005-01-07 07:47:53 +00004549}
4550
4551void SelectionDAGLowering::visitVACopy(CallInst &I) {
Nate Begemanacc398c2006-01-25 18:21:52 +00004552 DAG.setRoot(DAG.getNode(ISD::VACOPY, MVT::Other, getRoot(),
4553 getValue(I.getOperand(1)),
4554 getValue(I.getOperand(2)),
4555 DAG.getSrcValue(I.getOperand(1)),
4556 DAG.getSrcValue(I.getOperand(2))));
Chris Lattner1c08c712005-01-07 07:47:53 +00004557}
4558
Chris Lattnerfdfded52006-04-12 16:20:43 +00004559/// TargetLowering::LowerArguments - This is the default LowerArguments
4560/// implementation, which just inserts a FORMAL_ARGUMENTS node. FIXME: When all
Chris Lattnerf4ec8172006-05-16 22:53:20 +00004561/// targets are migrated to using FORMAL_ARGUMENTS, this hook should be
4562/// integrated into SDISel.
Chris Lattnerfdfded52006-04-12 16:20:43 +00004563std::vector<SDOperand>
4564TargetLowering::LowerArguments(Function &F, SelectionDAG &DAG) {
4565 // Add CC# and isVararg as operands to the FORMAL_ARGUMENTS node.
4566 std::vector<SDOperand> Ops;
Chris Lattner8c0c10c2006-05-16 06:45:34 +00004567 Ops.push_back(DAG.getRoot());
Chris Lattnerfdfded52006-04-12 16:20:43 +00004568 Ops.push_back(DAG.getConstant(F.getCallingConv(), getPointerTy()));
4569 Ops.push_back(DAG.getConstant(F.isVarArg(), getPointerTy()));
4570
4571 // Add one result value for each formal argument.
Duncan Sands83ec4b62008-06-06 12:08:01 +00004572 std::vector<MVT> RetVals;
Anton Korobeynikov6aa279d2007-01-28 18:01:49 +00004573 unsigned j = 1;
Anton Korobeynikovac2b2cf2007-01-28 16:04:40 +00004574 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end();
4575 I != E; ++I, ++j) {
Dan Gohmanf5025cf2008-06-09 21:19:23 +00004576 SmallVector<MVT, 4> ValueVTs;
4577 ComputeValueVTs(*this, I->getType(), ValueVTs);
4578 for (unsigned Value = 0, NumValues = ValueVTs.size();
4579 Value != NumValues; ++Value) {
4580 MVT VT = ValueVTs[Value];
4581 const Type *ArgTy = VT.getTypeForMVT();
4582 ISD::ArgFlagsTy Flags;
4583 unsigned OriginalAlignment =
4584 getTargetData()->getABITypeAlignment(ArgTy);
Lauro Ramos Venancio7aa47b62007-02-13 13:50:08 +00004585
Dan Gohmanf5025cf2008-06-09 21:19:23 +00004586 if (F.paramHasAttr(j, ParamAttr::ZExt))
4587 Flags.setZExt();
4588 if (F.paramHasAttr(j, ParamAttr::SExt))
4589 Flags.setSExt();
4590 if (F.paramHasAttr(j, ParamAttr::InReg))
4591 Flags.setInReg();
4592 if (F.paramHasAttr(j, ParamAttr::StructRet))
4593 Flags.setSRet();
4594 if (F.paramHasAttr(j, ParamAttr::ByVal)) {
4595 Flags.setByVal();
4596 const PointerType *Ty = cast<PointerType>(I->getType());
4597 const Type *ElementTy = Ty->getElementType();
4598 unsigned FrameAlign = getByValTypeAlignment(ElementTy);
4599 unsigned FrameSize = getTargetData()->getABITypeSize(ElementTy);
4600 // For ByVal, alignment should be passed from FE. BE will guess if
4601 // this info is not there but there are cases it cannot get right.
4602 if (F.getParamAlignment(j))
4603 FrameAlign = F.getParamAlignment(j);
4604 Flags.setByValAlign(FrameAlign);
4605 Flags.setByValSize(FrameSize);
4606 }
4607 if (F.paramHasAttr(j, ParamAttr::Nest))
4608 Flags.setNest();
4609 Flags.setOrigAlign(OriginalAlignment);
Duncan Sandsb988bac2008-02-11 20:58:28 +00004610
Dan Gohmanf5025cf2008-06-09 21:19:23 +00004611 MVT RegisterVT = getRegisterType(VT);
4612 unsigned NumRegs = getNumRegisters(VT);
4613 for (unsigned i = 0; i != NumRegs; ++i) {
4614 RetVals.push_back(RegisterVT);
4615 ISD::ArgFlagsTy MyFlags = Flags;
4616 if (NumRegs > 1 && i == 0)
4617 MyFlags.setSplit();
4618 // if it isn't first piece, alignment must be 1
4619 else if (i > 0)
4620 MyFlags.setOrigAlign(1);
4621 Ops.push_back(DAG.getArgFlags(MyFlags));
4622 }
Dan Gohmanb6f5b002007-06-28 23:29:44 +00004623 }
Chris Lattnerfdfded52006-04-12 16:20:43 +00004624 }
Evan Cheng3b0d2862006-04-25 23:03:35 +00004625
Chris Lattner8c0c10c2006-05-16 06:45:34 +00004626 RetVals.push_back(MVT::Other);
Chris Lattnerfdfded52006-04-12 16:20:43 +00004627
4628 // Create the node.
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00004629 SDNode *Result = DAG.getNode(ISD::FORMAL_ARGUMENTS,
Chris Lattner86ca3ca2008-02-13 07:39:09 +00004630 DAG.getVTList(&RetVals[0], RetVals.size()),
Chris Lattnerbd564bf2006-08-08 02:23:42 +00004631 &Ops[0], Ops.size()).Val;
Chris Lattner86ca3ca2008-02-13 07:39:09 +00004632
4633 // Prelower FORMAL_ARGUMENTS. This isn't required for functionality, but
4634 // allows exposing the loads that may be part of the argument access to the
4635 // first DAGCombiner pass.
4636 SDOperand TmpRes = LowerOperation(SDOperand(Result, 0), DAG);
4637
4638 // The number of results should match up, except that the lowered one may have
4639 // an extra flag result.
4640 assert((Result->getNumValues() == TmpRes.Val->getNumValues() ||
4641 (Result->getNumValues()+1 == TmpRes.Val->getNumValues() &&
4642 TmpRes.getValue(Result->getNumValues()).getValueType() == MVT::Flag))
4643 && "Lowering produced unexpected number of results!");
4644 Result = TmpRes.Val;
4645
Dan Gohman27a70be2007-07-02 16:18:06 +00004646 unsigned NumArgRegs = Result->getNumValues() - 1;
4647 DAG.setRoot(SDOperand(Result, NumArgRegs));
Chris Lattnerfdfded52006-04-12 16:20:43 +00004648
4649 // Set up the return result vector.
4650 Ops.clear();
4651 unsigned i = 0;
Reid Spencer47857812006-12-31 05:55:36 +00004652 unsigned Idx = 1;
4653 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E;
4654 ++I, ++Idx) {
Dan Gohmanf5025cf2008-06-09 21:19:23 +00004655 SmallVector<MVT, 4> ValueVTs;
4656 ComputeValueVTs(*this, I->getType(), ValueVTs);
4657 for (unsigned Value = 0, NumValues = ValueVTs.size();
4658 Value != NumValues; ++Value) {
4659 MVT VT = ValueVTs[Value];
4660 MVT PartVT = getRegisterType(VT);
Duncan Sandsb988bac2008-02-11 20:58:28 +00004661
Dan Gohmanf5025cf2008-06-09 21:19:23 +00004662 unsigned NumParts = getNumRegisters(VT);
4663 SmallVector<SDOperand, 4> Parts(NumParts);
4664 for (unsigned j = 0; j != NumParts; ++j)
4665 Parts[j] = SDOperand(Result, i++);
Duncan Sandsb988bac2008-02-11 20:58:28 +00004666
Dan Gohmanf5025cf2008-06-09 21:19:23 +00004667 ISD::NodeType AssertOp = ISD::DELETED_NODE;
4668 if (F.paramHasAttr(Idx, ParamAttr::SExt))
4669 AssertOp = ISD::AssertSext;
4670 else if (F.paramHasAttr(Idx, ParamAttr::ZExt))
4671 AssertOp = ISD::AssertZext;
Duncan Sandsb988bac2008-02-11 20:58:28 +00004672
Dan Gohmanf5025cf2008-06-09 21:19:23 +00004673 Ops.push_back(getCopyFromParts(DAG, &Parts[0], NumParts, PartVT, VT,
4674 AssertOp));
4675 }
Chris Lattnerfdfded52006-04-12 16:20:43 +00004676 }
Dan Gohman27a70be2007-07-02 16:18:06 +00004677 assert(i == NumArgRegs && "Argument register count mismatch!");
Chris Lattnerfdfded52006-04-12 16:20:43 +00004678 return Ops;
4679}
4680
Chris Lattnerf4ec8172006-05-16 22:53:20 +00004681
4682/// TargetLowering::LowerCallTo - This is the default LowerCallTo
4683/// implementation, which just inserts an ISD::CALL node, which is later custom
4684/// lowered by the target to something concrete. FIXME: When all targets are
4685/// migrated to using ISD::CALL, this hook should be integrated into SDISel.
4686std::pair<SDOperand, SDOperand>
Duncan Sands00fee652008-02-14 17:28:50 +00004687TargetLowering::LowerCallTo(SDOperand Chain, const Type *RetTy,
4688 bool RetSExt, bool RetZExt, bool isVarArg,
4689 unsigned CallingConv, bool isTailCall,
Chris Lattnerf4ec8172006-05-16 22:53:20 +00004690 SDOperand Callee,
4691 ArgListTy &Args, SelectionDAG &DAG) {
Chris Lattnerbe384162006-08-16 22:57:46 +00004692 SmallVector<SDOperand, 32> Ops;
Chris Lattnerf4ec8172006-05-16 22:53:20 +00004693 Ops.push_back(Chain); // Op#0 - Chain
4694 Ops.push_back(DAG.getConstant(CallingConv, getPointerTy())); // Op#1 - CC
4695 Ops.push_back(DAG.getConstant(isVarArg, getPointerTy())); // Op#2 - VarArg
4696 Ops.push_back(DAG.getConstant(isTailCall, getPointerTy())); // Op#3 - Tail
4697 Ops.push_back(Callee);
4698
4699 // Handle all of the outgoing arguments.
4700 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
Dan Gohmanf5025cf2008-06-09 21:19:23 +00004701 SmallVector<MVT, 4> ValueVTs;
4702 ComputeValueVTs(*this, Args[i].Ty, ValueVTs);
4703 for (unsigned Value = 0, NumValues = ValueVTs.size();
4704 Value != NumValues; ++Value) {
4705 MVT VT = ValueVTs[Value];
4706 const Type *ArgTy = VT.getTypeForMVT();
4707 SDOperand Op = SDOperand(Args[i].Node.Val, Args[i].Node.ResNo + Value);
4708 ISD::ArgFlagsTy Flags;
4709 unsigned OriginalAlignment =
4710 getTargetData()->getABITypeAlignment(ArgTy);
Duncan Sands276dcbd2008-03-21 09:14:45 +00004711
Dan Gohmanf5025cf2008-06-09 21:19:23 +00004712 if (Args[i].isZExt)
4713 Flags.setZExt();
4714 if (Args[i].isSExt)
4715 Flags.setSExt();
4716 if (Args[i].isInReg)
4717 Flags.setInReg();
4718 if (Args[i].isSRet)
4719 Flags.setSRet();
4720 if (Args[i].isByVal) {
4721 Flags.setByVal();
4722 const PointerType *Ty = cast<PointerType>(Args[i].Ty);
4723 const Type *ElementTy = Ty->getElementType();
4724 unsigned FrameAlign = getByValTypeAlignment(ElementTy);
4725 unsigned FrameSize = getTargetData()->getABITypeSize(ElementTy);
4726 // For ByVal, alignment should come from FE. BE will guess if this
4727 // info is not there but there are cases it cannot get right.
4728 if (Args[i].Alignment)
4729 FrameAlign = Args[i].Alignment;
4730 Flags.setByValAlign(FrameAlign);
4731 Flags.setByValSize(FrameSize);
4732 }
4733 if (Args[i].isNest)
4734 Flags.setNest();
4735 Flags.setOrigAlign(OriginalAlignment);
Dan Gohman27a70be2007-07-02 16:18:06 +00004736
Dan Gohmanf5025cf2008-06-09 21:19:23 +00004737 MVT PartVT = getRegisterType(VT);
4738 unsigned NumParts = getNumRegisters(VT);
4739 SmallVector<SDOperand, 4> Parts(NumParts);
4740 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
Duncan Sandsb988bac2008-02-11 20:58:28 +00004741
Dan Gohmanf5025cf2008-06-09 21:19:23 +00004742 if (Args[i].isSExt)
4743 ExtendKind = ISD::SIGN_EXTEND;
4744 else if (Args[i].isZExt)
4745 ExtendKind = ISD::ZERO_EXTEND;
Duncan Sandsb988bac2008-02-11 20:58:28 +00004746
Dan Gohmanf5025cf2008-06-09 21:19:23 +00004747 getCopyToParts(DAG, Op, &Parts[0], NumParts, PartVT, ExtendKind);
Duncan Sandsb988bac2008-02-11 20:58:28 +00004748
Dan Gohmanf5025cf2008-06-09 21:19:23 +00004749 for (unsigned i = 0; i != NumParts; ++i) {
4750 // if it isn't first piece, alignment must be 1
4751 ISD::ArgFlagsTy MyFlags = Flags;
4752 if (NumParts > 1 && i == 0)
4753 MyFlags.setSplit();
4754 else if (i != 0)
4755 MyFlags.setOrigAlign(1);
Duncan Sandsb988bac2008-02-11 20:58:28 +00004756
Dan Gohmanf5025cf2008-06-09 21:19:23 +00004757 Ops.push_back(Parts[i]);
4758 Ops.push_back(DAG.getArgFlags(MyFlags));
4759 }
Dan Gohman27a70be2007-07-02 16:18:06 +00004760 }
Chris Lattnerf4ec8172006-05-16 22:53:20 +00004761 }
4762
Dan Gohmanef5d1942008-03-11 21:11:25 +00004763 // Figure out the result value types. We start by making a list of
Dan Gohman23ce5022008-04-25 18:27:55 +00004764 // the potentially illegal return value types.
Duncan Sands83ec4b62008-06-06 12:08:01 +00004765 SmallVector<MVT, 4> LoweredRetTys;
4766 SmallVector<MVT, 4> RetTys;
Dan Gohman23ce5022008-04-25 18:27:55 +00004767 ComputeValueVTs(*this, RetTy, RetTys);
Dan Gohmanef5d1942008-03-11 21:11:25 +00004768
Dan Gohman23ce5022008-04-25 18:27:55 +00004769 // Then we translate that to a list of legal types.
4770 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
Duncan Sands83ec4b62008-06-06 12:08:01 +00004771 MVT VT = RetTys[I];
4772 MVT RegisterVT = getRegisterType(VT);
Dan Gohmanef5d1942008-03-11 21:11:25 +00004773 unsigned NumRegs = getNumRegisters(VT);
4774 for (unsigned i = 0; i != NumRegs; ++i)
4775 LoweredRetTys.push_back(RegisterVT);
4776 }
Chris Lattnerf4ec8172006-05-16 22:53:20 +00004777
Dan Gohmanef5d1942008-03-11 21:11:25 +00004778 LoweredRetTys.push_back(MVT::Other); // Always has a chain.
Chris Lattnerf4ec8172006-05-16 22:53:20 +00004779
Dan Gohmanb6f5b002007-06-28 23:29:44 +00004780 // Create the CALL node.
Chris Lattnerbe384162006-08-16 22:57:46 +00004781 SDOperand Res = DAG.getNode(ISD::CALL,
Dan Gohmanef5d1942008-03-11 21:11:25 +00004782 DAG.getVTList(&LoweredRetTys[0],
4783 LoweredRetTys.size()),
Chris Lattnerbe384162006-08-16 22:57:46 +00004784 &Ops[0], Ops.size());
Dan Gohmanef5d1942008-03-11 21:11:25 +00004785 Chain = Res.getValue(LoweredRetTys.size() - 1);
Dan Gohmanb6f5b002007-06-28 23:29:44 +00004786
4787 // Gather up the call result into a single value.
4788 if (RetTy != Type::VoidTy) {
Duncan Sands00fee652008-02-14 17:28:50 +00004789 ISD::NodeType AssertOp = ISD::DELETED_NODE;
4790
4791 if (RetSExt)
4792 AssertOp = ISD::AssertSext;
4793 else if (RetZExt)
Dan Gohmanb6f5b002007-06-28 23:29:44 +00004794 AssertOp = ISD::AssertZext;
Duncan Sands00fee652008-02-14 17:28:50 +00004795
Dan Gohmanef5d1942008-03-11 21:11:25 +00004796 SmallVector<SDOperand, 4> ReturnValues;
4797 unsigned RegNo = 0;
Dan Gohman23ce5022008-04-25 18:27:55 +00004798 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
Duncan Sands83ec4b62008-06-06 12:08:01 +00004799 MVT VT = RetTys[I];
4800 MVT RegisterVT = getRegisterType(VT);
Dan Gohmanef5d1942008-03-11 21:11:25 +00004801 unsigned NumRegs = getNumRegisters(VT);
4802 unsigned RegNoEnd = NumRegs + RegNo;
4803 SmallVector<SDOperand, 4> Results;
4804 for (; RegNo != RegNoEnd; ++RegNo)
4805 Results.push_back(Res.getValue(RegNo));
4806 SDOperand ReturnValue =
4807 getCopyFromParts(DAG, &Results[0], NumRegs, RegisterVT, VT,
4808 AssertOp);
4809 ReturnValues.push_back(ReturnValue);
4810 }
4811 Res = ReturnValues.size() == 1 ? ReturnValues.front() :
4812 DAG.getNode(ISD::MERGE_VALUES,
4813 DAG.getVTList(&RetTys[0], RetTys.size()),
4814 &ReturnValues[0], ReturnValues.size());
Chris Lattnerf4ec8172006-05-16 22:53:20 +00004815 }
Dan Gohmanb6f5b002007-06-28 23:29:44 +00004816
4817 return std::make_pair(Res, Chain);
Chris Lattnerf4ec8172006-05-16 22:53:20 +00004818}
4819
Chris Lattner50381b62005-05-14 05:50:48 +00004820SDOperand TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
Chris Lattner171453a2005-01-16 07:28:41 +00004821 assert(0 && "LowerOperation not implemented for this target!");
4822 abort();
Misha Brukmand3f03e42005-02-17 21:39:27 +00004823 return SDOperand();
Chris Lattner171453a2005-01-16 07:28:41 +00004824}
4825
Nate Begeman0aed7842006-01-28 03:14:31 +00004826SDOperand TargetLowering::CustomPromoteOperation(SDOperand Op,
4827 SelectionDAG &DAG) {
4828 assert(0 && "CustomPromoteOperation not implemented for this target!");
4829 abort();
4830 return SDOperand();
4831}
4832
Chris Lattner7041ee32005-01-11 05:56:49 +00004833//===----------------------------------------------------------------------===//
4834// SelectionDAGISel code
4835//===----------------------------------------------------------------------===//
Chris Lattner1c08c712005-01-07 07:47:53 +00004836
Duncan Sands83ec4b62008-06-06 12:08:01 +00004837unsigned SelectionDAGISel::MakeReg(MVT VT) {
Chris Lattner84bc5422007-12-31 04:13:23 +00004838 return RegInfo->createVirtualRegister(TLI.getRegClassFor(VT));
Chris Lattner1c08c712005-01-07 07:47:53 +00004839}
4840
Chris Lattner495a0b52005-08-17 06:37:43 +00004841void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const {
Jim Laskeyc7c3f112006-10-16 20:52:31 +00004842 AU.addRequired<AliasAnalysis>();
Gordon Henriksence224772008-01-07 01:30:38 +00004843 AU.addRequired<CollectorModuleMetadata>();
Chris Lattnerc8d288f2007-03-31 04:18:03 +00004844 AU.setPreservesAll();
Chris Lattner495a0b52005-08-17 06:37:43 +00004845}
Chris Lattner1c08c712005-01-07 07:47:53 +00004846
Chris Lattner1c08c712005-01-07 07:47:53 +00004847bool SelectionDAGISel::runOnFunction(Function &Fn) {
Dan Gohman5f43f922007-08-27 16:26:13 +00004848 // Get alias analysis for load/store combining.
4849 AA = &getAnalysis<AliasAnalysis>();
4850
Chris Lattner1c08c712005-01-07 07:47:53 +00004851 MachineFunction &MF = MachineFunction::construct(&Fn, TLI.getTargetMachine());
Gordon Henriksence224772008-01-07 01:30:38 +00004852 if (MF.getFunction()->hasCollector())
4853 GCI = &getAnalysis<CollectorModuleMetadata>().get(*MF.getFunction());
4854 else
4855 GCI = 0;
Chris Lattner84bc5422007-12-31 04:13:23 +00004856 RegInfo = &MF.getRegInfo();
Bill Wendling832171c2006-12-07 20:04:42 +00004857 DOUT << "\n\n\n=== " << Fn.getName() << "\n";
Chris Lattner1c08c712005-01-07 07:47:53 +00004858
4859 FunctionLoweringInfo FuncInfo(TLI, Fn, MF);
4860
Dale Johannesen1532f3d2008-04-02 00:25:04 +00004861 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
4862 if (InvokeInst *Invoke = dyn_cast<InvokeInst>(I->getTerminator()))
4863 // Mark landing pad.
4864 FuncInfo.MBBMap[Invoke->getSuccessor(1)]->setIsLandingPad();
Duncan Sands9fac0b52007-06-06 10:05:18 +00004865
4866 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
Chris Lattner1c08c712005-01-07 07:47:53 +00004867 SelectBasicBlock(I, MF, FuncInfo);
Misha Brukmanedf128a2005-04-21 22:36:52 +00004868
Evan Chengad2070c2007-02-10 02:43:39 +00004869 // Add function live-ins to entry block live-in set.
4870 BasicBlock *EntryBB = &Fn.getEntryBlock();
4871 BB = FuncInfo.MBBMap[EntryBB];
Chris Lattner84bc5422007-12-31 04:13:23 +00004872 if (!RegInfo->livein_empty())
4873 for (MachineRegisterInfo::livein_iterator I = RegInfo->livein_begin(),
4874 E = RegInfo->livein_end(); I != E; ++I)
Evan Chengad2070c2007-02-10 02:43:39 +00004875 BB->addLiveIn(I->first);
4876
Duncan Sandsf4070822007-06-15 19:04:19 +00004877#ifndef NDEBUG
4878 assert(FuncInfo.CatchInfoFound.size() == FuncInfo.CatchInfoLost.size() &&
4879 "Not all catch info was assigned to a landing pad!");
4880#endif
4881
Chris Lattner1c08c712005-01-07 07:47:53 +00004882 return true;
4883}
4884
Chris Lattner6833b062008-04-28 07:16:35 +00004885void SelectionDAGLowering::CopyValueToVirtualRegister(Value *V, unsigned Reg) {
Chris Lattner571e4342006-10-27 21:36:01 +00004886 SDOperand Op = getValue(V);
Chris Lattner18c2f132005-01-13 20:50:02 +00004887 assert((Op.getOpcode() != ISD::CopyFromReg ||
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00004888 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
Chris Lattner18c2f132005-01-13 20:50:02 +00004889 "Copy from a reg to the same reg!");
Dan Gohman86e1ebf2008-03-27 19:56:19 +00004890 assert(!TargetRegisterInfo::isPhysicalRegister(Reg) && "Is a physreg");
Dan Gohmanb6f5b002007-06-28 23:29:44 +00004891
Dan Gohman23ce5022008-04-25 18:27:55 +00004892 RegsForValue RFV(TLI, Reg, V->getType());
4893 SDOperand Chain = DAG.getEntryNode();
4894 RFV.getCopyToRegs(Op, DAG, Chain, 0);
4895 PendingExports.push_back(Chain);
Chris Lattner1c08c712005-01-07 07:47:53 +00004896}
4897
Chris Lattner068a81e2005-01-17 17:15:02 +00004898void SelectionDAGISel::
Dan Gohman86e1ebf2008-03-27 19:56:19 +00004899LowerArguments(BasicBlock *LLVMBB, SelectionDAGLowering &SDL) {
Chris Lattner068a81e2005-01-17 17:15:02 +00004900 // If this is the entry block, emit arguments.
Evan Cheng15699fc2007-02-10 01:08:18 +00004901 Function &F = *LLVMBB->getParent();
Chris Lattner0afa8e32005-01-17 17:55:19 +00004902 FunctionLoweringInfo &FuncInfo = SDL.FuncInfo;
Chris Lattnerbf209482005-10-30 19:42:35 +00004903 SDOperand OldRoot = SDL.DAG.getRoot();
4904 std::vector<SDOperand> Args = TLI.LowerArguments(F, SDL.DAG);
Chris Lattner068a81e2005-01-17 17:15:02 +00004905
Chris Lattnerbf209482005-10-30 19:42:35 +00004906 unsigned a = 0;
4907 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
Dan Gohmanf5025cf2008-06-09 21:19:23 +00004908 AI != E; ++AI) {
4909 SmallVector<MVT, 4> ValueVTs;
4910 ComputeValueVTs(TLI, AI->getType(), ValueVTs);
4911 unsigned NumValues = ValueVTs.size();
Chris Lattnerbf209482005-10-30 19:42:35 +00004912 if (!AI->use_empty()) {
Dan Gohmanf5025cf2008-06-09 21:19:23 +00004913 SmallVector<MVT, 4> LegalValueVTs(NumValues);
4914 for (unsigned VI = 0; VI != NumValues; ++VI)
4915 LegalValueVTs[VI] = Args[a + VI].getValueType();
4916 SDL.setValue(AI, SDL.DAG.getNode(ISD::MERGE_VALUES,
4917 SDL.DAG.getVTList(&LegalValueVTs[0],
4918 NumValues),
4919 &Args[a], NumValues));
Chris Lattnerbf209482005-10-30 19:42:35 +00004920 // If this argument is live outside of the entry block, insert a copy from
4921 // whereever we got it to the vreg that other BB's will reference it as.
Chris Lattner251db182007-02-25 18:40:32 +00004922 DenseMap<const Value*, unsigned>::iterator VMI=FuncInfo.ValueMap.find(AI);
4923 if (VMI != FuncInfo.ValueMap.end()) {
Dan Gohman86e1ebf2008-03-27 19:56:19 +00004924 SDL.CopyValueToVirtualRegister(AI, VMI->second);
Chris Lattnerbf209482005-10-30 19:42:35 +00004925 }
Chris Lattner0afa8e32005-01-17 17:55:19 +00004926 }
Dan Gohmanf5025cf2008-06-09 21:19:23 +00004927 a += NumValues;
4928 }
Chris Lattnerbf209482005-10-30 19:42:35 +00004929
Chris Lattnerbf209482005-10-30 19:42:35 +00004930 // Finally, if the target has anything special to do, allow it to do so.
Chris Lattner96645412006-05-16 06:10:58 +00004931 // FIXME: this should insert code into the DAG!
Chris Lattnerbf209482005-10-30 19:42:35 +00004932 EmitFunctionEntryCode(F, SDL.DAG.getMachineFunction());
Chris Lattner068a81e2005-01-17 17:15:02 +00004933}
4934
Duncan Sandsf4070822007-06-15 19:04:19 +00004935static void copyCatchInfo(BasicBlock *SrcBB, BasicBlock *DestBB,
4936 MachineModuleInfo *MMI, FunctionLoweringInfo &FLI) {
Duncan Sandsf4070822007-06-15 19:04:19 +00004937 for (BasicBlock::iterator I = SrcBB->begin(), E = --SrcBB->end(); I != E; ++I)
Duncan Sandscf26d7c2007-07-04 20:52:51 +00004938 if (isSelector(I)) {
Duncan Sandsf4070822007-06-15 19:04:19 +00004939 // Apply the catch info to DestBB.
4940 addCatchInfo(cast<CallInst>(*I), MMI, FLI.MBBMap[DestBB]);
4941#ifndef NDEBUG
Duncan Sands560a7372007-11-15 09:54:37 +00004942 if (!FLI.MBBMap[SrcBB]->isLandingPad())
4943 FLI.CatchInfoFound.insert(I);
Duncan Sandsf4070822007-06-15 19:04:19 +00004944#endif
4945 }
4946}
4947
Arnold Schwaighofer30e62c02008-04-30 09:16:33 +00004948/// IsFixedFrameObjectWithPosOffset - Check if object is a fixed frame object and
4949/// whether object offset >= 0.
4950static bool
4951IsFixedFrameObjectWithPosOffset(MachineFrameInfo * MFI, SDOperand Op) {
4952 if (!isa<FrameIndexSDNode>(Op)) return false;
4953
4954 FrameIndexSDNode * FrameIdxNode = dyn_cast<FrameIndexSDNode>(Op);
4955 int FrameIdx = FrameIdxNode->getIndex();
4956 return MFI->isFixedObjectIndex(FrameIdx) &&
4957 MFI->getObjectOffset(FrameIdx) >= 0;
4958}
4959
4960/// IsPossiblyOverwrittenArgumentOfTailCall - Check if the operand could
4961/// possibly be overwritten when lowering the outgoing arguments in a tail
4962/// call. Currently the implementation of this call is very conservative and
4963/// assumes all arguments sourcing from FORMAL_ARGUMENTS or a CopyFromReg with
4964/// virtual registers would be overwritten by direct lowering.
4965static bool IsPossiblyOverwrittenArgumentOfTailCall(SDOperand Op,
4966 MachineFrameInfo * MFI) {
4967 RegisterSDNode * OpReg = NULL;
4968 if (Op.getOpcode() == ISD::FORMAL_ARGUMENTS ||
4969 (Op.getOpcode()== ISD::CopyFromReg &&
4970 (OpReg = dyn_cast<RegisterSDNode>(Op.getOperand(1))) &&
4971 (OpReg->getReg() >= TargetRegisterInfo::FirstVirtualRegister)) ||
4972 (Op.getOpcode() == ISD::LOAD &&
4973 IsFixedFrameObjectWithPosOffset(MFI, Op.getOperand(1))) ||
4974 (Op.getOpcode() == ISD::MERGE_VALUES &&
4975 Op.getOperand(Op.ResNo).getOpcode() == ISD::LOAD &&
4976 IsFixedFrameObjectWithPosOffset(MFI, Op.getOperand(Op.ResNo).
4977 getOperand(1))))
4978 return true;
4979 return false;
4980}
4981
Arnold Schwaighoferc85e1712007-10-11 19:40:01 +00004982/// CheckDAGForTailCallsAndFixThem - This Function looks for CALL nodes in the
Arnold Schwaighofer48abc5c2007-10-12 21:30:57 +00004983/// DAG and fixes their tailcall attribute operand.
Arnold Schwaighoferc85e1712007-10-11 19:40:01 +00004984static void CheckDAGForTailCallsAndFixThem(SelectionDAG &DAG,
4985 TargetLowering& TLI) {
4986 SDNode * Ret = NULL;
4987 SDOperand Terminator = DAG.getRoot();
4988
4989 // Find RET node.
4990 if (Terminator.getOpcode() == ISD::RET) {
4991 Ret = Terminator.Val;
4992 }
4993
4994 // Fix tail call attribute of CALL nodes.
4995 for (SelectionDAG::allnodes_iterator BE = DAG.allnodes_begin(),
4996 BI = prior(DAG.allnodes_end()); BI != BE; --BI) {
4997 if (BI->getOpcode() == ISD::CALL) {
4998 SDOperand OpRet(Ret, 0);
4999 SDOperand OpCall(static_cast<SDNode*>(BI), 0);
5000 bool isMarkedTailCall =
5001 cast<ConstantSDNode>(OpCall.getOperand(3))->getValue() != 0;
5002 // If CALL node has tail call attribute set to true and the call is not
5003 // eligible (no RET or the target rejects) the attribute is fixed to
Arnold Schwaighofer48abc5c2007-10-12 21:30:57 +00005004 // false. The TargetLowering::IsEligibleForTailCallOptimization function
Arnold Schwaighoferc85e1712007-10-11 19:40:01 +00005005 // must correctly identify tail call optimizable calls.
Arnold Schwaighofer30e62c02008-04-30 09:16:33 +00005006 if (!isMarkedTailCall) continue;
5007 if (Ret==NULL ||
5008 !TLI.IsEligibleForTailCallOptimization(OpCall, OpRet, DAG)) {
5009 // Not eligible. Mark CALL node as non tail call.
Arnold Schwaighoferc85e1712007-10-11 19:40:01 +00005010 SmallVector<SDOperand, 32> Ops;
5011 unsigned idx=0;
Arnold Schwaighofer30e62c02008-04-30 09:16:33 +00005012 for(SDNode::op_iterator I =OpCall.Val->op_begin(),
5013 E = OpCall.Val->op_end(); I != E; I++, idx++) {
Arnold Schwaighoferc85e1712007-10-11 19:40:01 +00005014 if (idx!=3)
5015 Ops.push_back(*I);
Arnold Schwaighofer30e62c02008-04-30 09:16:33 +00005016 else
Arnold Schwaighoferc85e1712007-10-11 19:40:01 +00005017 Ops.push_back(DAG.getConstant(false, TLI.getPointerTy()));
5018 }
5019 DAG.UpdateNodeOperands(OpCall, Ops.begin(), Ops.size());
Arnold Schwaighofer30e62c02008-04-30 09:16:33 +00005020 } else {
5021 // Look for tail call clobbered arguments. Emit a series of
5022 // copyto/copyfrom virtual register nodes to protect them.
5023 SmallVector<SDOperand, 32> Ops;
5024 SDOperand Chain = OpCall.getOperand(0), InFlag;
5025 unsigned idx=0;
5026 for(SDNode::op_iterator I = OpCall.Val->op_begin(),
5027 E = OpCall.Val->op_end(); I != E; I++, idx++) {
5028 SDOperand Arg = *I;
5029 if (idx > 4 && (idx % 2)) {
5030 bool isByVal = cast<ARG_FLAGSSDNode>(OpCall.getOperand(idx+1))->
5031 getArgFlags().isByVal();
5032 MachineFunction &MF = DAG.getMachineFunction();
5033 MachineFrameInfo *MFI = MF.getFrameInfo();
5034 if (!isByVal &&
5035 IsPossiblyOverwrittenArgumentOfTailCall(Arg, MFI)) {
Duncan Sands83ec4b62008-06-06 12:08:01 +00005036 MVT VT = Arg.getValueType();
Arnold Schwaighofer30e62c02008-04-30 09:16:33 +00005037 unsigned VReg = MF.getRegInfo().
5038 createVirtualRegister(TLI.getRegClassFor(VT));
5039 Chain = DAG.getCopyToReg(Chain, VReg, Arg, InFlag);
5040 InFlag = Chain.getValue(1);
5041 Arg = DAG.getCopyFromReg(Chain, VReg, VT, InFlag);
5042 Chain = Arg.getValue(1);
5043 InFlag = Arg.getValue(2);
5044 }
5045 }
5046 Ops.push_back(Arg);
5047 }
5048 // Link in chain of CopyTo/CopyFromReg.
5049 Ops[0] = Chain;
5050 DAG.UpdateNodeOperands(OpCall, Ops.begin(), Ops.size());
Arnold Schwaighoferc85e1712007-10-11 19:40:01 +00005051 }
5052 }
5053 }
5054}
5055
Chris Lattner1c08c712005-01-07 07:47:53 +00005056void SelectionDAGISel::BuildSelectionDAG(SelectionDAG &DAG, BasicBlock *LLVMBB,
5057 std::vector<std::pair<MachineInstr*, unsigned> > &PHINodesToUpdate,
Nate Begemanf15485a2006-03-27 01:32:24 +00005058 FunctionLoweringInfo &FuncInfo) {
Gordon Henriksence224772008-01-07 01:30:38 +00005059 SelectionDAGLowering SDL(DAG, TLI, *AA, FuncInfo, GCI);
Chris Lattnerddb870b2005-01-13 17:59:43 +00005060
Chris Lattnerbf209482005-10-30 19:42:35 +00005061 // Lower any arguments needed in this block if this is the entry block.
Dan Gohmanecb7a772007-03-22 16:38:57 +00005062 if (LLVMBB == &LLVMBB->getParent()->getEntryBlock())
Dan Gohman86e1ebf2008-03-27 19:56:19 +00005063 LowerArguments(LLVMBB, SDL);
Chris Lattner1c08c712005-01-07 07:47:53 +00005064
5065 BB = FuncInfo.MBBMap[LLVMBB];
5066 SDL.setCurrentBasicBlock(BB);
5067
Duncan Sandsf4070822007-06-15 19:04:19 +00005068 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Duncan Sands9fac0b52007-06-06 10:05:18 +00005069
Dale Johannesen1532f3d2008-04-02 00:25:04 +00005070 if (MMI && BB->isLandingPad()) {
Duncan Sandsf4070822007-06-15 19:04:19 +00005071 // Add a label to mark the beginning of the landing pad. Deletion of the
5072 // landing pad can thus be detected via the MachineModuleInfo.
5073 unsigned LabelID = MMI->addLandingPad(BB);
5074 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, DAG.getEntryNode(),
Evan Chengbb81d972008-01-31 09:59:15 +00005075 DAG.getConstant(LabelID, MVT::i32),
5076 DAG.getConstant(1, MVT::i32)));
Duncan Sandsf4070822007-06-15 19:04:19 +00005077
Evan Chenge47c3332007-06-27 18:45:32 +00005078 // Mark exception register as live in.
5079 unsigned Reg = TLI.getExceptionAddressRegister();
5080 if (Reg) BB->addLiveIn(Reg);
5081
5082 // Mark exception selector register as live in.
5083 Reg = TLI.getExceptionSelectorRegister();
5084 if (Reg) BB->addLiveIn(Reg);
5085
Duncan Sandsf4070822007-06-15 19:04:19 +00005086 // FIXME: Hack around an exception handling flaw (PR1508): the personality
5087 // function and list of typeids logically belong to the invoke (or, if you
5088 // like, the basic block containing the invoke), and need to be associated
5089 // with it in the dwarf exception handling tables. Currently however the
Duncan Sandscf26d7c2007-07-04 20:52:51 +00005090 // information is provided by an intrinsic (eh.selector) that can be moved
5091 // to unexpected places by the optimizers: if the unwind edge is critical,
5092 // then breaking it can result in the intrinsics being in the successor of
5093 // the landing pad, not the landing pad itself. This results in exceptions
5094 // not being caught because no typeids are associated with the invoke.
5095 // This may not be the only way things can go wrong, but it is the only way
5096 // we try to work around for the moment.
Duncan Sandsf4070822007-06-15 19:04:19 +00005097 BranchInst *Br = dyn_cast<BranchInst>(LLVMBB->getTerminator());
5098
5099 if (Br && Br->isUnconditional()) { // Critical edge?
5100 BasicBlock::iterator I, E;
5101 for (I = LLVMBB->begin(), E = --LLVMBB->end(); I != E; ++I)
Duncan Sandscf26d7c2007-07-04 20:52:51 +00005102 if (isSelector(I))
Duncan Sandsf4070822007-06-15 19:04:19 +00005103 break;
5104
5105 if (I == E)
5106 // No catch info found - try to extract some from the successor.
5107 copyCatchInfo(Br->getSuccessor(0), LLVMBB, MMI, FuncInfo);
Duncan Sands9fac0b52007-06-06 10:05:18 +00005108 }
5109 }
5110
Chris Lattner1c08c712005-01-07 07:47:53 +00005111 // Lower all of the non-terminator instructions.
5112 for (BasicBlock::iterator I = LLVMBB->begin(), E = --LLVMBB->end();
5113 I != E; ++I)
5114 SDL.visit(*I);
Duncan Sandsf19f6bb2007-06-13 05:51:31 +00005115
Chris Lattner1c08c712005-01-07 07:47:53 +00005116 // Ensure that all instructions which are used outside of their defining
Duncan Sandsf19f6bb2007-06-13 05:51:31 +00005117 // blocks are available as virtual registers. Invoke is handled elsewhere.
Chris Lattner1c08c712005-01-07 07:47:53 +00005118 for (BasicBlock::iterator I = LLVMBB->begin(), E = LLVMBB->end(); I != E;++I)
Duncan Sandsf19f6bb2007-06-13 05:51:31 +00005119 if (!I->use_empty() && !isa<PHINode>(I) && !isa<InvokeInst>(I)) {
Chris Lattner9f24ad72007-02-04 01:35:11 +00005120 DenseMap<const Value*, unsigned>::iterator VMI =FuncInfo.ValueMap.find(I);
Chris Lattner1c08c712005-01-07 07:47:53 +00005121 if (VMI != FuncInfo.ValueMap.end())
Dan Gohman86e1ebf2008-03-27 19:56:19 +00005122 SDL.CopyValueToVirtualRegister(I, VMI->second);
Chris Lattner1c08c712005-01-07 07:47:53 +00005123 }
5124
5125 // Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
5126 // ensure constants are generated when needed. Remember the virtual registers
5127 // that need to be added to the Machine PHI nodes as input. We cannot just
5128 // directly add them, because expansion might result in multiple MBB's for one
5129 // BB. As such, the start of the BB might correspond to a different MBB than
5130 // the end.
Misha Brukmanedf128a2005-04-21 22:36:52 +00005131 //
Chris Lattner8c494ab2006-10-27 23:50:33 +00005132 TerminatorInst *TI = LLVMBB->getTerminator();
Chris Lattner1c08c712005-01-07 07:47:53 +00005133
5134 // Emit constants only once even if used by multiple PHI nodes.
5135 std::map<Constant*, unsigned> ConstantsOut;
Chris Lattnerd5e93c02006-09-07 01:59:34 +00005136
Chris Lattner8c494ab2006-10-27 23:50:33 +00005137 // Vector bool would be better, but vector<bool> is really slow.
5138 std::vector<unsigned char> SuccsHandled;
5139 if (TI->getNumSuccessors())
5140 SuccsHandled.resize(BB->getParent()->getNumBlockIDs());
5141
Dan Gohman532dc2e2007-07-09 20:59:04 +00005142 // Check successor nodes' PHI nodes that expect a constant to be available
5143 // from this block.
Chris Lattner1c08c712005-01-07 07:47:53 +00005144 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
5145 BasicBlock *SuccBB = TI->getSuccessor(succ);
Chris Lattnerd5e93c02006-09-07 01:59:34 +00005146 if (!isa<PHINode>(SuccBB->begin())) continue;
Chris Lattner8c494ab2006-10-27 23:50:33 +00005147 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
Chris Lattnerd5e93c02006-09-07 01:59:34 +00005148
Chris Lattner8c494ab2006-10-27 23:50:33 +00005149 // If this terminator has multiple identical successors (common for
5150 // switches), only handle each succ once.
5151 unsigned SuccMBBNo = SuccMBB->getNumber();
5152 if (SuccsHandled[SuccMBBNo]) continue;
5153 SuccsHandled[SuccMBBNo] = true;
5154
5155 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
Chris Lattner1c08c712005-01-07 07:47:53 +00005156 PHINode *PN;
5157
5158 // At this point we know that there is a 1-1 correspondence between LLVM PHI
5159 // nodes and Machine PHI nodes, but the incoming operands have not been
5160 // emitted yet.
5161 for (BasicBlock::iterator I = SuccBB->begin();
Chris Lattner8c494ab2006-10-27 23:50:33 +00005162 (PN = dyn_cast<PHINode>(I)); ++I) {
5163 // Ignore dead phi's.
5164 if (PN->use_empty()) continue;
5165
5166 unsigned Reg;
5167 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
Chris Lattner3f7927c2006-11-29 01:12:32 +00005168
Chris Lattner8c494ab2006-10-27 23:50:33 +00005169 if (Constant *C = dyn_cast<Constant>(PHIOp)) {
5170 unsigned &RegOut = ConstantsOut[C];
5171 if (RegOut == 0) {
5172 RegOut = FuncInfo.CreateRegForValue(C);
Dan Gohman86e1ebf2008-03-27 19:56:19 +00005173 SDL.CopyValueToVirtualRegister(C, RegOut);
Chris Lattner1c08c712005-01-07 07:47:53 +00005174 }
Chris Lattner8c494ab2006-10-27 23:50:33 +00005175 Reg = RegOut;
5176 } else {
5177 Reg = FuncInfo.ValueMap[PHIOp];
5178 if (Reg == 0) {
5179 assert(isa<AllocaInst>(PHIOp) &&
5180 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
5181 "Didn't codegen value into a register!??");
5182 Reg = FuncInfo.CreateRegForValue(PHIOp);
Dan Gohman86e1ebf2008-03-27 19:56:19 +00005183 SDL.CopyValueToVirtualRegister(PHIOp, Reg);
Chris Lattner7e021512006-03-31 02:12:18 +00005184 }
Chris Lattner1c08c712005-01-07 07:47:53 +00005185 }
Chris Lattner8c494ab2006-10-27 23:50:33 +00005186
5187 // Remember that this register needs to added to the machine PHI node as
5188 // the input for this MBB.
Duncan Sands83ec4b62008-06-06 12:08:01 +00005189 MVT VT = TLI.getValueType(PN->getType());
Dan Gohman7f321562007-06-25 16:23:39 +00005190 unsigned NumRegisters = TLI.getNumRegisters(VT);
Dan Gohmanb9f10192007-06-21 14:42:22 +00005191 for (unsigned i = 0, e = NumRegisters; i != e; ++i)
Chris Lattner8c494ab2006-10-27 23:50:33 +00005192 PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
5193 }
Chris Lattner1c08c712005-01-07 07:47:53 +00005194 }
5195 ConstantsOut.clear();
5196
5197 // Lower the terminator after the copies are emitted.
Duncan Sandsf19f6bb2007-06-13 05:51:31 +00005198 SDL.visit(*LLVMBB->getTerminator());
Chris Lattnera651cf62005-01-17 19:43:36 +00005199
Nate Begemanf15485a2006-03-27 01:32:24 +00005200 // Copy over any CaseBlock records that may now exist due to SwitchInst
Nate Begeman37efe672006-04-22 18:53:45 +00005201 // lowering, as well as any jump table information.
Nate Begemanf15485a2006-03-27 01:32:24 +00005202 SwitchCases.clear();
5203 SwitchCases = SDL.SwitchCases;
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00005204 JTCases.clear();
5205 JTCases = SDL.JTCases;
Anton Korobeynikov4198c582007-04-09 12:31:58 +00005206 BitTestCases.clear();
5207 BitTestCases = SDL.BitTestCases;
5208
Chris Lattnera651cf62005-01-17 19:43:36 +00005209 // Make sure the root of the DAG is up-to-date.
Dan Gohman86e1ebf2008-03-27 19:56:19 +00005210 DAG.setRoot(SDL.getControlRoot());
Arnold Schwaighoferc85e1712007-10-11 19:40:01 +00005211
5212 // Check whether calls in this block are real tail calls. Fix up CALL nodes
5213 // with correct tailcall attribute so that the target can rely on the tailcall
5214 // attribute indicating whether the call is really eligible for tail call
5215 // optimization.
5216 CheckDAGForTailCallsAndFixThem(DAG, TLI);
Chris Lattner1c08c712005-01-07 07:47:53 +00005217}
5218
Nate Begemanf15485a2006-03-27 01:32:24 +00005219void SelectionDAGISel::CodeGenAndEmitDAG(SelectionDAG &DAG) {
Dan Gohman417e11b2007-10-08 15:12:17 +00005220 DOUT << "Lowered selection DAG:\n";
5221 DEBUG(DAG.dump());
5222
Chris Lattneraf21d552005-10-10 16:47:10 +00005223 // Run the DAG combiner in pre-legalize mode.
Dan Gohman5f43f922007-08-27 16:26:13 +00005224 DAG.Combine(false, *AA);
Nate Begeman2300f552005-09-07 00:15:36 +00005225
Dan Gohman417e11b2007-10-08 15:12:17 +00005226 DOUT << "Optimized lowered selection DAG:\n";
Chris Lattner1c08c712005-01-07 07:47:53 +00005227 DEBUG(DAG.dump());
Nate Begemanf15485a2006-03-27 01:32:24 +00005228
Chris Lattner1c08c712005-01-07 07:47:53 +00005229 // Second step, hack on the DAG until it only uses operations and types that
5230 // the target supports.
Chris Lattner01d029b2007-10-15 06:10:22 +00005231#if 0 // Enable this some day.
5232 DAG.LegalizeTypes();
5233 // Someday even later, enable a dag combine pass here.
5234#endif
Chris Lattnerac9dc082005-01-23 04:36:26 +00005235 DAG.Legalize();
Nate Begemanf15485a2006-03-27 01:32:24 +00005236
Bill Wendling832171c2006-12-07 20:04:42 +00005237 DOUT << "Legalized selection DAG:\n";
Chris Lattner1c08c712005-01-07 07:47:53 +00005238 DEBUG(DAG.dump());
Nate Begemanf15485a2006-03-27 01:32:24 +00005239
Chris Lattneraf21d552005-10-10 16:47:10 +00005240 // Run the DAG combiner in post-legalize mode.
Dan Gohman5f43f922007-08-27 16:26:13 +00005241 DAG.Combine(true, *AA);
Nate Begeman2300f552005-09-07 00:15:36 +00005242
Dan Gohman417e11b2007-10-08 15:12:17 +00005243 DOUT << "Optimized legalized selection DAG:\n";
5244 DEBUG(DAG.dump());
5245
Evan Chenga9c20912006-01-21 02:32:06 +00005246 if (ViewISelDAGs) DAG.viewGraph();
Evan Cheng552c4a82006-04-28 02:09:19 +00005247
Chris Lattnera33ef482005-03-30 01:10:47 +00005248 // Third, instruction select all of the operations to machine code, adding the
5249 // code to the MachineBasicBlock.
Chris Lattner1c08c712005-01-07 07:47:53 +00005250 InstructionSelectBasicBlock(DAG);
Nate Begemanf15485a2006-03-27 01:32:24 +00005251
Bill Wendling832171c2006-12-07 20:04:42 +00005252 DOUT << "Selected machine code:\n";
Chris Lattner1c08c712005-01-07 07:47:53 +00005253 DEBUG(BB->dump());
Nate Begemanf15485a2006-03-27 01:32:24 +00005254}
Chris Lattner1c08c712005-01-07 07:47:53 +00005255
Nate Begemanf15485a2006-03-27 01:32:24 +00005256void SelectionDAGISel::SelectBasicBlock(BasicBlock *LLVMBB, MachineFunction &MF,
5257 FunctionLoweringInfo &FuncInfo) {
5258 std::vector<std::pair<MachineInstr*, unsigned> > PHINodesToUpdate;
5259 {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00005260 SelectionDAG DAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
Nate Begemanf15485a2006-03-27 01:32:24 +00005261 CurDAG = &DAG;
5262
5263 // First step, lower LLVM code to some DAG. This DAG may use operations and
5264 // types that are not supported by the target.
5265 BuildSelectionDAG(DAG, LLVMBB, PHINodesToUpdate, FuncInfo);
5266
5267 // Second step, emit the lowered DAG as machine code.
5268 CodeGenAndEmitDAG(DAG);
5269 }
Anton Korobeynikov4198c582007-04-09 12:31:58 +00005270
5271 DOUT << "Total amount of phi nodes to update: "
5272 << PHINodesToUpdate.size() << "\n";
5273 DEBUG(for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i)
5274 DOUT << "Node " << i << " : (" << PHINodesToUpdate[i].first
5275 << ", " << PHINodesToUpdate[i].second << ")\n";);
Nate Begemanf15485a2006-03-27 01:32:24 +00005276
Chris Lattnera33ef482005-03-30 01:10:47 +00005277 // Next, now that we know what the last MBB the LLVM BB expanded is, update
Chris Lattner1c08c712005-01-07 07:47:53 +00005278 // PHI nodes in successors.
Anton Korobeynikov4198c582007-04-09 12:31:58 +00005279 if (SwitchCases.empty() && JTCases.empty() && BitTestCases.empty()) {
Nate Begemanf15485a2006-03-27 01:32:24 +00005280 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
5281 MachineInstr *PHI = PHINodesToUpdate[i].first;
5282 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
5283 "This is not a machine PHI node that we are updating!");
Chris Lattner9ce2e9d2007-12-30 00:57:42 +00005284 PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[i].second,
5285 false));
5286 PHI->addOperand(MachineOperand::CreateMBB(BB));
Nate Begemanf15485a2006-03-27 01:32:24 +00005287 }
5288 return;
Chris Lattner1c08c712005-01-07 07:47:53 +00005289 }
Anton Korobeynikov4198c582007-04-09 12:31:58 +00005290
5291 for (unsigned i = 0, e = BitTestCases.size(); i != e; ++i) {
5292 // Lower header first, if it wasn't already lowered
5293 if (!BitTestCases[i].Emitted) {
5294 SelectionDAG HSDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
5295 CurDAG = &HSDAG;
Gordon Henriksence224772008-01-07 01:30:38 +00005296 SelectionDAGLowering HSDL(HSDAG, TLI, *AA, FuncInfo, GCI);
Anton Korobeynikov4198c582007-04-09 12:31:58 +00005297 // Set the current basic block to the mbb we wish to insert the code into
5298 BB = BitTestCases[i].Parent;
5299 HSDL.setCurrentBasicBlock(BB);
5300 // Emit the code
5301 HSDL.visitBitTestHeader(BitTestCases[i]);
5302 HSDAG.setRoot(HSDL.getRoot());
5303 CodeGenAndEmitDAG(HSDAG);
5304 }
5305
5306 for (unsigned j = 0, ej = BitTestCases[i].Cases.size(); j != ej; ++j) {
5307 SelectionDAG BSDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
5308 CurDAG = &BSDAG;
Gordon Henriksence224772008-01-07 01:30:38 +00005309 SelectionDAGLowering BSDL(BSDAG, TLI, *AA, FuncInfo, GCI);
Anton Korobeynikov4198c582007-04-09 12:31:58 +00005310 // Set the current basic block to the mbb we wish to insert the code into
5311 BB = BitTestCases[i].Cases[j].ThisBB;
5312 BSDL.setCurrentBasicBlock(BB);
5313 // Emit the code
5314 if (j+1 != ej)
5315 BSDL.visitBitTestCase(BitTestCases[i].Cases[j+1].ThisBB,
5316 BitTestCases[i].Reg,
5317 BitTestCases[i].Cases[j]);
5318 else
5319 BSDL.visitBitTestCase(BitTestCases[i].Default,
5320 BitTestCases[i].Reg,
5321 BitTestCases[i].Cases[j]);
5322
5323
5324 BSDAG.setRoot(BSDL.getRoot());
5325 CodeGenAndEmitDAG(BSDAG);
5326 }
5327
5328 // Update PHI Nodes
5329 for (unsigned pi = 0, pe = PHINodesToUpdate.size(); pi != pe; ++pi) {
5330 MachineInstr *PHI = PHINodesToUpdate[pi].first;
5331 MachineBasicBlock *PHIBB = PHI->getParent();
5332 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
5333 "This is not a machine PHI node that we are updating!");
5334 // This is "default" BB. We have two jumps to it. From "header" BB and
5335 // from last "case" BB.
5336 if (PHIBB == BitTestCases[i].Default) {
Chris Lattner9ce2e9d2007-12-30 00:57:42 +00005337 PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[pi].second,
5338 false));
5339 PHI->addOperand(MachineOperand::CreateMBB(BitTestCases[i].Parent));
5340 PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[pi].second,
5341 false));
5342 PHI->addOperand(MachineOperand::CreateMBB(BitTestCases[i].Cases.
5343 back().ThisBB));
Anton Korobeynikov4198c582007-04-09 12:31:58 +00005344 }
5345 // One of "cases" BB.
5346 for (unsigned j = 0, ej = BitTestCases[i].Cases.size(); j != ej; ++j) {
5347 MachineBasicBlock* cBB = BitTestCases[i].Cases[j].ThisBB;
5348 if (cBB->succ_end() !=
5349 std::find(cBB->succ_begin(),cBB->succ_end(), PHIBB)) {
Chris Lattner9ce2e9d2007-12-30 00:57:42 +00005350 PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[pi].second,
5351 false));
5352 PHI->addOperand(MachineOperand::CreateMBB(cBB));
Anton Korobeynikov4198c582007-04-09 12:31:58 +00005353 }
5354 }
5355 }
5356 }
5357
Nate Begeman9453eea2006-04-23 06:26:20 +00005358 // If the JumpTable record is filled in, then we need to emit a jump table.
5359 // Updating the PHI nodes is tricky in this case, since we need to determine
5360 // whether the PHI is a successor of the range check MBB or the jump table MBB
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00005361 for (unsigned i = 0, e = JTCases.size(); i != e; ++i) {
5362 // Lower header first, if it wasn't already lowered
5363 if (!JTCases[i].first.Emitted) {
5364 SelectionDAG HSDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
5365 CurDAG = &HSDAG;
Gordon Henriksence224772008-01-07 01:30:38 +00005366 SelectionDAGLowering HSDL(HSDAG, TLI, *AA, FuncInfo, GCI);
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00005367 // Set the current basic block to the mbb we wish to insert the code into
5368 BB = JTCases[i].first.HeaderBB;
5369 HSDL.setCurrentBasicBlock(BB);
5370 // Emit the code
5371 HSDL.visitJumpTableHeader(JTCases[i].second, JTCases[i].first);
5372 HSDAG.setRoot(HSDL.getRoot());
5373 CodeGenAndEmitDAG(HSDAG);
Anton Korobeynikov4198c582007-04-09 12:31:58 +00005374 }
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00005375
5376 SelectionDAG JSDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
5377 CurDAG = &JSDAG;
Gordon Henriksence224772008-01-07 01:30:38 +00005378 SelectionDAGLowering JSDL(JSDAG, TLI, *AA, FuncInfo, GCI);
Nate Begeman37efe672006-04-22 18:53:45 +00005379 // Set the current basic block to the mbb we wish to insert the code into
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00005380 BB = JTCases[i].second.MBB;
5381 JSDL.setCurrentBasicBlock(BB);
Nate Begeman37efe672006-04-22 18:53:45 +00005382 // Emit the code
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00005383 JSDL.visitJumpTable(JTCases[i].second);
5384 JSDAG.setRoot(JSDL.getRoot());
5385 CodeGenAndEmitDAG(JSDAG);
5386
Nate Begeman37efe672006-04-22 18:53:45 +00005387 // Update PHI Nodes
5388 for (unsigned pi = 0, pe = PHINodesToUpdate.size(); pi != pe; ++pi) {
5389 MachineInstr *PHI = PHINodesToUpdate[pi].first;
5390 MachineBasicBlock *PHIBB = PHI->getParent();
5391 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
5392 "This is not a machine PHI node that we are updating!");
Anton Korobeynikov4198c582007-04-09 12:31:58 +00005393 // "default" BB. We can go there only from header BB.
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00005394 if (PHIBB == JTCases[i].second.Default) {
Chris Lattner9ce2e9d2007-12-30 00:57:42 +00005395 PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[pi].second,
5396 false));
5397 PHI->addOperand(MachineOperand::CreateMBB(JTCases[i].first.HeaderBB));
Nate Begemanf4360a42006-05-03 03:48:02 +00005398 }
Anton Korobeynikov4198c582007-04-09 12:31:58 +00005399 // JT BB. Just iterate over successors here
Nate Begemanf4360a42006-05-03 03:48:02 +00005400 if (BB->succ_end() != std::find(BB->succ_begin(),BB->succ_end(), PHIBB)) {
Chris Lattner9ce2e9d2007-12-30 00:57:42 +00005401 PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[pi].second,
5402 false));
5403 PHI->addOperand(MachineOperand::CreateMBB(BB));
Nate Begeman37efe672006-04-22 18:53:45 +00005404 }
5405 }
Nate Begeman37efe672006-04-22 18:53:45 +00005406 }
5407
Chris Lattnerb2e806e2006-10-22 23:00:53 +00005408 // If the switch block involved a branch to one of the actual successors, we
5409 // need to update PHI nodes in that block.
5410 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
5411 MachineInstr *PHI = PHINodesToUpdate[i].first;
5412 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
5413 "This is not a machine PHI node that we are updating!");
5414 if (BB->isSuccessor(PHI->getParent())) {
Chris Lattner9ce2e9d2007-12-30 00:57:42 +00005415 PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[i].second,
5416 false));
5417 PHI->addOperand(MachineOperand::CreateMBB(BB));
Chris Lattnerb2e806e2006-10-22 23:00:53 +00005418 }
5419 }
5420
Nate Begemanf15485a2006-03-27 01:32:24 +00005421 // If we generated any switch lowering information, build and codegen any
5422 // additional DAGs necessary.
Chris Lattnerd5e93c02006-09-07 01:59:34 +00005423 for (unsigned i = 0, e = SwitchCases.size(); i != e; ++i) {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00005424 SelectionDAG SDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
Nate Begemanf15485a2006-03-27 01:32:24 +00005425 CurDAG = &SDAG;
Gordon Henriksence224772008-01-07 01:30:38 +00005426 SelectionDAGLowering SDL(SDAG, TLI, *AA, FuncInfo, GCI);
Chris Lattnerd5e93c02006-09-07 01:59:34 +00005427
Nate Begemanf15485a2006-03-27 01:32:24 +00005428 // Set the current basic block to the mbb we wish to insert the code into
5429 BB = SwitchCases[i].ThisBB;
5430 SDL.setCurrentBasicBlock(BB);
Chris Lattnerd5e93c02006-09-07 01:59:34 +00005431
Nate Begemanf15485a2006-03-27 01:32:24 +00005432 // Emit the code
5433 SDL.visitSwitchCase(SwitchCases[i]);
5434 SDAG.setRoot(SDL.getRoot());
5435 CodeGenAndEmitDAG(SDAG);
Chris Lattnerd5e93c02006-09-07 01:59:34 +00005436
5437 // Handle any PHI nodes in successors of this chunk, as if we were coming
5438 // from the original BB before switch expansion. Note that PHI nodes can
5439 // occur multiple times in PHINodesToUpdate. We have to be very careful to
5440 // handle them the right number of times.
Chris Lattner57ab6592006-10-24 17:57:59 +00005441 while ((BB = SwitchCases[i].TrueBB)) { // Handle LHS and RHS.
Chris Lattnerd5e93c02006-09-07 01:59:34 +00005442 for (MachineBasicBlock::iterator Phi = BB->begin();
5443 Phi != BB->end() && Phi->getOpcode() == TargetInstrInfo::PHI; ++Phi){
5444 // This value for this PHI node is recorded in PHINodesToUpdate, get it.
5445 for (unsigned pn = 0; ; ++pn) {
5446 assert(pn != PHINodesToUpdate.size() && "Didn't find PHI entry!");
5447 if (PHINodesToUpdate[pn].first == Phi) {
Chris Lattner9ce2e9d2007-12-30 00:57:42 +00005448 Phi->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[pn].
5449 second, false));
5450 Phi->addOperand(MachineOperand::CreateMBB(SwitchCases[i].ThisBB));
Chris Lattnerd5e93c02006-09-07 01:59:34 +00005451 break;
5452 }
5453 }
Nate Begemanf15485a2006-03-27 01:32:24 +00005454 }
Chris Lattnerd5e93c02006-09-07 01:59:34 +00005455
5456 // Don't process RHS if same block as LHS.
Chris Lattner57ab6592006-10-24 17:57:59 +00005457 if (BB == SwitchCases[i].FalseBB)
5458 SwitchCases[i].FalseBB = 0;
Chris Lattnerd5e93c02006-09-07 01:59:34 +00005459
5460 // If we haven't handled the RHS, do so now. Otherwise, we're done.
Chris Lattner24525952006-10-24 18:07:37 +00005461 SwitchCases[i].TrueBB = SwitchCases[i].FalseBB;
Chris Lattner57ab6592006-10-24 17:57:59 +00005462 SwitchCases[i].FalseBB = 0;
Nate Begemanf15485a2006-03-27 01:32:24 +00005463 }
Chris Lattner57ab6592006-10-24 17:57:59 +00005464 assert(SwitchCases[i].TrueBB == 0 && SwitchCases[i].FalseBB == 0);
Chris Lattnera33ef482005-03-30 01:10:47 +00005465 }
Chris Lattner1c08c712005-01-07 07:47:53 +00005466}
Evan Chenga9c20912006-01-21 02:32:06 +00005467
Jim Laskey13ec7022006-08-01 14:21:23 +00005468
Evan Chenga9c20912006-01-21 02:32:06 +00005469//===----------------------------------------------------------------------===//
5470/// ScheduleAndEmitDAG - Pick a safe ordering and emit instructions for each
5471/// target node in the graph.
5472void SelectionDAGISel::ScheduleAndEmitDAG(SelectionDAG &DAG) {
5473 if (ViewSchedDAGs) DAG.viewGraph();
Evan Cheng4ef10862006-01-23 07:01:07 +00005474
Jim Laskeyeb577ba2006-08-02 12:30:23 +00005475 RegisterScheduler::FunctionPassCtor Ctor = RegisterScheduler::getDefault();
Jim Laskey13ec7022006-08-01 14:21:23 +00005476
5477 if (!Ctor) {
Jim Laskeyeb577ba2006-08-02 12:30:23 +00005478 Ctor = ISHeuristic;
Jim Laskey9373beb2006-08-01 19:14:14 +00005479 RegisterScheduler::setDefault(Ctor);
Evan Cheng4ef10862006-01-23 07:01:07 +00005480 }
Jim Laskey13ec7022006-08-01 14:21:23 +00005481
Jim Laskey9ff542f2006-08-01 18:29:48 +00005482 ScheduleDAG *SL = Ctor(this, &DAG, BB);
Chris Lattnera3818e62006-01-21 19:12:11 +00005483 BB = SL->Run();
Dan Gohman3e1a7ae2007-08-28 20:32:58 +00005484
5485 if (ViewSUnitDAGs) SL->viewGraph();
5486
Evan Chengcccf1232006-02-04 06:49:00 +00005487 delete SL;
Evan Chenga9c20912006-01-21 02:32:06 +00005488}
Chris Lattner0e43f2b2006-02-24 02:13:54 +00005489
Chris Lattner03fc53c2006-03-06 00:22:00 +00005490
Jim Laskey9ff542f2006-08-01 18:29:48 +00005491HazardRecognizer *SelectionDAGISel::CreateTargetHazardRecognizer() {
5492 return new HazardRecognizer();
5493}
5494
Chris Lattner75548062006-10-11 03:58:02 +00005495//===----------------------------------------------------------------------===//
5496// Helper functions used by the generated instruction selector.
5497//===----------------------------------------------------------------------===//
5498// Calls to these methods are generated by tblgen.
5499
5500/// CheckAndMask - The isel is trying to match something like (and X, 255). If
5501/// the dag combiner simplified the 255, we still want to match. RHS is the
5502/// actual value in the DAG on the RHS of an AND, and DesiredMaskS is the value
5503/// specified in the .td file (e.g. 255).
5504bool SelectionDAGISel::CheckAndMask(SDOperand LHS, ConstantSDNode *RHS,
Dan Gohmandc9b3d02007-07-24 23:00:27 +00005505 int64_t DesiredMaskS) const {
Dan Gohman2e68b6f2008-02-25 21:11:39 +00005506 const APInt &ActualMask = RHS->getAPIntValue();
5507 const APInt &DesiredMask = APInt(LHS.getValueSizeInBits(), DesiredMaskS);
Chris Lattner75548062006-10-11 03:58:02 +00005508
5509 // If the actual mask exactly matches, success!
5510 if (ActualMask == DesiredMask)
5511 return true;
5512
5513 // If the actual AND mask is allowing unallowed bits, this doesn't match.
Dan Gohman2e68b6f2008-02-25 21:11:39 +00005514 if (ActualMask.intersects(~DesiredMask))
Chris Lattner75548062006-10-11 03:58:02 +00005515 return false;
5516
5517 // Otherwise, the DAG Combiner may have proven that the value coming in is
5518 // either already zero or is not demanded. Check for known zero input bits.
Dan Gohman2e68b6f2008-02-25 21:11:39 +00005519 APInt NeededMask = DesiredMask & ~ActualMask;
Dan Gohmanea859be2007-06-22 14:59:07 +00005520 if (CurDAG->MaskedValueIsZero(LHS, NeededMask))
Chris Lattner75548062006-10-11 03:58:02 +00005521 return true;
5522
5523 // TODO: check to see if missing bits are just not demanded.
5524
5525 // Otherwise, this pattern doesn't match.
5526 return false;
5527}
5528
5529/// CheckOrMask - The isel is trying to match something like (or X, 255). If
5530/// the dag combiner simplified the 255, we still want to match. RHS is the
5531/// actual value in the DAG on the RHS of an OR, and DesiredMaskS is the value
5532/// specified in the .td file (e.g. 255).
5533bool SelectionDAGISel::CheckOrMask(SDOperand LHS, ConstantSDNode *RHS,
Dan Gohman2e68b6f2008-02-25 21:11:39 +00005534 int64_t DesiredMaskS) const {
5535 const APInt &ActualMask = RHS->getAPIntValue();
5536 const APInt &DesiredMask = APInt(LHS.getValueSizeInBits(), DesiredMaskS);
Chris Lattner75548062006-10-11 03:58:02 +00005537
5538 // If the actual mask exactly matches, success!
5539 if (ActualMask == DesiredMask)
5540 return true;
5541
5542 // If the actual AND mask is allowing unallowed bits, this doesn't match.
Dan Gohman2e68b6f2008-02-25 21:11:39 +00005543 if (ActualMask.intersects(~DesiredMask))
Chris Lattner75548062006-10-11 03:58:02 +00005544 return false;
5545
5546 // Otherwise, the DAG Combiner may have proven that the value coming in is
5547 // either already zero or is not demanded. Check for known zero input bits.
Dan Gohman2e68b6f2008-02-25 21:11:39 +00005548 APInt NeededMask = DesiredMask & ~ActualMask;
Chris Lattner75548062006-10-11 03:58:02 +00005549
Dan Gohman2e68b6f2008-02-25 21:11:39 +00005550 APInt KnownZero, KnownOne;
Dan Gohmanea859be2007-06-22 14:59:07 +00005551 CurDAG->ComputeMaskedBits(LHS, NeededMask, KnownZero, KnownOne);
Chris Lattner75548062006-10-11 03:58:02 +00005552
5553 // If all the missing bits in the or are already known to be set, match!
5554 if ((NeededMask & KnownOne) == NeededMask)
5555 return true;
5556
5557 // TODO: check to see if missing bits are just not demanded.
5558
5559 // Otherwise, this pattern doesn't match.
5560 return false;
5561}
5562
Jim Laskey9ff542f2006-08-01 18:29:48 +00005563
Chris Lattner0e43f2b2006-02-24 02:13:54 +00005564/// SelectInlineAsmMemoryOperands - Calls to this are automatically generated
5565/// by tblgen. Others should not call it.
5566void SelectionDAGISel::
5567SelectInlineAsmMemoryOperands(std::vector<SDOperand> &Ops, SelectionDAG &DAG) {
5568 std::vector<SDOperand> InOps;
5569 std::swap(InOps, Ops);
5570
5571 Ops.push_back(InOps[0]); // input chain.
5572 Ops.push_back(InOps[1]); // input asm string.
5573
Chris Lattner0e43f2b2006-02-24 02:13:54 +00005574 unsigned i = 2, e = InOps.size();
5575 if (InOps[e-1].getValueType() == MVT::Flag)
5576 --e; // Don't process a flag operand if it is here.
5577
5578 while (i != e) {
5579 unsigned Flags = cast<ConstantSDNode>(InOps[i])->getValue();
5580 if ((Flags & 7) != 4 /*MEM*/) {
5581 // Just skip over this operand, copying the operands verbatim.
5582 Ops.insert(Ops.end(), InOps.begin()+i, InOps.begin()+i+(Flags >> 3) + 1);
5583 i += (Flags >> 3) + 1;
5584 } else {
5585 assert((Flags >> 3) == 1 && "Memory operand with multiple values?");
5586 // Otherwise, this is a memory operand. Ask the target to select it.
5587 std::vector<SDOperand> SelOps;
5588 if (SelectInlineAsmMemoryOperand(InOps[i+1], 'm', SelOps, DAG)) {
Bill Wendling832171c2006-12-07 20:04:42 +00005589 cerr << "Could not match memory address. Inline asm failure!\n";
Chris Lattner0e43f2b2006-02-24 02:13:54 +00005590 exit(1);
5591 }
5592
5593 // Add this to the output node.
Duncan Sands83ec4b62008-06-06 12:08:01 +00005594 MVT IntPtrTy = DAG.getTargetLoweringInfo().getPointerTy();
Chris Lattner36d43962006-12-16 21:14:48 +00005595 Ops.push_back(DAG.getTargetConstant(4/*MEM*/ | (SelOps.size() << 3),
Chris Lattner4b993b12007-04-09 00:33:58 +00005596 IntPtrTy));
Chris Lattner0e43f2b2006-02-24 02:13:54 +00005597 Ops.insert(Ops.end(), SelOps.begin(), SelOps.end());
5598 i += 2;
5599 }
5600 }
5601
5602 // Add the flag input back if present.
5603 if (e != InOps.size())
5604 Ops.push_back(InOps.back());
5605}
Devang Patel794fd752007-05-01 21:15:47 +00005606
Devang Patel19974732007-05-03 01:11:54 +00005607char SelectionDAGISel::ID = 0;