blob: 7ec5b8534dd3d85cf9657570ed92acc2de979879 [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"
Evan Cheng381cb072008-08-08 07:27:28 +000015#include "llvm/CodeGen/SelectionDAGISel.h"
Anton Korobeynikov5502bf62007-04-04 21:14:49 +000016#include "llvm/ADT/BitVector.h"
Jim Laskeyc7c3f112006-10-16 20:52:31 +000017#include "llvm/Analysis/AliasAnalysis.h"
Anton Korobeynikov5502bf62007-04-04 21:14:49 +000018#include "llvm/Constants.h"
Chris Lattneradf6a962005-05-13 18:50:42 +000019#include "llvm/CallingConv.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000020#include "llvm/DerivedTypes.h"
21#include "llvm/Function.h"
Chris Lattner36ce6912005-11-29 06:21:05 +000022#include "llvm/GlobalVariable.h"
Chris Lattnerce7518c2006-01-26 22:24:51 +000023#include "llvm/InlineAsm.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000024#include "llvm/Instructions.h"
25#include "llvm/Intrinsics.h"
Jim Laskey43970fe2006-03-23 18:06:46 +000026#include "llvm/IntrinsicInst.h"
Reid Spencer5694b6e2007-04-09 06:17:21 +000027#include "llvm/ParameterAttributes.h"
Dan Gohman78eca172008-08-19 22:33:34 +000028#include "llvm/CodeGen/FastISel.h"
Gordon Henriksen5a29c9e2008-08-17 12:56:54 +000029#include "llvm/CodeGen/GCStrategy.h"
Gordon Henriksen5eca0752008-08-17 18:44:35 +000030#include "llvm/CodeGen/GCMetadata.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000031#include "llvm/CodeGen/MachineFunction.h"
32#include "llvm/CodeGen/MachineFrameInfo.h"
33#include "llvm/CodeGen/MachineInstrBuilder.h"
Chris Lattner84bc5422007-12-31 04:13:23 +000034#include "llvm/CodeGen/MachineJumpTableInfo.h"
35#include "llvm/CodeGen/MachineModuleInfo.h"
36#include "llvm/CodeGen/MachineRegisterInfo.h"
Evan Cheng381cb072008-08-08 07:27:28 +000037#include "llvm/CodeGen/ScheduleDAG.h"
Jim Laskeyeb577ba2006-08-02 12:30:23 +000038#include "llvm/CodeGen/SchedulerRegistry.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000039#include "llvm/CodeGen/SelectionDAG.h"
Dan Gohman6f0d0242008-02-10 18:45:23 +000040#include "llvm/Target/TargetRegisterInfo.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000041#include "llvm/Target/TargetData.h"
42#include "llvm/Target/TargetFrameInfo.h"
43#include "llvm/Target/TargetInstrInfo.h"
44#include "llvm/Target/TargetLowering.h"
45#include "llvm/Target/TargetMachine.h"
Vladimir Prus12472912006-05-23 13:43:15 +000046#include "llvm/Target/TargetOptions.h"
Chris Lattnera4f0b3a2006-08-27 12:54:02 +000047#include "llvm/Support/Compiler.h"
Evan Chengdb8d56b2008-06-30 20:45:06 +000048#include "llvm/Support/Debug.h"
49#include "llvm/Support/MathExtras.h"
50#include "llvm/Support/Timer.h"
Jeff Cohen7e881032006-02-24 02:52:40 +000051#include <algorithm>
Chris Lattner1c08c712005-01-07 07:47:53 +000052using namespace llvm;
53
Chris Lattneread0d882008-06-17 06:09:18 +000054static cl::opt<bool>
Chris Lattner70587ea2008-07-10 23:37:50 +000055EnableValueProp("enable-value-prop", cl::Hidden);
56static cl::opt<bool>
Duncan Sandsf00e74f2008-07-17 17:06:03 +000057EnableLegalizeTypes("enable-legalize-types", cl::Hidden);
Dan Gohman78eca172008-08-19 22:33:34 +000058static cl::opt<bool>
59EnableFastISel("fast-isel", cl::Hidden,
60 cl::desc("Enable the experimental \"fast\" instruction selector"));
Dan Gohman3e697cf2008-08-20 00:47:54 +000061static cl::opt<bool>
62DisableFastISelAbort("fast-isel-no-abort", cl::Hidden,
63 cl::desc("Use the SelectionDAGISel when \"fast\" instruction "
64 "selection fails"));
Chris Lattneread0d882008-06-17 06:09:18 +000065
Chris Lattnerda8abb02005-09-01 18:44:10 +000066#ifndef NDEBUG
Chris Lattner7944d9d2005-01-12 03:41:21 +000067static cl::opt<bool>
Dan Gohman462dc7f2008-07-21 20:00:07 +000068ViewDAGCombine1("view-dag-combine1-dags", cl::Hidden,
69 cl::desc("Pop up a window to show dags before the first "
70 "dag combine pass"));
71static cl::opt<bool>
72ViewLegalizeTypesDAGs("view-legalize-types-dags", cl::Hidden,
73 cl::desc("Pop up a window to show dags before legalize types"));
74static cl::opt<bool>
75ViewLegalizeDAGs("view-legalize-dags", cl::Hidden,
76 cl::desc("Pop up a window to show dags before legalize"));
77static cl::opt<bool>
78ViewDAGCombine2("view-dag-combine2-dags", cl::Hidden,
79 cl::desc("Pop up a window to show dags before the second "
80 "dag combine pass"));
81static cl::opt<bool>
Evan Chenga9c20912006-01-21 02:32:06 +000082ViewISelDAGs("view-isel-dags", cl::Hidden,
83 cl::desc("Pop up a window to show isel dags as they are selected"));
84static cl::opt<bool>
85ViewSchedDAGs("view-sched-dags", cl::Hidden,
86 cl::desc("Pop up a window to show sched dags as they are processed"));
Dan Gohman3e1a7ae2007-08-28 20:32:58 +000087static cl::opt<bool>
88ViewSUnitDAGs("view-sunit-dags", cl::Hidden,
Chris Lattner5bab7852008-01-25 17:24:52 +000089 cl::desc("Pop up a window to show SUnit dags after they are processed"));
Chris Lattner7944d9d2005-01-12 03:41:21 +000090#else
Dan Gohman462dc7f2008-07-21 20:00:07 +000091static const bool ViewDAGCombine1 = false,
92 ViewLegalizeTypesDAGs = false, ViewLegalizeDAGs = false,
93 ViewDAGCombine2 = false,
94 ViewISelDAGs = false, ViewSchedDAGs = false,
95 ViewSUnitDAGs = false;
Chris Lattner7944d9d2005-01-12 03:41:21 +000096#endif
97
Jim Laskeyeb577ba2006-08-02 12:30:23 +000098//===---------------------------------------------------------------------===//
99///
100/// RegisterScheduler class - Track the registration of instruction schedulers.
101///
102//===---------------------------------------------------------------------===//
103MachinePassRegistry RegisterScheduler::Registry;
104
105//===---------------------------------------------------------------------===//
106///
107/// ISHeuristic command line option for instruction schedulers.
108///
109//===---------------------------------------------------------------------===//
Dan Gohman844731a2008-05-13 00:00:25 +0000110static cl::opt<RegisterScheduler::FunctionPassCtor, false,
111 RegisterPassParser<RegisterScheduler> >
112ISHeuristic("pre-RA-sched",
113 cl::init(&createDefaultScheduler),
114 cl::desc("Instruction schedulers available (before register"
115 " allocation):"));
Jim Laskey13ec7022006-08-01 14:21:23 +0000116
Dan Gohman844731a2008-05-13 00:00:25 +0000117static RegisterScheduler
118defaultListDAGScheduler("default", " Best scheduler for the target",
119 createDefaultScheduler);
Evan Cheng4ef10862006-01-23 07:01:07 +0000120
Evan Cheng5c807602008-02-26 02:33:44 +0000121namespace { struct SDISelAsmOperandInfo; }
Chris Lattnerbf996f12007-04-30 17:29:31 +0000122
Dan Gohman1d685a42008-06-07 02:02:36 +0000123/// ComputeLinearIndex - Given an LLVM IR aggregate type and a sequence
124/// insertvalue or extractvalue indices that identify a member, return
125/// the linearized index of the start of the member.
126///
127static unsigned ComputeLinearIndex(const TargetLowering &TLI, const Type *Ty,
128 const unsigned *Indices,
129 const unsigned *IndicesEnd,
130 unsigned CurIndex = 0) {
131 // Base case: We're done.
Dan Gohman8f36f6d2008-06-20 00:53:00 +0000132 if (Indices && Indices == IndicesEnd)
Dan Gohman1d685a42008-06-07 02:02:36 +0000133 return CurIndex;
134
Chris Lattnerf899fce2008-04-27 23:48:12 +0000135 // Given a struct type, recursively traverse the elements.
136 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
Dan Gohman8f36f6d2008-06-20 00:53:00 +0000137 for (StructType::element_iterator EB = STy->element_begin(),
138 EI = EB,
Dan Gohman1d685a42008-06-07 02:02:36 +0000139 EE = STy->element_end();
140 EI != EE; ++EI) {
Dan Gohman8f36f6d2008-06-20 00:53:00 +0000141 if (Indices && *Indices == unsigned(EI - EB))
142 return ComputeLinearIndex(TLI, *EI, Indices+1, IndicesEnd, CurIndex);
143 CurIndex = ComputeLinearIndex(TLI, *EI, 0, 0, CurIndex);
Dan Gohman1d685a42008-06-07 02:02:36 +0000144 }
145 }
146 // Given an array type, recursively traverse the elements.
147 else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
148 const Type *EltTy = ATy->getElementType();
149 for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i) {
Dan Gohman8f36f6d2008-06-20 00:53:00 +0000150 if (Indices && *Indices == i)
151 return ComputeLinearIndex(TLI, EltTy, Indices+1, IndicesEnd, CurIndex);
152 CurIndex = ComputeLinearIndex(TLI, EltTy, 0, 0, CurIndex);
Dan Gohman1d685a42008-06-07 02:02:36 +0000153 }
154 }
155 // We haven't found the type we're looking for, so keep searching.
Dan Gohman8f36f6d2008-06-20 00:53:00 +0000156 return CurIndex + 1;
Dan Gohman1d685a42008-06-07 02:02:36 +0000157}
158
159/// ComputeValueVTs - Given an LLVM IR type, compute a sequence of
160/// MVTs that represent all the individual underlying
161/// non-aggregate types that comprise it.
162///
163/// If Offsets is non-null, it points to a vector to be filled in
164/// with the in-memory offsets of each of the individual values.
165///
166static void ComputeValueVTs(const TargetLowering &TLI, const Type *Ty,
167 SmallVectorImpl<MVT> &ValueVTs,
168 SmallVectorImpl<uint64_t> *Offsets = 0,
169 uint64_t StartingOffset = 0) {
170 // Given a struct type, recursively traverse the elements.
171 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
172 const StructLayout *SL = TLI.getTargetData()->getStructLayout(STy);
173 for (StructType::element_iterator EB = STy->element_begin(),
174 EI = EB,
175 EE = STy->element_end();
176 EI != EE; ++EI)
177 ComputeValueVTs(TLI, *EI, ValueVTs, Offsets,
178 StartingOffset + SL->getElementOffset(EI - EB));
Chris Lattnerf899fce2008-04-27 23:48:12 +0000179 return;
Dan Gohman23ce5022008-04-25 18:27:55 +0000180 }
Chris Lattnerf899fce2008-04-27 23:48:12 +0000181 // Given an array type, recursively traverse the elements.
182 if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
183 const Type *EltTy = ATy->getElementType();
Dan Gohman1d685a42008-06-07 02:02:36 +0000184 uint64_t EltSize = TLI.getTargetData()->getABITypeSize(EltTy);
Chris Lattnerf899fce2008-04-27 23:48:12 +0000185 for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i)
Dan Gohman1d685a42008-06-07 02:02:36 +0000186 ComputeValueVTs(TLI, EltTy, ValueVTs, Offsets,
187 StartingOffset + i * EltSize);
Chris Lattnerf899fce2008-04-27 23:48:12 +0000188 return;
189 }
Duncan Sands83ec4b62008-06-06 12:08:01 +0000190 // Base case: we can get an MVT for this LLVM IR type.
Chris Lattnerf899fce2008-04-27 23:48:12 +0000191 ValueVTs.push_back(TLI.getValueType(Ty));
Dan Gohman1d685a42008-06-07 02:02:36 +0000192 if (Offsets)
193 Offsets->push_back(StartingOffset);
Chris Lattnerf899fce2008-04-27 23:48:12 +0000194}
Dan Gohman23ce5022008-04-25 18:27:55 +0000195
Chris Lattnerf899fce2008-04-27 23:48:12 +0000196namespace {
Dan Gohman0fe00902008-04-28 18:10:39 +0000197 /// RegsForValue - This struct represents the registers (physical or virtual)
198 /// that a particular set of values is assigned, and the type information about
199 /// the value. The most common situation is to represent one value at a time,
200 /// but struct or array values are handled element-wise as multiple values.
201 /// The splitting of aggregates is performed recursively, so that we never
202 /// have aggregate-typed registers. The values at this point do not necessarily
203 /// have legal types, so each value may require one or more registers of some
204 /// legal type.
205 ///
Chris Lattner95255282006-06-28 23:17:24 +0000206 struct VISIBILITY_HIDDEN RegsForValue {
Dan Gohman23ce5022008-04-25 18:27:55 +0000207 /// TLI - The TargetLowering object.
Dan Gohman0fe00902008-04-28 18:10:39 +0000208 ///
Dan Gohman23ce5022008-04-25 18:27:55 +0000209 const TargetLowering *TLI;
210
Dan Gohman0fe00902008-04-28 18:10:39 +0000211 /// ValueVTs - The value types of the values, which may not be legal, and
212 /// may need be promoted or synthesized from one or more registers.
213 ///
Duncan Sands83ec4b62008-06-06 12:08:01 +0000214 SmallVector<MVT, 4> ValueVTs;
Chris Lattner864635a2006-02-22 22:37:12 +0000215
Dan Gohman0fe00902008-04-28 18:10:39 +0000216 /// RegVTs - The value types of the registers. This is the same size as
217 /// ValueVTs and it records, for each value, what the type of the assigned
218 /// register or registers are. (Individual values are never synthesized
219 /// from more than one type of register.)
220 ///
221 /// With virtual registers, the contents of RegVTs is redundant with TLI's
222 /// getRegisterType member function, however when with physical registers
223 /// it is necessary to have a separate record of the types.
Chris Lattner864635a2006-02-22 22:37:12 +0000224 ///
Duncan Sands83ec4b62008-06-06 12:08:01 +0000225 SmallVector<MVT, 4> RegVTs;
Chris Lattner864635a2006-02-22 22:37:12 +0000226
Dan Gohman0fe00902008-04-28 18:10:39 +0000227 /// Regs - This list holds the registers assigned to the values.
228 /// Each legal or promoted value requires one register, and each
229 /// expanded value requires multiple registers.
230 ///
231 SmallVector<unsigned, 4> Regs;
Chris Lattner864635a2006-02-22 22:37:12 +0000232
Dan Gohman23ce5022008-04-25 18:27:55 +0000233 RegsForValue() : TLI(0) {}
Chris Lattner864635a2006-02-22 22:37:12 +0000234
Dan Gohman23ce5022008-04-25 18:27:55 +0000235 RegsForValue(const TargetLowering &tli,
Chris Lattnerb606dba2008-04-28 06:44:42 +0000236 const SmallVector<unsigned, 4> &regs,
Duncan Sands83ec4b62008-06-06 12:08:01 +0000237 MVT regvt, MVT valuevt)
Dan Gohman0fe00902008-04-28 18:10:39 +0000238 : TLI(&tli), ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs) {}
Dan Gohman23ce5022008-04-25 18:27:55 +0000239 RegsForValue(const TargetLowering &tli,
Chris Lattnerb606dba2008-04-28 06:44:42 +0000240 const SmallVector<unsigned, 4> &regs,
Duncan Sands83ec4b62008-06-06 12:08:01 +0000241 const SmallVector<MVT, 4> &regvts,
242 const SmallVector<MVT, 4> &valuevts)
Dan Gohman0fe00902008-04-28 18:10:39 +0000243 : TLI(&tli), ValueVTs(valuevts), RegVTs(regvts), Regs(regs) {}
Dan Gohman23ce5022008-04-25 18:27:55 +0000244 RegsForValue(const TargetLowering &tli,
245 unsigned Reg, const Type *Ty) : TLI(&tli) {
246 ComputeValueVTs(tli, Ty, ValueVTs);
247
Dan Gohmanb20d4f82008-04-28 17:42:03 +0000248 for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
Duncan Sands83ec4b62008-06-06 12:08:01 +0000249 MVT ValueVT = ValueVTs[Value];
Dan Gohman23ce5022008-04-25 18:27:55 +0000250 unsigned NumRegs = TLI->getNumRegisters(ValueVT);
Duncan Sands83ec4b62008-06-06 12:08:01 +0000251 MVT RegisterVT = TLI->getRegisterType(ValueVT);
Dan Gohman23ce5022008-04-25 18:27:55 +0000252 for (unsigned i = 0; i != NumRegs; ++i)
253 Regs.push_back(Reg + i);
254 RegVTs.push_back(RegisterVT);
255 Reg += NumRegs;
256 }
Chris Lattner864635a2006-02-22 22:37:12 +0000257 }
258
Chris Lattner41f62592008-04-29 04:29:54 +0000259 /// append - Add the specified values to this one.
260 void append(const RegsForValue &RHS) {
261 TLI = RHS.TLI;
262 ValueVTs.append(RHS.ValueVTs.begin(), RHS.ValueVTs.end());
263 RegVTs.append(RHS.RegVTs.begin(), RHS.RegVTs.end());
264 Regs.append(RHS.Regs.begin(), RHS.Regs.end());
265 }
266
267
Chris Lattner864635a2006-02-22 22:37:12 +0000268 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
Dan Gohman23ce5022008-04-25 18:27:55 +0000269 /// this value and returns the result as a ValueVTs value. This uses
Chris Lattner864635a2006-02-22 22:37:12 +0000270 /// Chain/Flag as the input and updates them for the output Chain/Flag.
Dan Gohmanb6f5b002007-06-28 23:29:44 +0000271 /// If the Flag pointer is NULL, no flag is used.
Dan Gohman475871a2008-07-27 21:46:04 +0000272 SDValue getCopyFromRegs(SelectionDAG &DAG,
273 SDValue &Chain, SDValue *Flag) const;
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +0000274
275 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
276 /// specified value into the registers specified by this object. This uses
277 /// Chain/Flag as the input and updates them for the output Chain/Flag.
Dan Gohmanb6f5b002007-06-28 23:29:44 +0000278 /// If the Flag pointer is NULL, no flag is used.
Dan Gohman475871a2008-07-27 21:46:04 +0000279 void getCopyToRegs(SDValue Val, SelectionDAG &DAG,
280 SDValue &Chain, SDValue *Flag) const;
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +0000281
282 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
283 /// operand list. This adds the code marker and includes the number of
284 /// values added into it.
285 void AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
Dan Gohman475871a2008-07-27 21:46:04 +0000286 std::vector<SDValue> &Ops) const;
Chris Lattner864635a2006-02-22 22:37:12 +0000287 };
288}
Evan Cheng4ef10862006-01-23 07:01:07 +0000289
Chris Lattner1c08c712005-01-07 07:47:53 +0000290namespace llvm {
291 //===--------------------------------------------------------------------===//
Jim Laskey9373beb2006-08-01 19:14:14 +0000292 /// createDefaultScheduler - This creates an instruction scheduler appropriate
293 /// for the target.
294 ScheduleDAG* createDefaultScheduler(SelectionDAGISel *IS,
295 SelectionDAG *DAG,
Evan Cheng4576f6d2008-07-01 18:05:03 +0000296 MachineBasicBlock *BB,
297 bool Fast) {
Jim Laskey9373beb2006-08-01 19:14:14 +0000298 TargetLowering &TLI = IS->getTargetLowering();
299
300 if (TLI.getSchedulingPreference() == TargetLowering::SchedulingForLatency) {
Evan Cheng4576f6d2008-07-01 18:05:03 +0000301 return createTDListDAGScheduler(IS, DAG, BB, Fast);
Jim Laskey9373beb2006-08-01 19:14:14 +0000302 } else {
303 assert(TLI.getSchedulingPreference() ==
304 TargetLowering::SchedulingForRegPressure && "Unknown sched type!");
Evan Cheng4576f6d2008-07-01 18:05:03 +0000305 return createBURRListDAGScheduler(IS, DAG, BB, Fast);
Jim Laskey9373beb2006-08-01 19:14:14 +0000306 }
307 }
308
309
310 //===--------------------------------------------------------------------===//
Chris Lattner1c08c712005-01-07 07:47:53 +0000311 /// FunctionLoweringInfo - This contains information that is global to a
312 /// function that is used when lowering a region of the function.
Chris Lattnerf26bc8e2005-01-08 19:52:31 +0000313 class FunctionLoweringInfo {
314 public:
Chris Lattner1c08c712005-01-07 07:47:53 +0000315 TargetLowering &TLI;
316 Function &Fn;
317 MachineFunction &MF;
Chris Lattner84bc5422007-12-31 04:13:23 +0000318 MachineRegisterInfo &RegInfo;
Chris Lattner1c08c712005-01-07 07:47:53 +0000319
320 FunctionLoweringInfo(TargetLowering &TLI, Function &Fn,MachineFunction &MF);
321
322 /// MBBMap - A mapping from LLVM basic blocks to their machine code entry.
Dan Gohman6ecf5092008-08-23 02:44:46 +0000323 DenseMap<const BasicBlock*, MachineBasicBlock *> MBBMap;
Chris Lattner1c08c712005-01-07 07:47:53 +0000324
325 /// ValueMap - Since we emit code for the function a basic block at a time,
326 /// we must remember which virtual registers hold the values for
327 /// cross-basic-block values.
Chris Lattner9f24ad72007-02-04 01:35:11 +0000328 DenseMap<const Value*, unsigned> ValueMap;
Chris Lattner1c08c712005-01-07 07:47:53 +0000329
330 /// StaticAllocaMap - Keep track of frame indices for fixed sized allocas in
331 /// the entry block. This allows the allocas to be efficiently referenced
332 /// anywhere in the function.
Dan Gohman6ecf5092008-08-23 02:44:46 +0000333 DenseMap<const AllocaInst*, int> StaticAllocaMap;
Chris Lattner1c08c712005-01-07 07:47:53 +0000334
Duncan Sandsf4070822007-06-15 19:04:19 +0000335#ifndef NDEBUG
336 SmallSet<Instruction*, 8> CatchInfoLost;
337 SmallSet<Instruction*, 8> CatchInfoFound;
338#endif
339
Duncan Sands83ec4b62008-06-06 12:08:01 +0000340 unsigned MakeReg(MVT VT) {
Chris Lattner84bc5422007-12-31 04:13:23 +0000341 return RegInfo.createVirtualRegister(TLI.getRegClassFor(VT));
Chris Lattner1c08c712005-01-07 07:47:53 +0000342 }
Chris Lattner571e4342006-10-27 21:36:01 +0000343
344 /// isExportedInst - Return true if the specified value is an instruction
345 /// exported from its block.
346 bool isExportedInst(const Value *V) {
347 return ValueMap.count(V);
348 }
Misha Brukmanedf128a2005-04-21 22:36:52 +0000349
Chris Lattner3c384492006-03-16 19:51:18 +0000350 unsigned CreateRegForValue(const Value *V);
351
Chris Lattner1c08c712005-01-07 07:47:53 +0000352 unsigned InitializeRegForValue(const Value *V) {
353 unsigned &R = ValueMap[V];
354 assert(R == 0 && "Already initialized this value register!");
355 return R = CreateRegForValue(V);
356 }
Chris Lattneread0d882008-06-17 06:09:18 +0000357
358 struct LiveOutInfo {
359 unsigned NumSignBits;
360 APInt KnownOne, KnownZero;
361 LiveOutInfo() : NumSignBits(0) {}
362 };
363
364 /// LiveOutRegInfo - Information about live out vregs, indexed by their
365 /// register number offset by 'FirstVirtualRegister'.
366 std::vector<LiveOutInfo> LiveOutRegInfo;
Chris Lattner1c08c712005-01-07 07:47:53 +0000367 };
368}
369
Duncan Sandscf26d7c2007-07-04 20:52:51 +0000370/// isSelector - Return true if this instruction is a call to the
371/// eh.selector intrinsic.
372static bool isSelector(Instruction *I) {
Duncan Sandsf4070822007-06-15 19:04:19 +0000373 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
Anton Korobeynikov8806c7b2007-09-07 11:39:35 +0000374 return (II->getIntrinsicID() == Intrinsic::eh_selector_i32 ||
375 II->getIntrinsicID() == Intrinsic::eh_selector_i64);
Duncan Sandsf4070822007-06-15 19:04:19 +0000376 return false;
377}
378
Chris Lattner1c08c712005-01-07 07:47:53 +0000379/// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by
Nate Begemanf15485a2006-03-27 01:32:24 +0000380/// PHI nodes or outside of the basic block that defines it, or used by a
Andrew Lenharthab0b9492008-02-21 06:45:13 +0000381/// switch or atomic instruction, which may expand to multiple basic blocks.
Chris Lattner1c08c712005-01-07 07:47:53 +0000382static bool isUsedOutsideOfDefiningBlock(Instruction *I) {
383 if (isa<PHINode>(I)) return true;
384 BasicBlock *BB = I->getParent();
385 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; ++UI)
Nate Begemanf15485a2006-03-27 01:32:24 +0000386 if (cast<Instruction>(*UI)->getParent() != BB || isa<PHINode>(*UI) ||
Chris Lattner571e4342006-10-27 21:36:01 +0000387 // FIXME: Remove switchinst special case.
Nate Begemanf15485a2006-03-27 01:32:24 +0000388 isa<SwitchInst>(*UI))
Chris Lattner1c08c712005-01-07 07:47:53 +0000389 return true;
390 return false;
391}
392
Chris Lattnerbf209482005-10-30 19:42:35 +0000393/// isOnlyUsedInEntryBlock - If the specified argument is only used in the
Nate Begemanf15485a2006-03-27 01:32:24 +0000394/// entry block, return true. This includes arguments used by switches, since
395/// the switch may expand into multiple basic blocks.
Chris Lattnerbf209482005-10-30 19:42:35 +0000396static bool isOnlyUsedInEntryBlock(Argument *A) {
Dan Gohmanf350b272008-08-23 02:25:05 +0000397 // With FastISel active, we may be splitting blocks, so force creation
398 // of virtual registers for all non-dead arguments.
399 if (EnableFastISel)
400 return A->use_empty();
401
Chris Lattnerbf209482005-10-30 19:42:35 +0000402 BasicBlock *Entry = A->getParent()->begin();
403 for (Value::use_iterator UI = A->use_begin(), E = A->use_end(); UI != E; ++UI)
Nate Begemanf15485a2006-03-27 01:32:24 +0000404 if (cast<Instruction>(*UI)->getParent() != Entry || isa<SwitchInst>(*UI))
Chris Lattnerbf209482005-10-30 19:42:35 +0000405 return false; // Use not in entry block.
406 return true;
407}
408
Chris Lattner1c08c712005-01-07 07:47:53 +0000409FunctionLoweringInfo::FunctionLoweringInfo(TargetLowering &tli,
Misha Brukmanedf128a2005-04-21 22:36:52 +0000410 Function &fn, MachineFunction &mf)
Chris Lattner84bc5422007-12-31 04:13:23 +0000411 : TLI(tli), Fn(fn), MF(mf), RegInfo(MF.getRegInfo()) {
Chris Lattner1c08c712005-01-07 07:47:53 +0000412
Chris Lattnerbf209482005-10-30 19:42:35 +0000413 // Create a vreg for each argument register that is not dead and is used
414 // outside of the entry block for the function.
415 for (Function::arg_iterator AI = Fn.arg_begin(), E = Fn.arg_end();
416 AI != E; ++AI)
417 if (!isOnlyUsedInEntryBlock(AI))
418 InitializeRegForValue(AI);
419
Chris Lattner1c08c712005-01-07 07:47:53 +0000420 // Initialize the mapping of values to registers. This is only set up for
421 // instruction values that are used outside of the block that defines
422 // them.
Jeff Cohen2aeaf4e2005-10-01 03:57:14 +0000423 Function::iterator BB = Fn.begin(), EB = Fn.end();
Chris Lattner1c08c712005-01-07 07:47:53 +0000424 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
425 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
Reid Spencerb83eb642006-10-20 07:07:24 +0000426 if (ConstantInt *CUI = dyn_cast<ConstantInt>(AI->getArraySize())) {
Chris Lattner1c08c712005-01-07 07:47:53 +0000427 const Type *Ty = AI->getAllocatedType();
Duncan Sands514ab342007-11-01 20:53:16 +0000428 uint64_t TySize = TLI.getTargetData()->getABITypeSize(Ty);
Nate Begemanae232e72005-11-06 09:00:38 +0000429 unsigned Align =
Chris Lattnerd2b7cec2007-02-14 05:52:17 +0000430 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
Nate Begemanae232e72005-11-06 09:00:38 +0000431 AI->getAlignment());
Chris Lattnera8217e32005-05-13 23:14:17 +0000432
Reid Spencerb83eb642006-10-20 07:07:24 +0000433 TySize *= CUI->getZExtValue(); // Get total allocated size.
Chris Lattnerd222f6a2005-10-18 22:14:06 +0000434 if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
Chris Lattner1c08c712005-01-07 07:47:53 +0000435 StaticAllocaMap[AI] =
Chris Lattner6266c182007-04-25 04:08:28 +0000436 MF.getFrameInfo()->CreateStackObject(TySize, Align);
Chris Lattner1c08c712005-01-07 07:47:53 +0000437 }
438
Jeff Cohen2aeaf4e2005-10-01 03:57:14 +0000439 for (; BB != EB; ++BB)
440 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
Chris Lattner1c08c712005-01-07 07:47:53 +0000441 if (!I->use_empty() && isUsedOutsideOfDefiningBlock(I))
442 if (!isa<AllocaInst>(I) ||
443 !StaticAllocaMap.count(cast<AllocaInst>(I)))
444 InitializeRegForValue(I);
445
446 // Create an initial MachineBasicBlock for each LLVM BasicBlock in F. This
447 // also creates the initial PHI MachineInstrs, though none of the input
448 // operands are populated.
Jeff Cohen2aeaf4e2005-10-01 03:57:14 +0000449 for (BB = Fn.begin(), EB = Fn.end(); BB != EB; ++BB) {
Dan Gohman0e5f1302008-07-07 23:02:41 +0000450 MachineBasicBlock *MBB = mf.CreateMachineBasicBlock(BB);
Chris Lattner1c08c712005-01-07 07:47:53 +0000451 MBBMap[BB] = MBB;
Dan Gohman0e5f1302008-07-07 23:02:41 +0000452 MF.push_back(MBB);
Chris Lattner1c08c712005-01-07 07:47:53 +0000453
454 // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
455 // appropriate.
456 PHINode *PN;
Chris Lattner8c494ab2006-10-27 23:50:33 +0000457 for (BasicBlock::iterator I = BB->begin();(PN = dyn_cast<PHINode>(I)); ++I){
458 if (PN->use_empty()) continue;
459
Chris Lattner8c494ab2006-10-27 23:50:33 +0000460 unsigned PHIReg = ValueMap[PN];
461 assert(PHIReg && "PHI node does not have an assigned virtual register!");
Dan Gohman6f498b02008-08-04 23:42:46 +0000462
463 SmallVector<MVT, 4> ValueVTs;
464 ComputeValueVTs(TLI, PN->getType(), ValueVTs);
465 for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
466 MVT VT = ValueVTs[vti];
467 unsigned NumRegisters = TLI.getNumRegisters(VT);
468 const TargetInstrInfo *TII = TLI.getTargetMachine().getInstrInfo();
469 for (unsigned i = 0; i != NumRegisters; ++i)
470 BuildMI(MBB, TII->get(TargetInstrInfo::PHI), PHIReg+i);
471 PHIReg += NumRegisters;
472 }
Chris Lattner8c494ab2006-10-27 23:50:33 +0000473 }
Chris Lattner1c08c712005-01-07 07:47:53 +0000474 }
475}
476
Chris Lattner3c384492006-03-16 19:51:18 +0000477/// CreateRegForValue - Allocate the appropriate number of virtual registers of
478/// the correctly promoted or expanded types. Assign these registers
479/// consecutive vreg numbers and return the first assigned number.
Dan Gohman10a6b7a2008-04-28 18:19:43 +0000480///
481/// In the case that the given value has struct or array type, this function
482/// will assign registers for each member or element.
483///
Chris Lattner3c384492006-03-16 19:51:18 +0000484unsigned FunctionLoweringInfo::CreateRegForValue(const Value *V) {
Duncan Sands83ec4b62008-06-06 12:08:01 +0000485 SmallVector<MVT, 4> ValueVTs;
Chris Lattnerb606dba2008-04-28 06:44:42 +0000486 ComputeValueVTs(TLI, V->getType(), ValueVTs);
Bill Wendling95b39552007-04-24 21:13:23 +0000487
Dan Gohman23ce5022008-04-25 18:27:55 +0000488 unsigned FirstReg = 0;
Dan Gohmanb20d4f82008-04-28 17:42:03 +0000489 for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
Duncan Sands83ec4b62008-06-06 12:08:01 +0000490 MVT ValueVT = ValueVTs[Value];
491 MVT RegisterVT = TLI.getRegisterType(ValueVT);
Dan Gohman8c8c5fc2007-06-27 14:34:07 +0000492
Chris Lattnerb606dba2008-04-28 06:44:42 +0000493 unsigned NumRegs = TLI.getNumRegisters(ValueVT);
Dan Gohman23ce5022008-04-25 18:27:55 +0000494 for (unsigned i = 0; i != NumRegs; ++i) {
495 unsigned R = MakeReg(RegisterVT);
496 if (!FirstReg) FirstReg = R;
497 }
498 }
499 return FirstReg;
Chris Lattner3c384492006-03-16 19:51:18 +0000500}
Chris Lattner1c08c712005-01-07 07:47:53 +0000501
502//===----------------------------------------------------------------------===//
503/// SelectionDAGLowering - This is the common target-independent lowering
504/// implementation that is parameterized by a TargetLowering object.
505/// Also, targets can overload any lowering method.
506///
507namespace llvm {
508class SelectionDAGLowering {
509 MachineBasicBlock *CurMBB;
510
Dan Gohman475871a2008-07-27 21:46:04 +0000511 DenseMap<const Value*, SDValue> NodeMap;
Chris Lattner1c08c712005-01-07 07:47:53 +0000512
Chris Lattnerd3948112005-01-17 22:19:26 +0000513 /// PendingLoads - Loads are not emitted to the program immediately. We bunch
514 /// them up and then emit token factor nodes when possible. This allows us to
515 /// get simple disambiguation between loads without worrying about alias
516 /// analysis.
Dan Gohman475871a2008-07-27 21:46:04 +0000517 SmallVector<SDValue, 8> PendingLoads;
Chris Lattnerd3948112005-01-17 22:19:26 +0000518
Dan Gohman86e1ebf2008-03-27 19:56:19 +0000519 /// PendingExports - CopyToReg nodes that copy values to virtual registers
520 /// for export to other blocks need to be emitted before any terminator
521 /// instruction, but they have no other ordering requirements. We bunch them
522 /// up and the emit a single tokenfactor for them just before terminator
523 /// instructions.
Dan Gohman475871a2008-07-27 21:46:04 +0000524 std::vector<SDValue> PendingExports;
Dan Gohman86e1ebf2008-03-27 19:56:19 +0000525
Anton Korobeynikov5502bf62007-04-04 21:14:49 +0000526 /// Case - A struct to record the Value for a switch case, and the
527 /// case's target basic block.
528 struct Case {
529 Constant* Low;
530 Constant* High;
531 MachineBasicBlock* BB;
532
533 Case() : Low(0), High(0), BB(0) { }
534 Case(Constant* low, Constant* high, MachineBasicBlock* bb) :
535 Low(low), High(high), BB(bb) { }
536 uint64_t size() const {
537 uint64_t rHigh = cast<ConstantInt>(High)->getSExtValue();
538 uint64_t rLow = cast<ConstantInt>(Low)->getSExtValue();
539 return (rHigh - rLow + 1ULL);
540 }
541 };
542
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000543 struct CaseBits {
544 uint64_t Mask;
545 MachineBasicBlock* BB;
546 unsigned Bits;
547
548 CaseBits(uint64_t mask, MachineBasicBlock* bb, unsigned bits):
549 Mask(mask), BB(bb), Bits(bits) { }
550 };
551
Anton Korobeynikov5502bf62007-04-04 21:14:49 +0000552 typedef std::vector<Case> CaseVector;
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000553 typedef std::vector<CaseBits> CaseBitsVector;
Anton Korobeynikov5502bf62007-04-04 21:14:49 +0000554 typedef CaseVector::iterator CaseItr;
555 typedef std::pair<CaseItr, CaseItr> CaseRange;
Nate Begemanf15485a2006-03-27 01:32:24 +0000556
557 /// CaseRec - A struct with ctor used in lowering switches to a binary tree
558 /// of conditional branches.
559 struct CaseRec {
560 CaseRec(MachineBasicBlock *bb, Constant *lt, Constant *ge, CaseRange r) :
561 CaseBB(bb), LT(lt), GE(ge), Range(r) {}
562
563 /// CaseBB - The MBB in which to emit the compare and branch
564 MachineBasicBlock *CaseBB;
565 /// LT, GE - If nonzero, we know the current case value must be less-than or
566 /// greater-than-or-equal-to these Constants.
567 Constant *LT;
568 Constant *GE;
569 /// Range - A pair of iterators representing the range of case values to be
570 /// processed at this point in the binary search tree.
571 CaseRange Range;
572 };
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +0000573
574 typedef std::vector<CaseRec> CaseRecVector;
Anton Korobeynikov5502bf62007-04-04 21:14:49 +0000575
576 /// The comparison function for sorting the switch case values in the vector.
577 /// WARNING: Case ranges should be disjoint!
Nate Begemanf15485a2006-03-27 01:32:24 +0000578 struct CaseCmp {
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000579 bool operator () (const Case& C1, const Case& C2) {
Anton Korobeynikov5502bf62007-04-04 21:14:49 +0000580 assert(isa<ConstantInt>(C1.Low) && isa<ConstantInt>(C2.High));
581 const ConstantInt* CI1 = cast<const ConstantInt>(C1.Low);
582 const ConstantInt* CI2 = cast<const ConstantInt>(C2.High);
583 return CI1->getValue().slt(CI2->getValue());
Nate Begemanf15485a2006-03-27 01:32:24 +0000584 }
585 };
Anton Korobeynikov5502bf62007-04-04 21:14:49 +0000586
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000587 struct CaseBitsCmp {
588 bool operator () (const CaseBits& C1, const CaseBits& C2) {
589 return C1.Bits > C2.Bits;
590 }
591 };
592
Anton Korobeynikov5502bf62007-04-04 21:14:49 +0000593 unsigned Clusterify(CaseVector& Cases, const SwitchInst &SI);
Nate Begemanf15485a2006-03-27 01:32:24 +0000594
Chris Lattner1c08c712005-01-07 07:47:53 +0000595public:
596 // TLI - This is information that describes the available target features we
597 // need for lowering. This indicates when operations are unavailable,
598 // implemented with a libcall, etc.
599 TargetLowering &TLI;
600 SelectionDAG &DAG;
Owen Andersona69571c2006-05-03 01:29:57 +0000601 const TargetData *TD;
Dan Gohman5f43f922007-08-27 16:26:13 +0000602 AliasAnalysis &AA;
Chris Lattner1c08c712005-01-07 07:47:53 +0000603
Nate Begemanf15485a2006-03-27 01:32:24 +0000604 /// SwitchCases - Vector of CaseBlock structures used to communicate
605 /// SwitchInst code generation information.
606 std::vector<SelectionDAGISel::CaseBlock> SwitchCases;
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +0000607 /// JTCases - Vector of JumpTable structures used to communicate
608 /// SwitchInst code generation information.
609 std::vector<SelectionDAGISel::JumpTableBlock> JTCases;
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000610 std::vector<SelectionDAGISel::BitTestBlock> BitTestCases;
Nate Begemanf15485a2006-03-27 01:32:24 +0000611
Chris Lattner1c08c712005-01-07 07:47:53 +0000612 /// FuncInfo - Information about the function as a whole.
613 ///
614 FunctionLoweringInfo &FuncInfo;
Gordon Henriksence224772008-01-07 01:30:38 +0000615
Gordon Henriksen5eca0752008-08-17 18:44:35 +0000616 /// GFI - Garbage collection metadata for the function.
617 GCFunctionInfo *GFI;
Chris Lattner1c08c712005-01-07 07:47:53 +0000618
619 SelectionDAGLowering(SelectionDAG &dag, TargetLowering &tli,
Dan Gohman5f43f922007-08-27 16:26:13 +0000620 AliasAnalysis &aa,
Gordon Henriksence224772008-01-07 01:30:38 +0000621 FunctionLoweringInfo &funcinfo,
Gordon Henriksen5eca0752008-08-17 18:44:35 +0000622 GCFunctionInfo *gfi)
Dan Gohman5f43f922007-08-27 16:26:13 +0000623 : TLI(tli), DAG(dag), TD(DAG.getTarget().getTargetData()), AA(aa),
Gordon Henriksen5eca0752008-08-17 18:44:35 +0000624 FuncInfo(funcinfo), GFI(gfi) {
Chris Lattner1c08c712005-01-07 07:47:53 +0000625 }
626
Dan Gohman86e1ebf2008-03-27 19:56:19 +0000627 /// getRoot - Return the current virtual root of the Selection DAG,
628 /// flushing any PendingLoad items. This must be done before emitting
629 /// a store or any other node that may need to be ordered after any
630 /// prior load instructions.
Chris Lattnera651cf62005-01-17 19:43:36 +0000631 ///
Dan Gohman475871a2008-07-27 21:46:04 +0000632 SDValue getRoot() {
Chris Lattnerd3948112005-01-17 22:19:26 +0000633 if (PendingLoads.empty())
634 return DAG.getRoot();
Misha Brukmanedf128a2005-04-21 22:36:52 +0000635
Chris Lattnerd3948112005-01-17 22:19:26 +0000636 if (PendingLoads.size() == 1) {
Dan Gohman475871a2008-07-27 21:46:04 +0000637 SDValue Root = PendingLoads[0];
Chris Lattnerd3948112005-01-17 22:19:26 +0000638 DAG.setRoot(Root);
639 PendingLoads.clear();
640 return Root;
641 }
642
643 // Otherwise, we have to make a token factor node.
Dan Gohman475871a2008-07-27 21:46:04 +0000644 SDValue Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
Chris Lattnerbd564bf2006-08-08 02:23:42 +0000645 &PendingLoads[0], PendingLoads.size());
Chris Lattnerd3948112005-01-17 22:19:26 +0000646 PendingLoads.clear();
647 DAG.setRoot(Root);
648 return Root;
Chris Lattnera651cf62005-01-17 19:43:36 +0000649 }
650
Dan Gohman86e1ebf2008-03-27 19:56:19 +0000651 /// getControlRoot - Similar to getRoot, but instead of flushing all the
652 /// PendingLoad items, flush all the PendingExports items. It is necessary
653 /// to do this before emitting a terminator instruction.
654 ///
Dan Gohman475871a2008-07-27 21:46:04 +0000655 SDValue getControlRoot() {
656 SDValue Root = DAG.getRoot();
Dan Gohman86e1ebf2008-03-27 19:56:19 +0000657
658 if (PendingExports.empty())
659 return Root;
660
661 // Turn all of the CopyToReg chains into one factored node.
662 if (Root.getOpcode() != ISD::EntryToken) {
663 unsigned i = 0, e = PendingExports.size();
664 for (; i != e; ++i) {
665 assert(PendingExports[i].Val->getNumOperands() > 1);
666 if (PendingExports[i].Val->getOperand(0) == Root)
667 break; // Don't add the root if we already indirectly depend on it.
668 }
669
670 if (i == e)
671 PendingExports.push_back(Root);
672 }
673
674 Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
675 &PendingExports[0],
676 PendingExports.size());
677 PendingExports.clear();
678 DAG.setRoot(Root);
679 return Root;
680 }
681
682 void CopyValueToVirtualRegister(Value *V, unsigned Reg);
Chris Lattner571e4342006-10-27 21:36:01 +0000683
Chris Lattner1c08c712005-01-07 07:47:53 +0000684 void visit(Instruction &I) { visit(I.getOpcode(), I); }
685
686 void visit(unsigned Opcode, User &I) {
Chris Lattner1e7aa5c2006-11-10 04:41:34 +0000687 // Note: this doesn't use InstVisitor, because it has to work with
688 // ConstantExpr's in addition to instructions.
Chris Lattner1c08c712005-01-07 07:47:53 +0000689 switch (Opcode) {
690 default: assert(0 && "Unknown instruction type encountered!");
691 abort();
692 // Build the switch statement using the Instruction.def file.
693#define HANDLE_INST(NUM, OPCODE, CLASS) \
694 case Instruction::OPCODE:return visit##OPCODE((CLASS&)I);
695#include "llvm/Instruction.def"
696 }
697 }
698
699 void setCurrentBasicBlock(MachineBasicBlock *MBB) { CurMBB = MBB; }
700
Dan Gohman475871a2008-07-27 21:46:04 +0000701 SDValue getValue(const Value *V);
Chris Lattner1c08c712005-01-07 07:47:53 +0000702
Dan Gohman475871a2008-07-27 21:46:04 +0000703 void setValue(const Value *V, SDValue NewN) {
704 SDValue &N = NodeMap[V];
Chris Lattner1c08c712005-01-07 07:47:53 +0000705 assert(N.Val == 0 && "Already set a value for this node!");
Chris Lattner0da331f2007-02-04 01:31:47 +0000706 N = NewN;
Chris Lattner1c08c712005-01-07 07:47:53 +0000707 }
Chris Lattner4e4b5762006-02-01 18:59:47 +0000708
Evan Cheng5c807602008-02-26 02:33:44 +0000709 void GetRegistersForValue(SDISelAsmOperandInfo &OpInfo, bool HasEarlyClobber,
Chris Lattnere7cf56a2007-04-30 21:11:17 +0000710 std::set<unsigned> &OutputRegs,
711 std::set<unsigned> &InputRegs);
Nate Begemanf15485a2006-03-27 01:32:24 +0000712
Chris Lattner571e4342006-10-27 21:36:01 +0000713 void FindMergedConditions(Value *Cond, MachineBasicBlock *TBB,
714 MachineBasicBlock *FBB, MachineBasicBlock *CurBB,
715 unsigned Opc);
Chris Lattner8c494ab2006-10-27 23:50:33 +0000716 bool isExportableFromCurrentBlock(Value *V, const BasicBlock *FromBB);
Chris Lattner571e4342006-10-27 21:36:01 +0000717 void ExportFromCurrentBlock(Value *V);
Dan Gohman475871a2008-07-27 21:46:04 +0000718 void LowerCallTo(CallSite CS, SDValue Callee, bool IsTailCall,
Anton Korobeynikov070280e2007-05-23 11:08:31 +0000719 MachineBasicBlock *LandingPad = NULL);
Duncan Sandsdc024672007-11-27 13:23:08 +0000720
Chris Lattner1c08c712005-01-07 07:47:53 +0000721 // Terminator instructions.
722 void visitRet(ReturnInst &I);
723 void visitBr(BranchInst &I);
Nate Begemanf15485a2006-03-27 01:32:24 +0000724 void visitSwitch(SwitchInst &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000725 void visitUnreachable(UnreachableInst &I) { /* noop */ }
726
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +0000727 // Helpers for visitSwitch
Anton Korobeynikovdd433212007-03-27 12:05:48 +0000728 bool handleSmallSwitchRange(CaseRec& CR,
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +0000729 CaseRecVector& WorkList,
730 Value* SV,
731 MachineBasicBlock* Default);
Anton Korobeynikovdd433212007-03-27 12:05:48 +0000732 bool handleJTSwitchCase(CaseRec& CR,
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +0000733 CaseRecVector& WorkList,
734 Value* SV,
735 MachineBasicBlock* Default);
Anton Korobeynikovdd433212007-03-27 12:05:48 +0000736 bool handleBTSplitSwitchCase(CaseRec& CR,
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +0000737 CaseRecVector& WorkList,
738 Value* SV,
739 MachineBasicBlock* Default);
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000740 bool handleBitTestsSwitchCase(CaseRec& CR,
741 CaseRecVector& WorkList,
742 Value* SV,
743 MachineBasicBlock* Default);
Nate Begemanf15485a2006-03-27 01:32:24 +0000744 void visitSwitchCase(SelectionDAGISel::CaseBlock &CB);
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000745 void visitBitTestHeader(SelectionDAGISel::BitTestBlock &B);
746 void visitBitTestCase(MachineBasicBlock* NextMBB,
747 unsigned Reg,
748 SelectionDAGISel::BitTestCase &B);
Nate Begeman37efe672006-04-22 18:53:45 +0000749 void visitJumpTable(SelectionDAGISel::JumpTable &JT);
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +0000750 void visitJumpTableHeader(SelectionDAGISel::JumpTable &JT,
751 SelectionDAGISel::JumpTableHeader &JTH);
Nate Begemanf15485a2006-03-27 01:32:24 +0000752
Chris Lattner1c08c712005-01-07 07:47:53 +0000753 // These all get lowered before this pass.
Jim Laskeyb180aa12007-02-21 22:53:45 +0000754 void visitInvoke(InvokeInst &I);
755 void visitUnwind(UnwindInst &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000756
Dan Gohman7f321562007-06-25 16:23:39 +0000757 void visitBinary(User &I, unsigned OpCode);
Nate Begemane21ea612005-11-18 07:42:56 +0000758 void visitShift(User &I, unsigned Opcode);
Nate Begeman5fbb5d22005-11-19 00:36:38 +0000759 void visitAdd(User &I) {
Dan Gohman7f321562007-06-25 16:23:39 +0000760 if (I.getType()->isFPOrFPVector())
761 visitBinary(I, ISD::FADD);
Reid Spencer1628cec2006-10-26 06:15:43 +0000762 else
Dan Gohman7f321562007-06-25 16:23:39 +0000763 visitBinary(I, ISD::ADD);
Chris Lattner01b3d732005-09-28 22:28:18 +0000764 }
Chris Lattnerb9fccc42005-04-02 05:04:50 +0000765 void visitSub(User &I);
Reid Spencer1628cec2006-10-26 06:15:43 +0000766 void visitMul(User &I) {
Dan Gohman7f321562007-06-25 16:23:39 +0000767 if (I.getType()->isFPOrFPVector())
768 visitBinary(I, ISD::FMUL);
Reid Spencer1628cec2006-10-26 06:15:43 +0000769 else
Dan Gohman7f321562007-06-25 16:23:39 +0000770 visitBinary(I, ISD::MUL);
Chris Lattner01b3d732005-09-28 22:28:18 +0000771 }
Dan Gohman7f321562007-06-25 16:23:39 +0000772 void visitURem(User &I) { visitBinary(I, ISD::UREM); }
773 void visitSRem(User &I) { visitBinary(I, ISD::SREM); }
774 void visitFRem(User &I) { visitBinary(I, ISD::FREM); }
775 void visitUDiv(User &I) { visitBinary(I, ISD::UDIV); }
776 void visitSDiv(User &I) { visitBinary(I, ISD::SDIV); }
777 void visitFDiv(User &I) { visitBinary(I, ISD::FDIV); }
778 void visitAnd (User &I) { visitBinary(I, ISD::AND); }
779 void visitOr (User &I) { visitBinary(I, ISD::OR); }
780 void visitXor (User &I) { visitBinary(I, ISD::XOR); }
Reid Spencer24d6da52007-01-21 00:29:26 +0000781 void visitShl (User &I) { visitShift(I, ISD::SHL); }
Reid Spencer3822ff52006-11-08 06:47:33 +0000782 void visitLShr(User &I) { visitShift(I, ISD::SRL); }
783 void visitAShr(User &I) { visitShift(I, ISD::SRA); }
Reid Spencer45fb3f32006-11-20 01:22:35 +0000784 void visitICmp(User &I);
785 void visitFCmp(User &I);
Nate Begemanb43e9c12008-05-12 19:40:03 +0000786 void visitVICmp(User &I);
787 void visitVFCmp(User &I);
Reid Spencer3da59db2006-11-27 01:05:10 +0000788 // Visit the conversion instructions
789 void visitTrunc(User &I);
790 void visitZExt(User &I);
791 void visitSExt(User &I);
792 void visitFPTrunc(User &I);
793 void visitFPExt(User &I);
794 void visitFPToUI(User &I);
795 void visitFPToSI(User &I);
796 void visitUIToFP(User &I);
797 void visitSIToFP(User &I);
798 void visitPtrToInt(User &I);
799 void visitIntToPtr(User &I);
800 void visitBitCast(User &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000801
Chris Lattner2bbd8102006-03-29 00:11:43 +0000802 void visitExtractElement(User &I);
803 void visitInsertElement(User &I);
Chris Lattner3e104b12006-04-08 04:15:24 +0000804 void visitShuffleVector(User &I);
Chris Lattnerc7029802006-03-18 01:44:44 +0000805
Dan Gohman1d685a42008-06-07 02:02:36 +0000806 void visitExtractValue(ExtractValueInst &I);
807 void visitInsertValue(InsertValueInst &I);
Dan Gohman041e2eb2008-05-15 19:50:34 +0000808
Chris Lattner1c08c712005-01-07 07:47:53 +0000809 void visitGetElementPtr(User &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000810 void visitSelect(User &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000811
812 void visitMalloc(MallocInst &I);
813 void visitFree(FreeInst &I);
814 void visitAlloca(AllocaInst &I);
815 void visitLoad(LoadInst &I);
816 void visitStore(StoreInst &I);
817 void visitPHI(PHINode &I) { } // PHI nodes are handled specially.
818 void visitCall(CallInst &I);
Duncan Sandsfd7b3262007-12-17 18:08:19 +0000819 void visitInlineAsm(CallSite CS);
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +0000820 const char *visitIntrinsicCall(CallInst &I, unsigned Intrinsic);
Chris Lattner0eade312006-03-24 02:22:33 +0000821 void visitTargetIntrinsic(CallInst &I, unsigned Intrinsic);
Chris Lattner1c08c712005-01-07 07:47:53 +0000822
Chris Lattner1c08c712005-01-07 07:47:53 +0000823 void visitVAStart(CallInst &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000824 void visitVAArg(VAArgInst &I);
825 void visitVAEnd(CallInst &I);
826 void visitVACopy(CallInst &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000827
Chris Lattner1c08c712005-01-07 07:47:53 +0000828 void visitUserOp1(Instruction &I) {
829 assert(0 && "UserOp1 should not exist at instruction selection time!");
830 abort();
831 }
832 void visitUserOp2(Instruction &I) {
833 assert(0 && "UserOp2 should not exist at instruction selection time!");
834 abort();
835 }
Mon P Wang63307c32008-05-05 19:05:59 +0000836
837private:
838 inline const char *implVisitBinaryAtomic(CallInst& I, ISD::NodeType Op);
839
Chris Lattner1c08c712005-01-07 07:47:53 +0000840};
841} // end namespace llvm
842
Dan Gohman6183f782007-07-05 20:12:34 +0000843
Duncan Sandsb988bac2008-02-11 20:58:28 +0000844/// getCopyFromParts - Create a value that contains the specified legal parts
845/// combined into the value they represent. If the parts combine to a type
846/// larger then ValueVT then AssertOp can be used to specify whether the extra
847/// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
Chris Lattner4468c1f2008-03-09 09:38:46 +0000848/// (ISD::AssertSext).
Dan Gohman475871a2008-07-27 21:46:04 +0000849static SDValue getCopyFromParts(SelectionDAG &DAG,
850 const SDValue *Parts,
Dan Gohman6183f782007-07-05 20:12:34 +0000851 unsigned NumParts,
Duncan Sands83ec4b62008-06-06 12:08:01 +0000852 MVT PartVT,
853 MVT ValueVT,
Chris Lattner4468c1f2008-03-09 09:38:46 +0000854 ISD::NodeType AssertOp = ISD::DELETED_NODE) {
Duncan Sands014e04a2008-02-12 20:46:31 +0000855 assert(NumParts > 0 && "No parts to assemble!");
856 TargetLowering &TLI = DAG.getTargetLoweringInfo();
Dan Gohman475871a2008-07-27 21:46:04 +0000857 SDValue Val = Parts[0];
Dan Gohman6183f782007-07-05 20:12:34 +0000858
Duncan Sands014e04a2008-02-12 20:46:31 +0000859 if (NumParts > 1) {
860 // Assemble the value from multiple parts.
Duncan Sands83ec4b62008-06-06 12:08:01 +0000861 if (!ValueVT.isVector()) {
862 unsigned PartBits = PartVT.getSizeInBits();
863 unsigned ValueBits = ValueVT.getSizeInBits();
Dan Gohman6183f782007-07-05 20:12:34 +0000864
Duncan Sands014e04a2008-02-12 20:46:31 +0000865 // Assemble the power of 2 part.
866 unsigned RoundParts = NumParts & (NumParts - 1) ?
867 1 << Log2_32(NumParts) : NumParts;
868 unsigned RoundBits = PartBits * RoundParts;
Duncan Sands83ec4b62008-06-06 12:08:01 +0000869 MVT RoundVT = RoundBits == ValueBits ?
870 ValueVT : MVT::getIntegerVT(RoundBits);
Dan Gohman475871a2008-07-27 21:46:04 +0000871 SDValue Lo, Hi;
Duncan Sands014e04a2008-02-12 20:46:31 +0000872
873 if (RoundParts > 2) {
Duncan Sands83ec4b62008-06-06 12:08:01 +0000874 MVT HalfVT = MVT::getIntegerVT(RoundBits/2);
Duncan Sands014e04a2008-02-12 20:46:31 +0000875 Lo = getCopyFromParts(DAG, Parts, RoundParts/2, PartVT, HalfVT);
876 Hi = getCopyFromParts(DAG, Parts+RoundParts/2, RoundParts/2,
877 PartVT, HalfVT);
Dan Gohman6183f782007-07-05 20:12:34 +0000878 } else {
Duncan Sands014e04a2008-02-12 20:46:31 +0000879 Lo = Parts[0];
880 Hi = Parts[1];
Dan Gohman6183f782007-07-05 20:12:34 +0000881 }
Duncan Sands014e04a2008-02-12 20:46:31 +0000882 if (TLI.isBigEndian())
883 std::swap(Lo, Hi);
884 Val = DAG.getNode(ISD::BUILD_PAIR, RoundVT, Lo, Hi);
885
886 if (RoundParts < NumParts) {
887 // Assemble the trailing non-power-of-2 part.
888 unsigned OddParts = NumParts - RoundParts;
Duncan Sands83ec4b62008-06-06 12:08:01 +0000889 MVT OddVT = MVT::getIntegerVT(OddParts * PartBits);
Duncan Sands014e04a2008-02-12 20:46:31 +0000890 Hi = getCopyFromParts(DAG, Parts+RoundParts, OddParts, PartVT, OddVT);
891
892 // Combine the round and odd parts.
893 Lo = Val;
894 if (TLI.isBigEndian())
895 std::swap(Lo, Hi);
Duncan Sands83ec4b62008-06-06 12:08:01 +0000896 MVT TotalVT = MVT::getIntegerVT(NumParts * PartBits);
Duncan Sands014e04a2008-02-12 20:46:31 +0000897 Hi = DAG.getNode(ISD::ANY_EXTEND, TotalVT, Hi);
898 Hi = DAG.getNode(ISD::SHL, TotalVT, Hi,
Duncan Sands83ec4b62008-06-06 12:08:01 +0000899 DAG.getConstant(Lo.getValueType().getSizeInBits(),
Duncan Sands014e04a2008-02-12 20:46:31 +0000900 TLI.getShiftAmountTy()));
901 Lo = DAG.getNode(ISD::ZERO_EXTEND, TotalVT, Lo);
902 Val = DAG.getNode(ISD::OR, TotalVT, Lo, Hi);
903 }
904 } else {
905 // Handle a multi-element vector.
Duncan Sands83ec4b62008-06-06 12:08:01 +0000906 MVT IntermediateVT, RegisterVT;
Duncan Sands014e04a2008-02-12 20:46:31 +0000907 unsigned NumIntermediates;
908 unsigned NumRegs =
909 TLI.getVectorTypeBreakdown(ValueVT, IntermediateVT, NumIntermediates,
910 RegisterVT);
Duncan Sands014e04a2008-02-12 20:46:31 +0000911 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
Evan Cheng35213342008-05-14 20:29:30 +0000912 NumParts = NumRegs; // Silence a compiler warning.
Duncan Sands014e04a2008-02-12 20:46:31 +0000913 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
914 assert(RegisterVT == Parts[0].getValueType() &&
915 "Part type doesn't match part!");
916
917 // Assemble the parts into intermediate operands.
Dan Gohman475871a2008-07-27 21:46:04 +0000918 SmallVector<SDValue, 8> Ops(NumIntermediates);
Duncan Sands014e04a2008-02-12 20:46:31 +0000919 if (NumIntermediates == NumParts) {
920 // If the register was not expanded, truncate or copy the value,
921 // as appropriate.
922 for (unsigned i = 0; i != NumParts; ++i)
923 Ops[i] = getCopyFromParts(DAG, &Parts[i], 1,
924 PartVT, IntermediateVT);
925 } else if (NumParts > 0) {
926 // If the intermediate type was expanded, build the intermediate operands
927 // from the parts.
928 assert(NumParts % NumIntermediates == 0 &&
929 "Must expand into a divisible number of parts!");
930 unsigned Factor = NumParts / NumIntermediates;
931 for (unsigned i = 0; i != NumIntermediates; ++i)
932 Ops[i] = getCopyFromParts(DAG, &Parts[i * Factor], Factor,
933 PartVT, IntermediateVT);
934 }
935
936 // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the intermediate
937 // operands.
Duncan Sands83ec4b62008-06-06 12:08:01 +0000938 Val = DAG.getNode(IntermediateVT.isVector() ?
Duncan Sands014e04a2008-02-12 20:46:31 +0000939 ISD::CONCAT_VECTORS : ISD::BUILD_VECTOR,
940 ValueVT, &Ops[0], NumIntermediates);
Dan Gohman6183f782007-07-05 20:12:34 +0000941 }
Dan Gohman6183f782007-07-05 20:12:34 +0000942 }
943
Duncan Sands014e04a2008-02-12 20:46:31 +0000944 // There is now one part, held in Val. Correct it to match ValueVT.
945 PartVT = Val.getValueType();
Dan Gohman6183f782007-07-05 20:12:34 +0000946
Duncan Sands014e04a2008-02-12 20:46:31 +0000947 if (PartVT == ValueVT)
948 return Val;
Dan Gohman6183f782007-07-05 20:12:34 +0000949
Duncan Sands83ec4b62008-06-06 12:08:01 +0000950 if (PartVT.isVector()) {
951 assert(ValueVT.isVector() && "Unknown vector conversion!");
Duncan Sands014e04a2008-02-12 20:46:31 +0000952 return DAG.getNode(ISD::BIT_CONVERT, ValueVT, Val);
Dan Gohman6183f782007-07-05 20:12:34 +0000953 }
Duncan Sands014e04a2008-02-12 20:46:31 +0000954
Duncan Sands83ec4b62008-06-06 12:08:01 +0000955 if (ValueVT.isVector()) {
956 assert(ValueVT.getVectorElementType() == PartVT &&
957 ValueVT.getVectorNumElements() == 1 &&
Duncan Sands014e04a2008-02-12 20:46:31 +0000958 "Only trivial scalar-to-vector conversions should get here!");
959 return DAG.getNode(ISD::BUILD_VECTOR, ValueVT, Val);
960 }
961
Duncan Sands83ec4b62008-06-06 12:08:01 +0000962 if (PartVT.isInteger() &&
963 ValueVT.isInteger()) {
Duncan Sands8e4eb092008-06-08 20:54:56 +0000964 if (ValueVT.bitsLT(PartVT)) {
Duncan Sands014e04a2008-02-12 20:46:31 +0000965 // For a truncate, see if we have any information to
966 // indicate whether the truncated bits will always be
967 // zero or sign-extension.
968 if (AssertOp != ISD::DELETED_NODE)
969 Val = DAG.getNode(AssertOp, PartVT, Val,
970 DAG.getValueType(ValueVT));
971 return DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
972 } else {
973 return DAG.getNode(ISD::ANY_EXTEND, ValueVT, Val);
974 }
975 }
976
Duncan Sands83ec4b62008-06-06 12:08:01 +0000977 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
Duncan Sands8e4eb092008-06-08 20:54:56 +0000978 if (ValueVT.bitsLT(Val.getValueType()))
Chris Lattner4468c1f2008-03-09 09:38:46 +0000979 // FP_ROUND's are always exact here.
Chris Lattnerd43d85c2008-03-09 07:47:22 +0000980 return DAG.getNode(ISD::FP_ROUND, ValueVT, Val,
Chris Lattner4468c1f2008-03-09 09:38:46 +0000981 DAG.getIntPtrConstant(1));
Chris Lattnerd43d85c2008-03-09 07:47:22 +0000982 return DAG.getNode(ISD::FP_EXTEND, ValueVT, Val);
983 }
Duncan Sands014e04a2008-02-12 20:46:31 +0000984
Duncan Sands83ec4b62008-06-06 12:08:01 +0000985 if (PartVT.getSizeInBits() == ValueVT.getSizeInBits())
Duncan Sands014e04a2008-02-12 20:46:31 +0000986 return DAG.getNode(ISD::BIT_CONVERT, ValueVT, Val);
987
988 assert(0 && "Unknown mismatch!");
Dan Gohman475871a2008-07-27 21:46:04 +0000989 return SDValue();
Dan Gohman6183f782007-07-05 20:12:34 +0000990}
991
Duncan Sandsb988bac2008-02-11 20:58:28 +0000992/// getCopyToParts - Create a series of nodes that contain the specified value
993/// split into legal parts. If the parts contain more bits than Val, then, for
994/// integers, ExtendKind can be used to specify how to generate the extra bits.
Dan Gohman6183f782007-07-05 20:12:34 +0000995static void getCopyToParts(SelectionDAG &DAG,
Dan Gohman475871a2008-07-27 21:46:04 +0000996 SDValue Val,
997 SDValue *Parts,
Dan Gohman6183f782007-07-05 20:12:34 +0000998 unsigned NumParts,
Duncan Sands83ec4b62008-06-06 12:08:01 +0000999 MVT PartVT,
Duncan Sandsb988bac2008-02-11 20:58:28 +00001000 ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
Dan Gohman25ac7e82007-08-10 14:59:38 +00001001 TargetLowering &TLI = DAG.getTargetLoweringInfo();
Duncan Sands83ec4b62008-06-06 12:08:01 +00001002 MVT PtrVT = TLI.getPointerTy();
1003 MVT ValueVT = Val.getValueType();
1004 unsigned PartBits = PartVT.getSizeInBits();
Duncan Sands014e04a2008-02-12 20:46:31 +00001005 assert(TLI.isTypeLegal(PartVT) && "Copying to an illegal type!");
Dan Gohman6183f782007-07-05 20:12:34 +00001006
Duncan Sands014e04a2008-02-12 20:46:31 +00001007 if (!NumParts)
1008 return;
1009
Duncan Sands83ec4b62008-06-06 12:08:01 +00001010 if (!ValueVT.isVector()) {
Duncan Sands014e04a2008-02-12 20:46:31 +00001011 if (PartVT == ValueVT) {
1012 assert(NumParts == 1 && "No-op copy with multiple parts!");
1013 Parts[0] = Val;
Dan Gohman6183f782007-07-05 20:12:34 +00001014 return;
1015 }
1016
Duncan Sands83ec4b62008-06-06 12:08:01 +00001017 if (NumParts * PartBits > ValueVT.getSizeInBits()) {
Duncan Sands014e04a2008-02-12 20:46:31 +00001018 // If the parts cover more bits than the value has, promote the value.
Duncan Sands83ec4b62008-06-06 12:08:01 +00001019 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
Duncan Sands014e04a2008-02-12 20:46:31 +00001020 assert(NumParts == 1 && "Do not know what to promote to!");
Dan Gohman6183f782007-07-05 20:12:34 +00001021 Val = DAG.getNode(ISD::FP_EXTEND, PartVT, Val);
Duncan Sands83ec4b62008-06-06 12:08:01 +00001022 } else if (PartVT.isInteger() && ValueVT.isInteger()) {
1023 ValueVT = MVT::getIntegerVT(NumParts * PartBits);
Duncan Sands014e04a2008-02-12 20:46:31 +00001024 Val = DAG.getNode(ExtendKind, ValueVT, Val);
1025 } else {
1026 assert(0 && "Unknown mismatch!");
1027 }
Duncan Sands83ec4b62008-06-06 12:08:01 +00001028 } else if (PartBits == ValueVT.getSizeInBits()) {
Duncan Sands014e04a2008-02-12 20:46:31 +00001029 // Different types of the same size.
1030 assert(NumParts == 1 && PartVT != ValueVT);
1031 Val = DAG.getNode(ISD::BIT_CONVERT, PartVT, Val);
Duncan Sands83ec4b62008-06-06 12:08:01 +00001032 } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
Duncan Sands014e04a2008-02-12 20:46:31 +00001033 // If the parts cover less bits than value has, truncate the value.
Duncan Sands83ec4b62008-06-06 12:08:01 +00001034 if (PartVT.isInteger() && ValueVT.isInteger()) {
1035 ValueVT = MVT::getIntegerVT(NumParts * PartBits);
Duncan Sands014e04a2008-02-12 20:46:31 +00001036 Val = DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
Dan Gohman6183f782007-07-05 20:12:34 +00001037 } else {
1038 assert(0 && "Unknown mismatch!");
1039 }
1040 }
Duncan Sands014e04a2008-02-12 20:46:31 +00001041
1042 // The value may have changed - recompute ValueVT.
1043 ValueVT = Val.getValueType();
Duncan Sands83ec4b62008-06-06 12:08:01 +00001044 assert(NumParts * PartBits == ValueVT.getSizeInBits() &&
Duncan Sands014e04a2008-02-12 20:46:31 +00001045 "Failed to tile the value with PartVT!");
1046
1047 if (NumParts == 1) {
1048 assert(PartVT == ValueVT && "Type conversion failed!");
1049 Parts[0] = Val;
1050 return;
1051 }
1052
1053 // Expand the value into multiple parts.
1054 if (NumParts & (NumParts - 1)) {
1055 // The number of parts is not a power of 2. Split off and copy the tail.
Duncan Sands83ec4b62008-06-06 12:08:01 +00001056 assert(PartVT.isInteger() && ValueVT.isInteger() &&
Duncan Sands014e04a2008-02-12 20:46:31 +00001057 "Do not know what to expand to!");
1058 unsigned RoundParts = 1 << Log2_32(NumParts);
1059 unsigned RoundBits = RoundParts * PartBits;
1060 unsigned OddParts = NumParts - RoundParts;
Dan Gohman475871a2008-07-27 21:46:04 +00001061 SDValue OddVal = DAG.getNode(ISD::SRL, ValueVT, Val,
Duncan Sands014e04a2008-02-12 20:46:31 +00001062 DAG.getConstant(RoundBits,
1063 TLI.getShiftAmountTy()));
1064 getCopyToParts(DAG, OddVal, Parts + RoundParts, OddParts, PartVT);
1065 if (TLI.isBigEndian())
1066 // The odd parts were reversed by getCopyToParts - unreverse them.
1067 std::reverse(Parts + RoundParts, Parts + NumParts);
1068 NumParts = RoundParts;
Duncan Sands83ec4b62008-06-06 12:08:01 +00001069 ValueVT = MVT::getIntegerVT(NumParts * PartBits);
Duncan Sands014e04a2008-02-12 20:46:31 +00001070 Val = DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
1071 }
1072
1073 // The number of parts is a power of 2. Repeatedly bisect the value using
1074 // EXTRACT_ELEMENT.
Duncan Sands25eb0432008-03-12 20:30:08 +00001075 Parts[0] = DAG.getNode(ISD::BIT_CONVERT,
Duncan Sands83ec4b62008-06-06 12:08:01 +00001076 MVT::getIntegerVT(ValueVT.getSizeInBits()),
Duncan Sands25eb0432008-03-12 20:30:08 +00001077 Val);
Duncan Sands014e04a2008-02-12 20:46:31 +00001078 for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
1079 for (unsigned i = 0; i < NumParts; i += StepSize) {
1080 unsigned ThisBits = StepSize * PartBits / 2;
Duncan Sands83ec4b62008-06-06 12:08:01 +00001081 MVT ThisVT = MVT::getIntegerVT (ThisBits);
Dan Gohman475871a2008-07-27 21:46:04 +00001082 SDValue &Part0 = Parts[i];
1083 SDValue &Part1 = Parts[i+StepSize/2];
Duncan Sands014e04a2008-02-12 20:46:31 +00001084
Duncan Sands25eb0432008-03-12 20:30:08 +00001085 Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, ThisVT, Part0,
1086 DAG.getConstant(1, PtrVT));
1087 Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, ThisVT, Part0,
1088 DAG.getConstant(0, PtrVT));
1089
1090 if (ThisBits == PartBits && ThisVT != PartVT) {
1091 Part0 = DAG.getNode(ISD::BIT_CONVERT, PartVT, Part0);
1092 Part1 = DAG.getNode(ISD::BIT_CONVERT, PartVT, Part1);
1093 }
Duncan Sands014e04a2008-02-12 20:46:31 +00001094 }
1095 }
1096
1097 if (TLI.isBigEndian())
1098 std::reverse(Parts, Parts + NumParts);
1099
1100 return;
1101 }
1102
1103 // Vector ValueVT.
1104 if (NumParts == 1) {
1105 if (PartVT != ValueVT) {
Duncan Sands83ec4b62008-06-06 12:08:01 +00001106 if (PartVT.isVector()) {
Duncan Sands014e04a2008-02-12 20:46:31 +00001107 Val = DAG.getNode(ISD::BIT_CONVERT, PartVT, Val);
1108 } else {
Duncan Sands83ec4b62008-06-06 12:08:01 +00001109 assert(ValueVT.getVectorElementType() == PartVT &&
1110 ValueVT.getVectorNumElements() == 1 &&
Duncan Sands014e04a2008-02-12 20:46:31 +00001111 "Only trivial vector-to-scalar conversions should get here!");
1112 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, PartVT, Val,
1113 DAG.getConstant(0, PtrVT));
1114 }
1115 }
1116
Dan Gohman6183f782007-07-05 20:12:34 +00001117 Parts[0] = Val;
1118 return;
1119 }
1120
1121 // Handle a multi-element vector.
Duncan Sands83ec4b62008-06-06 12:08:01 +00001122 MVT IntermediateVT, RegisterVT;
Dan Gohman6183f782007-07-05 20:12:34 +00001123 unsigned NumIntermediates;
1124 unsigned NumRegs =
1125 DAG.getTargetLoweringInfo()
1126 .getVectorTypeBreakdown(ValueVT, IntermediateVT, NumIntermediates,
1127 RegisterVT);
Duncan Sands83ec4b62008-06-06 12:08:01 +00001128 unsigned NumElements = ValueVT.getVectorNumElements();
Dan Gohman6183f782007-07-05 20:12:34 +00001129
1130 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
Evan Cheng35213342008-05-14 20:29:30 +00001131 NumParts = NumRegs; // Silence a compiler warning.
Dan Gohman6183f782007-07-05 20:12:34 +00001132 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
1133
1134 // Split the vector into intermediate operands.
Dan Gohman475871a2008-07-27 21:46:04 +00001135 SmallVector<SDValue, 8> Ops(NumIntermediates);
Dan Gohman6183f782007-07-05 20:12:34 +00001136 for (unsigned i = 0; i != NumIntermediates; ++i)
Duncan Sands83ec4b62008-06-06 12:08:01 +00001137 if (IntermediateVT.isVector())
Dan Gohman6183f782007-07-05 20:12:34 +00001138 Ops[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR,
1139 IntermediateVT, Val,
1140 DAG.getConstant(i * (NumElements / NumIntermediates),
Dan Gohman25ac7e82007-08-10 14:59:38 +00001141 PtrVT));
Dan Gohman6183f782007-07-05 20:12:34 +00001142 else
1143 Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
1144 IntermediateVT, Val,
Dan Gohman25ac7e82007-08-10 14:59:38 +00001145 DAG.getConstant(i, PtrVT));
Dan Gohman6183f782007-07-05 20:12:34 +00001146
1147 // Split the intermediate operands into legal parts.
1148 if (NumParts == NumIntermediates) {
1149 // If the register was not expanded, promote or copy the value,
1150 // as appropriate.
1151 for (unsigned i = 0; i != NumParts; ++i)
Dan Gohman532dc2e2007-07-09 20:59:04 +00001152 getCopyToParts(DAG, Ops[i], &Parts[i], 1, PartVT);
Dan Gohman6183f782007-07-05 20:12:34 +00001153 } else if (NumParts > 0) {
1154 // If the intermediate type was expanded, split each the value into
1155 // legal parts.
1156 assert(NumParts % NumIntermediates == 0 &&
1157 "Must expand into a divisible number of parts!");
1158 unsigned Factor = NumParts / NumIntermediates;
1159 for (unsigned i = 0; i != NumIntermediates; ++i)
Dan Gohman532dc2e2007-07-09 20:59:04 +00001160 getCopyToParts(DAG, Ops[i], &Parts[i * Factor], Factor, PartVT);
Dan Gohman6183f782007-07-05 20:12:34 +00001161 }
1162}
1163
1164
Dan Gohman475871a2008-07-27 21:46:04 +00001165SDValue SelectionDAGLowering::getValue(const Value *V) {
1166 SDValue &N = NodeMap[V];
Chris Lattner199862b2006-03-16 19:57:50 +00001167 if (N.Val) return N;
1168
Chris Lattner199862b2006-03-16 19:57:50 +00001169 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V))) {
Duncan Sands83ec4b62008-06-06 12:08:01 +00001170 MVT VT = TLI.getValueType(V->getType(), true);
Chris Lattnerb606dba2008-04-28 06:44:42 +00001171
1172 if (ConstantInt *CI = dyn_cast<ConstantInt>(C))
1173 return N = DAG.getConstant(CI->getValue(), VT);
1174
1175 if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
Chris Lattner199862b2006-03-16 19:57:50 +00001176 return N = DAG.getGlobalAddress(GV, VT);
Chris Lattnerb606dba2008-04-28 06:44:42 +00001177
1178 if (isa<ConstantPointerNull>(C))
Chris Lattner199862b2006-03-16 19:57:50 +00001179 return N = DAG.getConstant(0, TLI.getPointerTy());
Chris Lattnerb606dba2008-04-28 06:44:42 +00001180
1181 if (ConstantFP *CFP = dyn_cast<ConstantFP>(C))
1182 return N = DAG.getConstantFP(CFP->getValueAPF(), VT);
1183
Dan Gohman1d685a42008-06-07 02:02:36 +00001184 if (isa<UndefValue>(C) && !isa<VectorType>(V->getType()) &&
1185 !V->getType()->isAggregateType())
Chris Lattner6833b062008-04-28 07:16:35 +00001186 return N = DAG.getNode(ISD::UNDEF, VT);
Chris Lattnerb606dba2008-04-28 06:44:42 +00001187
1188 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
1189 visit(CE->getOpcode(), *CE);
Dan Gohman475871a2008-07-27 21:46:04 +00001190 SDValue N1 = NodeMap[V];
Chris Lattnerb606dba2008-04-28 06:44:42 +00001191 assert(N1.Val && "visit didn't populate the ValueMap!");
1192 return N1;
1193 }
1194
Dan Gohman1d685a42008-06-07 02:02:36 +00001195 if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
Dan Gohman475871a2008-07-27 21:46:04 +00001196 SmallVector<SDValue, 4> Constants;
Dan Gohman1d685a42008-06-07 02:02:36 +00001197 for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end();
1198 OI != OE; ++OI) {
1199 SDNode *Val = getValue(*OI).Val;
Duncan Sands4bdcb612008-07-02 17:40:58 +00001200 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
Dan Gohman475871a2008-07-27 21:46:04 +00001201 Constants.push_back(SDValue(Val, i));
Dan Gohman1d685a42008-06-07 02:02:36 +00001202 }
Duncan Sands4bdcb612008-07-02 17:40:58 +00001203 return DAG.getMergeValues(&Constants[0], Constants.size());
Dan Gohman1d685a42008-06-07 02:02:36 +00001204 }
1205
Dan Gohman1f565bc2008-08-04 23:30:41 +00001206 if (isa<StructType>(C->getType()) || isa<ArrayType>(C->getType())) {
Dan Gohman1d685a42008-06-07 02:02:36 +00001207 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
Dan Gohman1f565bc2008-08-04 23:30:41 +00001208 "Unknown struct or array constant!");
Dan Gohman1d685a42008-06-07 02:02:36 +00001209
Dan Gohman1f565bc2008-08-04 23:30:41 +00001210 SmallVector<MVT, 4> ValueVTs;
1211 ComputeValueVTs(TLI, C->getType(), ValueVTs);
1212 unsigned NumElts = ValueVTs.size();
Dan Gohman8a6ccb52008-06-09 15:21:47 +00001213 if (NumElts == 0)
Dan Gohman475871a2008-07-27 21:46:04 +00001214 return SDValue(); // empty struct
1215 SmallVector<SDValue, 4> Constants(NumElts);
Dan Gohman1f565bc2008-08-04 23:30:41 +00001216 for (unsigned i = 0; i != NumElts; ++i) {
1217 MVT EltVT = ValueVTs[i];
Dan Gohman1d685a42008-06-07 02:02:36 +00001218 if (isa<UndefValue>(C))
1219 Constants[i] = DAG.getNode(ISD::UNDEF, EltVT);
1220 else if (EltVT.isFloatingPoint())
1221 Constants[i] = DAG.getConstantFP(0, EltVT);
1222 else
1223 Constants[i] = DAG.getConstant(0, EltVT);
1224 }
Dan Gohman1f565bc2008-08-04 23:30:41 +00001225 return DAG.getMergeValues(&Constants[0], NumElts);
Dan Gohman1d685a42008-06-07 02:02:36 +00001226 }
1227
Chris Lattner6833b062008-04-28 07:16:35 +00001228 const VectorType *VecTy = cast<VectorType>(V->getType());
Chris Lattnerb606dba2008-04-28 06:44:42 +00001229 unsigned NumElements = VecTy->getNumElements();
Chris Lattnerb606dba2008-04-28 06:44:42 +00001230
Chris Lattner6833b062008-04-28 07:16:35 +00001231 // Now that we know the number and type of the elements, get that number of
1232 // elements into the Ops array based on what kind of constant it is.
Dan Gohman475871a2008-07-27 21:46:04 +00001233 SmallVector<SDValue, 16> Ops;
Chris Lattnerb606dba2008-04-28 06:44:42 +00001234 if (ConstantVector *CP = dyn_cast<ConstantVector>(C)) {
1235 for (unsigned i = 0; i != NumElements; ++i)
1236 Ops.push_back(getValue(CP->getOperand(i)));
1237 } else {
Chris Lattner6833b062008-04-28 07:16:35 +00001238 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
1239 "Unknown vector constant!");
Duncan Sands83ec4b62008-06-06 12:08:01 +00001240 MVT EltVT = TLI.getValueType(VecTy->getElementType());
Chris Lattner6833b062008-04-28 07:16:35 +00001241
Dan Gohman475871a2008-07-27 21:46:04 +00001242 SDValue Op;
Chris Lattner6833b062008-04-28 07:16:35 +00001243 if (isa<UndefValue>(C))
1244 Op = DAG.getNode(ISD::UNDEF, EltVT);
Duncan Sands83ec4b62008-06-06 12:08:01 +00001245 else if (EltVT.isFloatingPoint())
Chris Lattner6833b062008-04-28 07:16:35 +00001246 Op = DAG.getConstantFP(0, EltVT);
Chris Lattnerb606dba2008-04-28 06:44:42 +00001247 else
Chris Lattner6833b062008-04-28 07:16:35 +00001248 Op = DAG.getConstant(0, EltVT);
Chris Lattnerb606dba2008-04-28 06:44:42 +00001249 Ops.assign(NumElements, Op);
1250 }
1251
1252 // Create a BUILD_VECTOR node.
1253 return NodeMap[V] = DAG.getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
Chris Lattner199862b2006-03-16 19:57:50 +00001254 }
1255
Chris Lattnerb606dba2008-04-28 06:44:42 +00001256 // If this is a static alloca, generate it as the frameindex instead of
1257 // computation.
Chris Lattner199862b2006-03-16 19:57:50 +00001258 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
Dan Gohman6ecf5092008-08-23 02:44:46 +00001259 DenseMap<const AllocaInst*, int>::iterator SI =
Chris Lattnerb606dba2008-04-28 06:44:42 +00001260 FuncInfo.StaticAllocaMap.find(AI);
Chris Lattner199862b2006-03-16 19:57:50 +00001261 if (SI != FuncInfo.StaticAllocaMap.end())
1262 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
1263 }
1264
Chris Lattner251db182007-02-25 18:40:32 +00001265 unsigned InReg = FuncInfo.ValueMap[V];
1266 assert(InReg && "Value not in map!");
Chris Lattner199862b2006-03-16 19:57:50 +00001267
Chris Lattner6833b062008-04-28 07:16:35 +00001268 RegsForValue RFV(TLI, InReg, V->getType());
Dan Gohman475871a2008-07-27 21:46:04 +00001269 SDValue Chain = DAG.getEntryNode();
Dan Gohmanb6f5b002007-06-28 23:29:44 +00001270 return RFV.getCopyFromRegs(DAG, Chain, NULL);
Chris Lattner199862b2006-03-16 19:57:50 +00001271}
1272
1273
Chris Lattner1c08c712005-01-07 07:47:53 +00001274void SelectionDAGLowering::visitRet(ReturnInst &I) {
1275 if (I.getNumOperands() == 0) {
Dan Gohman86e1ebf2008-03-27 19:56:19 +00001276 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getControlRoot()));
Chris Lattner1c08c712005-01-07 07:47:53 +00001277 return;
1278 }
Chris Lattnerb606dba2008-04-28 06:44:42 +00001279
Dan Gohman475871a2008-07-27 21:46:04 +00001280 SmallVector<SDValue, 8> NewValues;
Dan Gohman86e1ebf2008-03-27 19:56:19 +00001281 NewValues.push_back(getControlRoot());
1282 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
Dan Gohman475871a2008-07-27 21:46:04 +00001283 SDValue RetOp = getValue(I.getOperand(i));
Duncan Sandsb988bac2008-02-11 20:58:28 +00001284
Dan Gohmanab8ec0a2008-06-20 01:29:26 +00001285 SmallVector<MVT, 4> ValueVTs;
1286 ComputeValueVTs(TLI, I.getOperand(i)->getType(), ValueVTs);
1287 for (unsigned j = 0, f = ValueVTs.size(); j != f; ++j) {
1288 MVT VT = ValueVTs[j];
Duncan Sandsb988bac2008-02-11 20:58:28 +00001289
Dan Gohmanab8ec0a2008-06-20 01:29:26 +00001290 // FIXME: C calling convention requires the return type to be promoted to
1291 // at least 32-bit. But this is not necessary for non-C calling conventions.
1292 if (VT.isInteger()) {
1293 MVT MinVT = TLI.getRegisterType(MVT::i32);
1294 if (VT.bitsLT(MinVT))
1295 VT = MinVT;
1296 }
Duncan Sandsb988bac2008-02-11 20:58:28 +00001297
Dan Gohmanab8ec0a2008-06-20 01:29:26 +00001298 unsigned NumParts = TLI.getNumRegisters(VT);
1299 MVT PartVT = TLI.getRegisterType(VT);
Dan Gohman475871a2008-07-27 21:46:04 +00001300 SmallVector<SDValue, 4> Parts(NumParts);
Dan Gohmanab8ec0a2008-06-20 01:29:26 +00001301 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
1302
1303 const Function *F = I.getParent()->getParent();
1304 if (F->paramHasAttr(0, ParamAttr::SExt))
1305 ExtendKind = ISD::SIGN_EXTEND;
1306 else if (F->paramHasAttr(0, ParamAttr::ZExt))
1307 ExtendKind = ISD::ZERO_EXTEND;
Duncan Sandsb988bac2008-02-11 20:58:28 +00001308
Dan Gohman475871a2008-07-27 21:46:04 +00001309 getCopyToParts(DAG, SDValue(RetOp.Val, RetOp.ResNo + j),
Dan Gohmanab8ec0a2008-06-20 01:29:26 +00001310 &Parts[0], NumParts, PartVT, ExtendKind);
Duncan Sandsb988bac2008-02-11 20:58:28 +00001311
Dan Gohmanab8ec0a2008-06-20 01:29:26 +00001312 for (unsigned i = 0; i < NumParts; ++i) {
1313 NewValues.push_back(Parts[i]);
1314 NewValues.push_back(DAG.getArgFlags(ISD::ArgFlagsTy()));
1315 }
Nate Begemanee625572006-01-27 21:09:22 +00001316 }
Chris Lattner1c08c712005-01-07 07:47:53 +00001317 }
Chris Lattnerbd564bf2006-08-08 02:23:42 +00001318 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other,
1319 &NewValues[0], NewValues.size()));
Chris Lattner1c08c712005-01-07 07:47:53 +00001320}
1321
Chris Lattner571e4342006-10-27 21:36:01 +00001322/// ExportFromCurrentBlock - If this condition isn't known to be exported from
1323/// the current basic block, add it to ValueMap now so that we'll get a
1324/// CopyTo/FromReg.
1325void SelectionDAGLowering::ExportFromCurrentBlock(Value *V) {
1326 // No need to export constants.
1327 if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
1328
1329 // Already exported?
1330 if (FuncInfo.isExportedInst(V)) return;
1331
1332 unsigned Reg = FuncInfo.InitializeRegForValue(V);
Dan Gohman86e1ebf2008-03-27 19:56:19 +00001333 CopyValueToVirtualRegister(V, Reg);
Chris Lattner571e4342006-10-27 21:36:01 +00001334}
1335
Chris Lattner8c494ab2006-10-27 23:50:33 +00001336bool SelectionDAGLowering::isExportableFromCurrentBlock(Value *V,
1337 const BasicBlock *FromBB) {
1338 // The operands of the setcc have to be in this block. We don't know
1339 // how to export them from some other block.
1340 if (Instruction *VI = dyn_cast<Instruction>(V)) {
1341 // Can export from current BB.
1342 if (VI->getParent() == FromBB)
1343 return true;
1344
1345 // Is already exported, noop.
1346 return FuncInfo.isExportedInst(V);
1347 }
1348
1349 // If this is an argument, we can export it if the BB is the entry block or
1350 // if it is already exported.
1351 if (isa<Argument>(V)) {
1352 if (FromBB == &FromBB->getParent()->getEntryBlock())
1353 return true;
1354
1355 // Otherwise, can only export this if it is already exported.
1356 return FuncInfo.isExportedInst(V);
1357 }
1358
1359 // Otherwise, constants can always be exported.
1360 return true;
1361}
1362
Chris Lattner6a586c82006-10-29 21:01:20 +00001363static bool InBlock(const Value *V, const BasicBlock *BB) {
1364 if (const Instruction *I = dyn_cast<Instruction>(V))
1365 return I->getParent() == BB;
1366 return true;
1367}
1368
Chris Lattner571e4342006-10-27 21:36:01 +00001369/// FindMergedConditions - If Cond is an expression like
1370void SelectionDAGLowering::FindMergedConditions(Value *Cond,
1371 MachineBasicBlock *TBB,
1372 MachineBasicBlock *FBB,
1373 MachineBasicBlock *CurBB,
1374 unsigned Opc) {
Chris Lattner571e4342006-10-27 21:36:01 +00001375 // If this node is not part of the or/and tree, emit it as a branch.
Reid Spencere4d87aa2006-12-23 06:05:41 +00001376 Instruction *BOp = dyn_cast<Instruction>(Cond);
Chris Lattner571e4342006-10-27 21:36:01 +00001377
Reid Spencere4d87aa2006-12-23 06:05:41 +00001378 if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
1379 (unsigned)BOp->getOpcode() != Opc || !BOp->hasOneUse() ||
Chris Lattner6a586c82006-10-29 21:01:20 +00001380 BOp->getParent() != CurBB->getBasicBlock() ||
1381 !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
1382 !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
Chris Lattner571e4342006-10-27 21:36:01 +00001383 const BasicBlock *BB = CurBB->getBasicBlock();
1384
Reid Spencere4d87aa2006-12-23 06:05:41 +00001385 // If the leaf of the tree is a comparison, merge the condition into
1386 // the caseblock.
1387 if ((isa<ICmpInst>(Cond) || isa<FCmpInst>(Cond)) &&
1388 // The operands of the cmp have to be in this block. We don't know
Chris Lattner5a145f02006-10-29 18:23:37 +00001389 // how to export them from some other block. If this is the first block
1390 // of the sequence, no exporting is needed.
1391 (CurBB == CurMBB ||
1392 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
1393 isExportableFromCurrentBlock(BOp->getOperand(1), BB)))) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00001394 BOp = cast<Instruction>(Cond);
1395 ISD::CondCode Condition;
1396 if (ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
1397 switch (IC->getPredicate()) {
1398 default: assert(0 && "Unknown icmp predicate opcode!");
1399 case ICmpInst::ICMP_EQ: Condition = ISD::SETEQ; break;
1400 case ICmpInst::ICMP_NE: Condition = ISD::SETNE; break;
1401 case ICmpInst::ICMP_SLE: Condition = ISD::SETLE; break;
1402 case ICmpInst::ICMP_ULE: Condition = ISD::SETULE; break;
1403 case ICmpInst::ICMP_SGE: Condition = ISD::SETGE; break;
1404 case ICmpInst::ICMP_UGE: Condition = ISD::SETUGE; break;
1405 case ICmpInst::ICMP_SLT: Condition = ISD::SETLT; break;
1406 case ICmpInst::ICMP_ULT: Condition = ISD::SETULT; break;
1407 case ICmpInst::ICMP_SGT: Condition = ISD::SETGT; break;
1408 case ICmpInst::ICMP_UGT: Condition = ISD::SETUGT; break;
1409 }
1410 } else if (FCmpInst *FC = dyn_cast<FCmpInst>(Cond)) {
1411 ISD::CondCode FPC, FOC;
1412 switch (FC->getPredicate()) {
1413 default: assert(0 && "Unknown fcmp predicate opcode!");
1414 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
1415 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
1416 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
1417 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
1418 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
1419 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
1420 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
Chris Lattner6bf30ab2008-05-01 07:26:11 +00001421 case FCmpInst::FCMP_ORD: FOC = FPC = ISD::SETO; break;
1422 case FCmpInst::FCMP_UNO: FOC = FPC = ISD::SETUO; break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00001423 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
1424 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
1425 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
1426 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
1427 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
1428 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
1429 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
1430 }
1431 if (FiniteOnlyFPMath())
1432 Condition = FOC;
1433 else
1434 Condition = FPC;
1435 } else {
Chris Lattner0da331f2007-02-04 01:31:47 +00001436 Condition = ISD::SETEQ; // silence warning.
Reid Spencere4d87aa2006-12-23 06:05:41 +00001437 assert(0 && "Unknown compare instruction");
Chris Lattner571e4342006-10-27 21:36:01 +00001438 }
1439
Chris Lattner571e4342006-10-27 21:36:01 +00001440 SelectionDAGISel::CaseBlock CB(Condition, BOp->getOperand(0),
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001441 BOp->getOperand(1), NULL, TBB, FBB, CurBB);
Chris Lattner571e4342006-10-27 21:36:01 +00001442 SwitchCases.push_back(CB);
1443 return;
1444 }
1445
1446 // Create a CaseBlock record representing this branch.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001447 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, Cond, ConstantInt::getTrue(),
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001448 NULL, TBB, FBB, CurBB);
Chris Lattner571e4342006-10-27 21:36:01 +00001449 SwitchCases.push_back(CB);
Chris Lattner571e4342006-10-27 21:36:01 +00001450 return;
1451 }
1452
Chris Lattnerd2f9ee92006-10-27 21:54:23 +00001453
1454 // Create TmpBB after CurBB.
Chris Lattner571e4342006-10-27 21:36:01 +00001455 MachineFunction::iterator BBI = CurBB;
Dan Gohman0e5f1302008-07-07 23:02:41 +00001456 MachineFunction &MF = DAG.getMachineFunction();
1457 MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
1458 CurBB->getParent()->insert(++BBI, TmpBB);
Chris Lattner571e4342006-10-27 21:36:01 +00001459
Chris Lattnerd2f9ee92006-10-27 21:54:23 +00001460 if (Opc == Instruction::Or) {
1461 // Codegen X | Y as:
1462 // jmp_if_X TBB
1463 // jmp TmpBB
1464 // TmpBB:
1465 // jmp_if_Y TBB
1466 // jmp FBB
1467 //
Chris Lattner571e4342006-10-27 21:36:01 +00001468
Chris Lattnerd2f9ee92006-10-27 21:54:23 +00001469 // Emit the LHS condition.
1470 FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, Opc);
1471
1472 // Emit the RHS condition into TmpBB.
1473 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
1474 } else {
1475 assert(Opc == Instruction::And && "Unknown merge op!");
1476 // Codegen X & Y as:
1477 // jmp_if_X TmpBB
1478 // jmp FBB
1479 // TmpBB:
1480 // jmp_if_Y TBB
1481 // jmp FBB
1482 //
1483 // This requires creation of TmpBB after CurBB.
1484
1485 // Emit the LHS condition.
1486 FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, Opc);
1487
1488 // Emit the RHS condition into TmpBB.
1489 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
1490 }
Chris Lattner571e4342006-10-27 21:36:01 +00001491}
1492
Chris Lattnerdf19f272006-10-31 22:37:42 +00001493/// If the set of cases should be emitted as a series of branches, return true.
1494/// If we should emit this as a bunch of and/or'd together conditions, return
1495/// false.
1496static bool
1497ShouldEmitAsBranches(const std::vector<SelectionDAGISel::CaseBlock> &Cases) {
1498 if (Cases.size() != 2) return true;
1499
Chris Lattner0ccb5002006-10-31 23:06:00 +00001500 // If this is two comparisons of the same values or'd or and'd together, they
1501 // will get folded into a single comparison, so don't emit two blocks.
1502 if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
1503 Cases[0].CmpRHS == Cases[1].CmpRHS) ||
1504 (Cases[0].CmpRHS == Cases[1].CmpLHS &&
1505 Cases[0].CmpLHS == Cases[1].CmpRHS)) {
1506 return false;
1507 }
1508
Chris Lattnerdf19f272006-10-31 22:37:42 +00001509 return true;
1510}
1511
Chris Lattner1c08c712005-01-07 07:47:53 +00001512void SelectionDAGLowering::visitBr(BranchInst &I) {
1513 // Update machine-CFG edges.
1514 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
Chris Lattner1c08c712005-01-07 07:47:53 +00001515
1516 // Figure out which block is immediately after the current one.
1517 MachineBasicBlock *NextBlock = 0;
1518 MachineFunction::iterator BBI = CurMBB;
1519 if (++BBI != CurMBB->getParent()->end())
1520 NextBlock = BBI;
1521
1522 if (I.isUnconditional()) {
Owen Anderson2d389e82008-06-07 00:00:23 +00001523 // Update machine-CFG edges.
1524 CurMBB->addSuccessor(Succ0MBB);
1525
Chris Lattner1c08c712005-01-07 07:47:53 +00001526 // If this is not a fall-through branch, emit the branch.
1527 if (Succ0MBB != NextBlock)
Dan Gohman86e1ebf2008-03-27 19:56:19 +00001528 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getControlRoot(),
Misha Brukmandedf2bd2005-04-22 04:01:18 +00001529 DAG.getBasicBlock(Succ0MBB)));
Chris Lattner57ab6592006-10-24 17:57:59 +00001530 return;
1531 }
1532
1533 // If this condition is one of the special cases we handle, do special stuff
1534 // now.
1535 Value *CondVal = I.getCondition();
Chris Lattner57ab6592006-10-24 17:57:59 +00001536 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
Chris Lattner571e4342006-10-27 21:36:01 +00001537
1538 // If this is a series of conditions that are or'd or and'd together, emit
1539 // this as a sequence of branches instead of setcc's with and/or operations.
1540 // For example, instead of something like:
1541 // cmp A, B
1542 // C = seteq
1543 // cmp D, E
1544 // F = setle
1545 // or C, F
1546 // jnz foo
1547 // Emit:
1548 // cmp A, B
1549 // je foo
1550 // cmp D, E
1551 // jle foo
1552 //
1553 if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
1554 if (BOp->hasOneUse() &&
Chris Lattnerd2f9ee92006-10-27 21:54:23 +00001555 (BOp->getOpcode() == Instruction::And ||
Chris Lattner571e4342006-10-27 21:36:01 +00001556 BOp->getOpcode() == Instruction::Or)) {
1557 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, CurMBB, BOp->getOpcode());
Chris Lattner0ccb5002006-10-31 23:06:00 +00001558 // If the compares in later blocks need to use values not currently
1559 // exported from this block, export them now. This block should always
1560 // be the first entry.
1561 assert(SwitchCases[0].ThisBB == CurMBB && "Unexpected lowering!");
1562
Chris Lattnerdf19f272006-10-31 22:37:42 +00001563 // Allow some cases to be rejected.
1564 if (ShouldEmitAsBranches(SwitchCases)) {
Chris Lattnerdf19f272006-10-31 22:37:42 +00001565 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
1566 ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
1567 ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
1568 }
1569
1570 // Emit the branch for this block.
1571 visitSwitchCase(SwitchCases[0]);
1572 SwitchCases.erase(SwitchCases.begin());
1573 return;
Chris Lattner5a145f02006-10-29 18:23:37 +00001574 }
1575
Chris Lattner0ccb5002006-10-31 23:06:00 +00001576 // Okay, we decided not to do this, remove any inserted MBB's and clear
1577 // SwitchCases.
1578 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
Dan Gohman0e5f1302008-07-07 23:02:41 +00001579 CurMBB->getParent()->erase(SwitchCases[i].ThisBB);
Chris Lattner0ccb5002006-10-31 23:06:00 +00001580
Chris Lattnerdf19f272006-10-31 22:37:42 +00001581 SwitchCases.clear();
Chris Lattner571e4342006-10-27 21:36:01 +00001582 }
1583 }
Chris Lattner24525952006-10-24 18:07:37 +00001584
1585 // Create a CaseBlock record representing this branch.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001586 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(),
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001587 NULL, Succ0MBB, Succ1MBB, CurMBB);
Chris Lattner24525952006-10-24 18:07:37 +00001588 // Use visitSwitchCase to actually insert the fast branch sequence for this
1589 // cond branch.
1590 visitSwitchCase(CB);
Chris Lattner1c08c712005-01-07 07:47:53 +00001591}
1592
Nate Begemanf15485a2006-03-27 01:32:24 +00001593/// visitSwitchCase - Emits the necessary code to represent a single node in
1594/// the binary search tree resulting from lowering a switch instruction.
1595void SelectionDAGLowering::visitSwitchCase(SelectionDAGISel::CaseBlock &CB) {
Dan Gohman475871a2008-07-27 21:46:04 +00001596 SDValue Cond;
1597 SDValue CondLHS = getValue(CB.CmpLHS);
Chris Lattner57ab6592006-10-24 17:57:59 +00001598
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001599 // Build the setcc now.
1600 if (CB.CmpMHS == NULL) {
1601 // Fold "(X == true)" to X and "(X == false)" to !X to
1602 // handle common cases produced by branch lowering.
1603 if (CB.CmpRHS == ConstantInt::getTrue() && CB.CC == ISD::SETEQ)
1604 Cond = CondLHS;
1605 else if (CB.CmpRHS == ConstantInt::getFalse() && CB.CC == ISD::SETEQ) {
Dan Gohman475871a2008-07-27 21:46:04 +00001606 SDValue True = DAG.getConstant(1, CondLHS.getValueType());
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001607 Cond = DAG.getNode(ISD::XOR, CondLHS.getValueType(), CondLHS, True);
1608 } else
1609 Cond = DAG.getSetCC(MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
1610 } else {
1611 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001612
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001613 uint64_t Low = cast<ConstantInt>(CB.CmpLHS)->getSExtValue();
1614 uint64_t High = cast<ConstantInt>(CB.CmpRHS)->getSExtValue();
1615
Dan Gohman475871a2008-07-27 21:46:04 +00001616 SDValue CmpOp = getValue(CB.CmpMHS);
Duncan Sands83ec4b62008-06-06 12:08:01 +00001617 MVT VT = CmpOp.getValueType();
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001618
1619 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
1620 Cond = DAG.getSetCC(MVT::i1, CmpOp, DAG.getConstant(High, VT), ISD::SETLE);
1621 } else {
Dan Gohman475871a2008-07-27 21:46:04 +00001622 SDValue SUB = DAG.getNode(ISD::SUB, VT, CmpOp, DAG.getConstant(Low, VT));
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001623 Cond = DAG.getSetCC(MVT::i1, SUB,
1624 DAG.getConstant(High-Low, VT), ISD::SETULE);
1625 }
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001626 }
1627
Owen Anderson2d389e82008-06-07 00:00:23 +00001628 // Update successor info
1629 CurMBB->addSuccessor(CB.TrueBB);
1630 CurMBB->addSuccessor(CB.FalseBB);
1631
Nate Begemanf15485a2006-03-27 01:32:24 +00001632 // Set NextBlock to be the MBB immediately after the current one, if any.
1633 // This is used to avoid emitting unnecessary branches to the next block.
1634 MachineBasicBlock *NextBlock = 0;
1635 MachineFunction::iterator BBI = CurMBB;
1636 if (++BBI != CurMBB->getParent()->end())
1637 NextBlock = BBI;
1638
1639 // If the lhs block is the next block, invert the condition so that we can
1640 // fall through to the lhs instead of the rhs block.
Chris Lattner57ab6592006-10-24 17:57:59 +00001641 if (CB.TrueBB == NextBlock) {
1642 std::swap(CB.TrueBB, CB.FalseBB);
Dan Gohman475871a2008-07-27 21:46:04 +00001643 SDValue True = DAG.getConstant(1, Cond.getValueType());
Nate Begemanf15485a2006-03-27 01:32:24 +00001644 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
1645 }
Dan Gohman475871a2008-07-27 21:46:04 +00001646 SDValue BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, getControlRoot(), Cond,
Chris Lattner57ab6592006-10-24 17:57:59 +00001647 DAG.getBasicBlock(CB.TrueBB));
Owen Andersonbd3ba462008-08-04 23:54:43 +00001648
1649 // If the branch was constant folded, fix up the CFG.
1650 if (BrCond.getOpcode() == ISD::BR) {
Owen Anderson3bc9c6f2008-08-05 18:27:54 +00001651 CurMBB->removeSuccessor(CB.FalseBB);
Nate Begemanf15485a2006-03-27 01:32:24 +00001652 DAG.setRoot(BrCond);
Owen Andersonbd3ba462008-08-04 23:54:43 +00001653 } else {
1654 // Otherwise, go ahead and insert the false branch.
1655 if (BrCond == getControlRoot())
Owen Anderson3bc9c6f2008-08-05 18:27:54 +00001656 CurMBB->removeSuccessor(CB.TrueBB);
Owen Andersonbd3ba462008-08-04 23:54:43 +00001657
1658 if (CB.FalseBB == NextBlock)
1659 DAG.setRoot(BrCond);
1660 else
1661 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond,
1662 DAG.getBasicBlock(CB.FalseBB)));
1663 }
Nate Begemanf15485a2006-03-27 01:32:24 +00001664}
1665
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001666/// visitJumpTable - Emit JumpTable node in the current MBB
Nate Begeman37efe672006-04-22 18:53:45 +00001667void SelectionDAGLowering::visitJumpTable(SelectionDAGISel::JumpTable &JT) {
Nate Begeman37efe672006-04-22 18:53:45 +00001668 // Emit the code for the jump table
Scott Michelf147a8d2007-04-24 01:24:20 +00001669 assert(JT.Reg != -1U && "Should lower JT Header first!");
Duncan Sands83ec4b62008-06-06 12:08:01 +00001670 MVT PTy = TLI.getPointerTy();
Dan Gohman475871a2008-07-27 21:46:04 +00001671 SDValue Index = DAG.getCopyFromReg(getControlRoot(), JT.Reg, PTy);
1672 SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
Evan Cheng3d4ce112006-10-30 08:00:44 +00001673 DAG.setRoot(DAG.getNode(ISD::BR_JT, MVT::Other, Index.getValue(1),
1674 Table, Index));
1675 return;
Nate Begeman37efe672006-04-22 18:53:45 +00001676}
1677
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001678/// visitJumpTableHeader - This function emits necessary code to produce index
1679/// in the JumpTable from switch case.
1680void SelectionDAGLowering::visitJumpTableHeader(SelectionDAGISel::JumpTable &JT,
1681 SelectionDAGISel::JumpTableHeader &JTH) {
1682 // Subtract the lowest switch case value from the value being switched on
1683 // and conditional branch to default mbb if the result is greater than the
1684 // difference between smallest and largest cases.
Dan Gohman475871a2008-07-27 21:46:04 +00001685 SDValue SwitchOp = getValue(JTH.SValue);
Duncan Sands83ec4b62008-06-06 12:08:01 +00001686 MVT VT = SwitchOp.getValueType();
Dan Gohman475871a2008-07-27 21:46:04 +00001687 SDValue SUB = DAG.getNode(ISD::SUB, VT, SwitchOp,
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001688 DAG.getConstant(JTH.First, VT));
1689
1690 // The SDNode we just created, which holds the value being switched on
1691 // minus the the smallest case value, needs to be copied to a virtual
1692 // register so it can be used as an index into the jump table in a
1693 // subsequent basic block. This value may be smaller or larger than the
1694 // target's pointer type, and therefore require extension or truncating.
Duncan Sands8e4eb092008-06-08 20:54:56 +00001695 if (VT.bitsGT(TLI.getPointerTy()))
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001696 SwitchOp = DAG.getNode(ISD::TRUNCATE, TLI.getPointerTy(), SUB);
1697 else
1698 SwitchOp = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(), SUB);
1699
1700 unsigned JumpTableReg = FuncInfo.MakeReg(TLI.getPointerTy());
Dan Gohman475871a2008-07-27 21:46:04 +00001701 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), JumpTableReg, SwitchOp);
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001702 JT.Reg = JumpTableReg;
1703
1704 // Emit the range check for the jump table, and branch to the default
1705 // block for the switch statement if the value being switched on exceeds
1706 // the largest case in the switch.
Dan Gohman475871a2008-07-27 21:46:04 +00001707 SDValue CMP = DAG.getSetCC(TLI.getSetCCResultType(SUB), SUB,
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001708 DAG.getConstant(JTH.Last-JTH.First,VT),
1709 ISD::SETUGT);
1710
1711 // Set NextBlock to be the MBB immediately after the current one, if any.
1712 // This is used to avoid emitting unnecessary branches to the next block.
1713 MachineBasicBlock *NextBlock = 0;
1714 MachineFunction::iterator BBI = CurMBB;
1715 if (++BBI != CurMBB->getParent()->end())
1716 NextBlock = BBI;
1717
Dan Gohman475871a2008-07-27 21:46:04 +00001718 SDValue BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, CopyTo, CMP,
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001719 DAG.getBasicBlock(JT.Default));
1720
1721 if (JT.MBB == NextBlock)
1722 DAG.setRoot(BrCond);
1723 else
1724 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond,
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001725 DAG.getBasicBlock(JT.MBB)));
1726
1727 return;
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001728}
1729
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001730/// visitBitTestHeader - This function emits necessary code to produce value
1731/// suitable for "bit tests"
1732void SelectionDAGLowering::visitBitTestHeader(SelectionDAGISel::BitTestBlock &B) {
1733 // Subtract the minimum value
Dan Gohman475871a2008-07-27 21:46:04 +00001734 SDValue SwitchOp = getValue(B.SValue);
Duncan Sands83ec4b62008-06-06 12:08:01 +00001735 MVT VT = SwitchOp.getValueType();
Dan Gohman475871a2008-07-27 21:46:04 +00001736 SDValue SUB = DAG.getNode(ISD::SUB, VT, SwitchOp,
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001737 DAG.getConstant(B.First, VT));
1738
1739 // Check range
Dan Gohman475871a2008-07-27 21:46:04 +00001740 SDValue RangeCmp = DAG.getSetCC(TLI.getSetCCResultType(SUB), SUB,
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001741 DAG.getConstant(B.Range, VT),
1742 ISD::SETUGT);
1743
Dan Gohman475871a2008-07-27 21:46:04 +00001744 SDValue ShiftOp;
Duncan Sands8e4eb092008-06-08 20:54:56 +00001745 if (VT.bitsGT(TLI.getShiftAmountTy()))
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001746 ShiftOp = DAG.getNode(ISD::TRUNCATE, TLI.getShiftAmountTy(), SUB);
1747 else
1748 ShiftOp = DAG.getNode(ISD::ZERO_EXTEND, TLI.getShiftAmountTy(), SUB);
1749
1750 // Make desired shift
Dan Gohman475871a2008-07-27 21:46:04 +00001751 SDValue SwitchVal = DAG.getNode(ISD::SHL, TLI.getPointerTy(),
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001752 DAG.getConstant(1, TLI.getPointerTy()),
1753 ShiftOp);
1754
1755 unsigned SwitchReg = FuncInfo.MakeReg(TLI.getPointerTy());
Dan Gohman475871a2008-07-27 21:46:04 +00001756 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), SwitchReg, SwitchVal);
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001757 B.Reg = SwitchReg;
1758
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001759 // Set NextBlock to be the MBB immediately after the current one, if any.
1760 // This is used to avoid emitting unnecessary branches to the next block.
1761 MachineBasicBlock *NextBlock = 0;
1762 MachineFunction::iterator BBI = CurMBB;
1763 if (++BBI != CurMBB->getParent()->end())
1764 NextBlock = BBI;
1765
1766 MachineBasicBlock* MBB = B.Cases[0].ThisBB;
Owen Anderson2d389e82008-06-07 00:00:23 +00001767
1768 CurMBB->addSuccessor(B.Default);
1769 CurMBB->addSuccessor(MBB);
1770
Dan Gohman475871a2008-07-27 21:46:04 +00001771 SDValue BrRange = DAG.getNode(ISD::BRCOND, MVT::Other, CopyTo, RangeCmp,
Owen Anderson2d389e82008-06-07 00:00:23 +00001772 DAG.getBasicBlock(B.Default));
1773
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001774 if (MBB == NextBlock)
1775 DAG.setRoot(BrRange);
1776 else
1777 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, CopyTo,
1778 DAG.getBasicBlock(MBB)));
1779
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001780 return;
1781}
1782
1783/// visitBitTestCase - this function produces one "bit test"
1784void SelectionDAGLowering::visitBitTestCase(MachineBasicBlock* NextMBB,
1785 unsigned Reg,
1786 SelectionDAGISel::BitTestCase &B) {
1787 // Emit bit tests and jumps
Dan Gohman475871a2008-07-27 21:46:04 +00001788 SDValue SwitchVal = DAG.getCopyFromReg(getControlRoot(), Reg,
Chris Lattneread0d882008-06-17 06:09:18 +00001789 TLI.getPointerTy());
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001790
Dan Gohman475871a2008-07-27 21:46:04 +00001791 SDValue AndOp = DAG.getNode(ISD::AND, TLI.getPointerTy(), SwitchVal,
Chris Lattneread0d882008-06-17 06:09:18 +00001792 DAG.getConstant(B.Mask, TLI.getPointerTy()));
Dan Gohman475871a2008-07-27 21:46:04 +00001793 SDValue AndCmp = DAG.getSetCC(TLI.getSetCCResultType(AndOp), AndOp,
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001794 DAG.getConstant(0, TLI.getPointerTy()),
1795 ISD::SETNE);
Owen Anderson2d389e82008-06-07 00:00:23 +00001796
1797 CurMBB->addSuccessor(B.TargetBB);
1798 CurMBB->addSuccessor(NextMBB);
1799
Dan Gohman475871a2008-07-27 21:46:04 +00001800 SDValue BrAnd = DAG.getNode(ISD::BRCOND, MVT::Other, getControlRoot(),
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001801 AndCmp, DAG.getBasicBlock(B.TargetBB));
1802
1803 // Set NextBlock to be the MBB immediately after the current one, if any.
1804 // This is used to avoid emitting unnecessary branches to the next block.
1805 MachineBasicBlock *NextBlock = 0;
1806 MachineFunction::iterator BBI = CurMBB;
1807 if (++BBI != CurMBB->getParent()->end())
1808 NextBlock = BBI;
1809
1810 if (NextMBB == NextBlock)
1811 DAG.setRoot(BrAnd);
1812 else
1813 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrAnd,
1814 DAG.getBasicBlock(NextMBB)));
1815
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001816 return;
1817}
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001818
Jim Laskeyb180aa12007-02-21 22:53:45 +00001819void SelectionDAGLowering::visitInvoke(InvokeInst &I) {
1820 // Retrieve successors.
1821 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
Duncan Sandsf19f6bb2007-06-13 05:51:31 +00001822 MachineBasicBlock *LandingPad = FuncInfo.MBBMap[I.getSuccessor(1)];
Duncan Sands9fac0b52007-06-06 10:05:18 +00001823
Duncan Sandsfd7b3262007-12-17 18:08:19 +00001824 if (isa<InlineAsm>(I.getCalledValue()))
1825 visitInlineAsm(&I);
1826 else
Duncan Sands6f74b482007-12-19 09:48:52 +00001827 LowerCallTo(&I, getValue(I.getOperand(0)), false, LandingPad);
Duncan Sands9fac0b52007-06-06 10:05:18 +00001828
Duncan Sandsf19f6bb2007-06-13 05:51:31 +00001829 // If the value of the invoke is used outside of its defining block, make it
1830 // available as a virtual register.
1831 if (!I.use_empty()) {
1832 DenseMap<const Value*, unsigned>::iterator VMI = FuncInfo.ValueMap.find(&I);
1833 if (VMI != FuncInfo.ValueMap.end())
Dan Gohman86e1ebf2008-03-27 19:56:19 +00001834 CopyValueToVirtualRegister(&I, VMI->second);
Jim Laskey183f47f2007-02-25 21:43:59 +00001835 }
Duncan Sandsf19f6bb2007-06-13 05:51:31 +00001836
Duncan Sandsf19f6bb2007-06-13 05:51:31 +00001837 // Update successor info
1838 CurMBB->addSuccessor(Return);
1839 CurMBB->addSuccessor(LandingPad);
Owen Anderson2d389e82008-06-07 00:00:23 +00001840
1841 // Drop into normal successor.
1842 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getControlRoot(),
1843 DAG.getBasicBlock(Return)));
Jim Laskeyb180aa12007-02-21 22:53:45 +00001844}
1845
1846void SelectionDAGLowering::visitUnwind(UnwindInst &I) {
1847}
1848
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001849/// handleSmallSwitchCaseRange - Emit a series of specific tests (suitable for
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001850/// small case ranges).
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001851bool SelectionDAGLowering::handleSmallSwitchRange(CaseRec& CR,
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001852 CaseRecVector& WorkList,
1853 Value* SV,
1854 MachineBasicBlock* Default) {
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001855 Case& BackCase = *(CR.Range.second-1);
1856
1857 // Size is the number of Cases represented by this range.
1858 unsigned Size = CR.Range.second - CR.Range.first;
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001859 if (Size > 3)
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001860 return false;
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001861
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001862 // Get the MachineFunction which holds the current MBB. This is used when
1863 // inserting any additional MBBs necessary to represent the switch.
1864 MachineFunction *CurMF = CurMBB->getParent();
1865
1866 // Figure out which block is immediately after the current one.
1867 MachineBasicBlock *NextBlock = 0;
1868 MachineFunction::iterator BBI = CR.CaseBB;
1869
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001870 if (++BBI != CurMBB->getParent()->end())
1871 NextBlock = BBI;
1872
1873 // TODO: If any two of the cases has the same destination, and if one value
1874 // is the same as the other, but has one bit unset that the other has set,
1875 // use bit manipulation to do two compares at once. For example:
1876 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
1877
1878 // Rearrange the case blocks so that the last one falls through if possible.
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001879 if (NextBlock && Default != NextBlock && BackCase.BB != NextBlock) {
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001880 // The last case block won't fall through into 'NextBlock' if we emit the
1881 // branches in this order. See if rearranging a case value would help.
1882 for (CaseItr I = CR.Range.first, E = CR.Range.second-1; I != E; ++I) {
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001883 if (I->BB == NextBlock) {
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001884 std::swap(*I, BackCase);
1885 break;
1886 }
1887 }
1888 }
1889
1890 // Create a CaseBlock record representing a conditional branch to
1891 // the Case's target mbb if the value being switched on SV is equal
1892 // to C.
1893 MachineBasicBlock *CurBlock = CR.CaseBB;
1894 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I) {
1895 MachineBasicBlock *FallThrough;
1896 if (I != E-1) {
Dan Gohman0e5f1302008-07-07 23:02:41 +00001897 FallThrough = CurMF->CreateMachineBasicBlock(CurBlock->getBasicBlock());
1898 CurMF->insert(BBI, FallThrough);
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001899 } else {
1900 // If the last case doesn't match, go to the default block.
1901 FallThrough = Default;
1902 }
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001903
1904 Value *RHS, *LHS, *MHS;
1905 ISD::CondCode CC;
1906 if (I->High == I->Low) {
1907 // This is just small small case range :) containing exactly 1 case
1908 CC = ISD::SETEQ;
1909 LHS = SV; RHS = I->High; MHS = NULL;
1910 } else {
1911 CC = ISD::SETLE;
1912 LHS = I->Low; MHS = SV; RHS = I->High;
1913 }
1914 SelectionDAGISel::CaseBlock CB(CC, LHS, RHS, MHS,
1915 I->BB, FallThrough, CurBlock);
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001916
1917 // If emitting the first comparison, just call visitSwitchCase to emit the
1918 // code into the current block. Otherwise, push the CaseBlock onto the
1919 // vector to be later processed by SDISel, and insert the node's MBB
1920 // before the next MBB.
1921 if (CurBlock == CurMBB)
1922 visitSwitchCase(CB);
1923 else
1924 SwitchCases.push_back(CB);
1925
1926 CurBlock = FallThrough;
1927 }
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001928
1929 return true;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001930}
1931
Anton Korobeynikov7294b582007-05-09 20:07:08 +00001932static inline bool areJTsAllowed(const TargetLowering &TLI) {
Dale Johannesen72324642008-07-31 18:13:12 +00001933 return !DisableJumpTables &&
1934 (TLI.isOperationLegal(ISD::BR_JT, MVT::Other) ||
1935 TLI.isOperationLegal(ISD::BRIND, MVT::Other));
Anton Korobeynikov7294b582007-05-09 20:07:08 +00001936}
1937
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001938/// handleJTSwitchCase - Emit jumptable for current switch case range
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001939bool SelectionDAGLowering::handleJTSwitchCase(CaseRec& CR,
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001940 CaseRecVector& WorkList,
1941 Value* SV,
1942 MachineBasicBlock* Default) {
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001943 Case& FrontCase = *CR.Range.first;
1944 Case& BackCase = *(CR.Range.second-1);
1945
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001946 int64_t First = cast<ConstantInt>(FrontCase.Low)->getSExtValue();
1947 int64_t Last = cast<ConstantInt>(BackCase.High)->getSExtValue();
1948
1949 uint64_t TSize = 0;
1950 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1951 I!=E; ++I)
1952 TSize += I->size();
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001953
Anton Korobeynikov7294b582007-05-09 20:07:08 +00001954 if (!areJTsAllowed(TLI) || TSize <= 3)
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001955 return false;
1956
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001957 double Density = (double)TSize / (double)((Last - First) + 1ULL);
1958 if (Density < 0.4)
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001959 return false;
1960
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001961 DOUT << "Lowering jump table\n"
1962 << "First entry: " << First << ". Last entry: " << Last << "\n"
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001963 << "Size: " << TSize << ". Density: " << Density << "\n\n";
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001964
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001965 // Get the MachineFunction which holds the current MBB. This is used when
1966 // inserting any additional MBBs necessary to represent the switch.
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001967 MachineFunction *CurMF = CurMBB->getParent();
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001968
1969 // Figure out which block is immediately after the current one.
1970 MachineBasicBlock *NextBlock = 0;
1971 MachineFunction::iterator BBI = CR.CaseBB;
1972
1973 if (++BBI != CurMBB->getParent()->end())
1974 NextBlock = BBI;
1975
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001976 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1977
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001978 // Create a new basic block to hold the code for loading the address
1979 // of the jump table, and jumping to it. Update successor information;
1980 // we will either branch to the default case for the switch, or the jump
1981 // table.
Dan Gohman0e5f1302008-07-07 23:02:41 +00001982 MachineBasicBlock *JumpTableBB = CurMF->CreateMachineBasicBlock(LLVMBB);
1983 CurMF->insert(BBI, JumpTableBB);
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001984 CR.CaseBB->addSuccessor(Default);
1985 CR.CaseBB->addSuccessor(JumpTableBB);
1986
1987 // Build a vector of destination BBs, corresponding to each target
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001988 // of the jump table. If the value of the jump table slot corresponds to
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001989 // a case statement, push the case's BB onto the vector, otherwise, push
1990 // the default BB.
1991 std::vector<MachineBasicBlock*> DestBBs;
1992 int64_t TEI = First;
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001993 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++TEI) {
1994 int64_t Low = cast<ConstantInt>(I->Low)->getSExtValue();
1995 int64_t High = cast<ConstantInt>(I->High)->getSExtValue();
1996
1997 if ((Low <= TEI) && (TEI <= High)) {
1998 DestBBs.push_back(I->BB);
1999 if (TEI==High)
2000 ++I;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00002001 } else {
2002 DestBBs.push_back(Default);
2003 }
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002004 }
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00002005
2006 // Update successor info. Add one edge to each unique successor.
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002007 BitVector SuccsHandled(CR.CaseBB->getParent()->getNumBlockIDs());
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00002008 for (std::vector<MachineBasicBlock*>::iterator I = DestBBs.begin(),
2009 E = DestBBs.end(); I != E; ++I) {
2010 if (!SuccsHandled[(*I)->getNumber()]) {
2011 SuccsHandled[(*I)->getNumber()] = true;
2012 JumpTableBB->addSuccessor(*I);
2013 }
2014 }
2015
2016 // Create a jump table index for this jump table, or return an existing
2017 // one.
2018 unsigned JTI = CurMF->getJumpTableInfo()->getJumpTableIndex(DestBBs);
2019
2020 // Set the jump table information so that we can codegen it as a second
2021 // MachineBasicBlock
Scott Michelf147a8d2007-04-24 01:24:20 +00002022 SelectionDAGISel::JumpTable JT(-1U, JTI, JumpTableBB, Default);
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00002023 SelectionDAGISel::JumpTableHeader JTH(First, Last, SV, CR.CaseBB,
2024 (CR.CaseBB == CurMBB));
2025 if (CR.CaseBB == CurMBB)
2026 visitJumpTableHeader(JT, JTH);
2027
2028 JTCases.push_back(SelectionDAGISel::JumpTableBlock(JTH, JT));
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00002029
Anton Korobeynikovdd433212007-03-27 12:05:48 +00002030 return true;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00002031}
2032
2033/// handleBTSplitSwitchCase - emit comparison and split binary search tree into
2034/// 2 subtrees.
Anton Korobeynikovdd433212007-03-27 12:05:48 +00002035bool SelectionDAGLowering::handleBTSplitSwitchCase(CaseRec& CR,
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00002036 CaseRecVector& WorkList,
2037 Value* SV,
2038 MachineBasicBlock* Default) {
2039 // Get the MachineFunction which holds the current MBB. This is used when
2040 // inserting any additional MBBs necessary to represent the switch.
2041 MachineFunction *CurMF = CurMBB->getParent();
2042
2043 // Figure out which block is immediately after the current one.
2044 MachineBasicBlock *NextBlock = 0;
2045 MachineFunction::iterator BBI = CR.CaseBB;
2046
2047 if (++BBI != CurMBB->getParent()->end())
2048 NextBlock = BBI;
2049
2050 Case& FrontCase = *CR.Range.first;
2051 Case& BackCase = *(CR.Range.second-1);
2052 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
2053
2054 // Size is the number of Cases represented by this range.
2055 unsigned Size = CR.Range.second - CR.Range.first;
2056
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002057 int64_t First = cast<ConstantInt>(FrontCase.Low)->getSExtValue();
2058 int64_t Last = cast<ConstantInt>(BackCase.High)->getSExtValue();
Anton Korobeynikov4198c582007-04-09 12:31:58 +00002059 double FMetric = 0;
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002060 CaseItr Pivot = CR.Range.first + Size/2;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00002061
2062 // Select optimal pivot, maximizing sum density of LHS and RHS. This will
2063 // (heuristically) allow us to emit JumpTable's later.
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002064 uint64_t TSize = 0;
2065 for (CaseItr I = CR.Range.first, E = CR.Range.second;
2066 I!=E; ++I)
2067 TSize += I->size();
2068
2069 uint64_t LSize = FrontCase.size();
2070 uint64_t RSize = TSize-LSize;
Anton Korobeynikov4198c582007-04-09 12:31:58 +00002071 DOUT << "Selecting best pivot: \n"
2072 << "First: " << First << ", Last: " << Last <<"\n"
2073 << "LSize: " << LSize << ", RSize: " << RSize << "\n";
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00002074 for (CaseItr I = CR.Range.first, J=I+1, E = CR.Range.second;
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002075 J!=E; ++I, ++J) {
2076 int64_t LEnd = cast<ConstantInt>(I->High)->getSExtValue();
2077 int64_t RBegin = cast<ConstantInt>(J->Low)->getSExtValue();
Anton Korobeynikov4198c582007-04-09 12:31:58 +00002078 assert((RBegin-LEnd>=1) && "Invalid case distance");
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00002079 double LDensity = (double)LSize / (double)((LEnd - First) + 1ULL);
2080 double RDensity = (double)RSize / (double)((Last - RBegin) + 1ULL);
Anton Korobeynikov54e2b142007-04-09 21:57:03 +00002081 double Metric = Log2_64(RBegin-LEnd)*(LDensity+RDensity);
Anton Korobeynikov4198c582007-04-09 12:31:58 +00002082 // Should always split in some non-trivial place
2083 DOUT <<"=>Step\n"
2084 << "LEnd: " << LEnd << ", RBegin: " << RBegin << "\n"
2085 << "LDensity: " << LDensity << ", RDensity: " << RDensity << "\n"
2086 << "Metric: " << Metric << "\n";
2087 if (FMetric < Metric) {
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00002088 Pivot = J;
Anton Korobeynikov4198c582007-04-09 12:31:58 +00002089 FMetric = Metric;
2090 DOUT << "Current metric set to: " << FMetric << "\n";
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00002091 }
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002092
2093 LSize += J->size();
2094 RSize -= J->size();
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00002095 }
Anton Korobeynikov7294b582007-05-09 20:07:08 +00002096 if (areJTsAllowed(TLI)) {
2097 // If our case is dense we *really* should handle it earlier!
2098 assert((FMetric > 0) && "Should handle dense range earlier!");
2099 } else {
2100 Pivot = CR.Range.first + Size/2;
2101 }
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00002102
2103 CaseRange LHSR(CR.Range.first, Pivot);
2104 CaseRange RHSR(Pivot, CR.Range.second);
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002105 Constant *C = Pivot->Low;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00002106 MachineBasicBlock *FalseBB = 0, *TrueBB = 0;
2107
2108 // We know that we branch to the LHS if the Value being switched on is
2109 // less than the Pivot value, C. We use this to optimize our binary
2110 // tree a bit, by recognizing that if SV is greater than or equal to the
2111 // LHS's Case Value, and that Case Value is exactly one less than the
2112 // Pivot's Value, then we can branch directly to the LHS's Target,
2113 // rather than creating a leaf node for it.
2114 if ((LHSR.second - LHSR.first) == 1 &&
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002115 LHSR.first->High == CR.GE &&
2116 cast<ConstantInt>(C)->getSExtValue() ==
2117 (cast<ConstantInt>(CR.GE)->getSExtValue() + 1LL)) {
2118 TrueBB = LHSR.first->BB;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00002119 } else {
Dan Gohman0e5f1302008-07-07 23:02:41 +00002120 TrueBB = CurMF->CreateMachineBasicBlock(LLVMBB);
2121 CurMF->insert(BBI, TrueBB);
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00002122 WorkList.push_back(CaseRec(TrueBB, C, CR.GE, LHSR));
2123 }
2124
2125 // Similar to the optimization above, if the Value being switched on is
2126 // known to be less than the Constant CR.LT, and the current Case Value
2127 // is CR.LT - 1, then we can branch directly to the target block for
2128 // the current Case Value, rather than emitting a RHS leaf node for it.
2129 if ((RHSR.second - RHSR.first) == 1 && CR.LT &&
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002130 cast<ConstantInt>(RHSR.first->Low)->getSExtValue() ==
2131 (cast<ConstantInt>(CR.LT)->getSExtValue() - 1LL)) {
2132 FalseBB = RHSR.first->BB;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00002133 } else {
Dan Gohman0e5f1302008-07-07 23:02:41 +00002134 FalseBB = CurMF->CreateMachineBasicBlock(LLVMBB);
2135 CurMF->insert(BBI, FalseBB);
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00002136 WorkList.push_back(CaseRec(FalseBB,CR.LT,C,RHSR));
2137 }
2138
2139 // Create a CaseBlock record representing a conditional branch to
2140 // the LHS node if the value being switched on SV is less than C.
2141 // Otherwise, branch to LHS.
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002142 SelectionDAGISel::CaseBlock CB(ISD::SETLT, SV, C, NULL,
2143 TrueBB, FalseBB, CR.CaseBB);
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00002144
2145 if (CR.CaseBB == CurMBB)
2146 visitSwitchCase(CB);
2147 else
2148 SwitchCases.push_back(CB);
Anton Korobeynikovdd433212007-03-27 12:05:48 +00002149
2150 return true;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00002151}
2152
Anton Korobeynikov4198c582007-04-09 12:31:58 +00002153/// handleBitTestsSwitchCase - if current case range has few destination and
2154/// range span less, than machine word bitwidth, encode case range into series
2155/// of masks and emit bit tests with these masks.
2156bool SelectionDAGLowering::handleBitTestsSwitchCase(CaseRec& CR,
2157 CaseRecVector& WorkList,
2158 Value* SV,
Chris Lattner3ff98172007-04-14 02:26:56 +00002159 MachineBasicBlock* Default){
Duncan Sands83ec4b62008-06-06 12:08:01 +00002160 unsigned IntPtrBits = TLI.getPointerTy().getSizeInBits();
Anton Korobeynikov4198c582007-04-09 12:31:58 +00002161
2162 Case& FrontCase = *CR.Range.first;
2163 Case& BackCase = *(CR.Range.second-1);
2164
2165 // Get the MachineFunction which holds the current MBB. This is used when
2166 // inserting any additional MBBs necessary to represent the switch.
2167 MachineFunction *CurMF = CurMBB->getParent();
2168
2169 unsigned numCmps = 0;
2170 for (CaseItr I = CR.Range.first, E = CR.Range.second;
2171 I!=E; ++I) {
2172 // Single case counts one, case range - two.
2173 if (I->Low == I->High)
2174 numCmps +=1;
2175 else
2176 numCmps +=2;
2177 }
2178
2179 // Count unique destinations
2180 SmallSet<MachineBasicBlock*, 4> Dests;
2181 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
2182 Dests.insert(I->BB);
2183 if (Dests.size() > 3)
2184 // Don't bother the code below, if there are too much unique destinations
2185 return false;
2186 }
2187 DOUT << "Total number of unique destinations: " << Dests.size() << "\n"
2188 << "Total number of comparisons: " << numCmps << "\n";
2189
2190 // Compute span of values.
2191 Constant* minValue = FrontCase.Low;
2192 Constant* maxValue = BackCase.High;
2193 uint64_t range = cast<ConstantInt>(maxValue)->getSExtValue() -
2194 cast<ConstantInt>(minValue)->getSExtValue();
2195 DOUT << "Compare range: " << range << "\n"
2196 << "Low bound: " << cast<ConstantInt>(minValue)->getSExtValue() << "\n"
2197 << "High bound: " << cast<ConstantInt>(maxValue)->getSExtValue() << "\n";
2198
Anton Korobeynikovab8fd402007-04-26 20:44:04 +00002199 if (range>=IntPtrBits ||
Anton Korobeynikov4198c582007-04-09 12:31:58 +00002200 (!(Dests.size() == 1 && numCmps >= 3) &&
2201 !(Dests.size() == 2 && numCmps >= 5) &&
2202 !(Dests.size() >= 3 && numCmps >= 6)))
2203 return false;
2204
2205 DOUT << "Emitting bit tests\n";
2206 int64_t lowBound = 0;
2207
2208 // Optimize the case where all the case values fit in a
2209 // word without having to subtract minValue. In this case,
2210 // we can optimize away the subtraction.
2211 if (cast<ConstantInt>(minValue)->getSExtValue() >= 0 &&
Anton Korobeynikove01017b2007-04-14 13:25:55 +00002212 cast<ConstantInt>(maxValue)->getSExtValue() < IntPtrBits) {
Anton Korobeynikov4198c582007-04-09 12:31:58 +00002213 range = cast<ConstantInt>(maxValue)->getSExtValue();
2214 } else {
2215 lowBound = cast<ConstantInt>(minValue)->getSExtValue();
2216 }
2217
2218 CaseBitsVector CasesBits;
2219 unsigned i, count = 0;
2220
2221 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
2222 MachineBasicBlock* Dest = I->BB;
2223 for (i = 0; i < count; ++i)
2224 if (Dest == CasesBits[i].BB)
2225 break;
2226
2227 if (i == count) {
2228 assert((count < 3) && "Too much destinations to test!");
2229 CasesBits.push_back(CaseBits(0, Dest, 0));
2230 count++;
2231 }
2232
2233 uint64_t lo = cast<ConstantInt>(I->Low)->getSExtValue() - lowBound;
2234 uint64_t hi = cast<ConstantInt>(I->High)->getSExtValue() - lowBound;
2235
2236 for (uint64_t j = lo; j <= hi; j++) {
Anton Korobeynikove01017b2007-04-14 13:25:55 +00002237 CasesBits[i].Mask |= 1ULL << j;
Anton Korobeynikov4198c582007-04-09 12:31:58 +00002238 CasesBits[i].Bits++;
2239 }
2240
2241 }
2242 std::sort(CasesBits.begin(), CasesBits.end(), CaseBitsCmp());
2243
2244 SelectionDAGISel::BitTestInfo BTC;
2245
2246 // Figure out which block is immediately after the current one.
2247 MachineFunction::iterator BBI = CR.CaseBB;
2248 ++BBI;
2249
2250 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
2251
2252 DOUT << "Cases:\n";
2253 for (unsigned i = 0, e = CasesBits.size(); i!=e; ++i) {
2254 DOUT << "Mask: " << CasesBits[i].Mask << ", Bits: " << CasesBits[i].Bits
2255 << ", BB: " << CasesBits[i].BB << "\n";
2256
Dan Gohman0e5f1302008-07-07 23:02:41 +00002257 MachineBasicBlock *CaseBB = CurMF->CreateMachineBasicBlock(LLVMBB);
2258 CurMF->insert(BBI, CaseBB);
Anton Korobeynikov4198c582007-04-09 12:31:58 +00002259 BTC.push_back(SelectionDAGISel::BitTestCase(CasesBits[i].Mask,
2260 CaseBB,
2261 CasesBits[i].BB));
2262 }
2263
2264 SelectionDAGISel::BitTestBlock BTB(lowBound, range, SV,
Jeff Cohenefc36622007-04-09 14:32:59 +00002265 -1U, (CR.CaseBB == CurMBB),
Anton Korobeynikov4198c582007-04-09 12:31:58 +00002266 CR.CaseBB, Default, BTC);
2267
2268 if (CR.CaseBB == CurMBB)
2269 visitBitTestHeader(BTB);
2270
2271 BitTestCases.push_back(BTB);
2272
2273 return true;
2274}
2275
2276
Dan Gohman86e1ebf2008-03-27 19:56:19 +00002277/// Clusterify - Transform simple list of Cases into list of CaseRange's
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002278unsigned SelectionDAGLowering::Clusterify(CaseVector& Cases,
2279 const SwitchInst& SI) {
2280 unsigned numCmps = 0;
2281
2282 // Start with "simple" cases
2283 for (unsigned i = 1; i < SI.getNumSuccessors(); ++i) {
2284 MachineBasicBlock *SMBB = FuncInfo.MBBMap[SI.getSuccessor(i)];
2285 Cases.push_back(Case(SI.getSuccessorValue(i),
2286 SI.getSuccessorValue(i),
2287 SMBB));
2288 }
Chris Lattnerb3d9cdb2007-11-27 06:14:32 +00002289 std::sort(Cases.begin(), Cases.end(), CaseCmp());
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002290
2291 // Merge case into clusters
2292 if (Cases.size()>=2)
David Greenea2a48852007-06-29 03:42:23 +00002293 // Must recompute end() each iteration because it may be
2294 // invalidated by erase if we hold on to it
Chris Lattner27a6c732007-11-24 07:07:01 +00002295 for (CaseItr I=Cases.begin(), J=++(Cases.begin()); J!=Cases.end(); ) {
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002296 int64_t nextValue = cast<ConstantInt>(J->Low)->getSExtValue();
2297 int64_t currentValue = cast<ConstantInt>(I->High)->getSExtValue();
2298 MachineBasicBlock* nextBB = J->BB;
2299 MachineBasicBlock* currentBB = I->BB;
2300
2301 // If the two neighboring cases go to the same destination, merge them
2302 // into a single case.
2303 if ((nextValue-currentValue==1) && (currentBB == nextBB)) {
2304 I->High = J->High;
2305 J = Cases.erase(J);
2306 } else {
2307 I = J++;
2308 }
2309 }
2310
2311 for (CaseItr I=Cases.begin(), E=Cases.end(); I!=E; ++I, ++numCmps) {
2312 if (I->Low != I->High)
2313 // A range counts double, since it requires two compares.
2314 ++numCmps;
2315 }
2316
2317 return numCmps;
2318}
2319
2320void SelectionDAGLowering::visitSwitch(SwitchInst &SI) {
Nate Begemanf15485a2006-03-27 01:32:24 +00002321 // Figure out which block is immediately after the current one.
2322 MachineBasicBlock *NextBlock = 0;
2323 MachineFunction::iterator BBI = CurMBB;
Bill Wendlingc70ddad2006-10-19 21:46:38 +00002324
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002325 MachineBasicBlock *Default = FuncInfo.MBBMap[SI.getDefaultDest()];
Chris Lattnerd2c1d222006-10-22 21:36:53 +00002326
Nate Begemanf15485a2006-03-27 01:32:24 +00002327 // If there is only the default destination, branch to it if it is not the
2328 // next basic block. Otherwise, just fall through.
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002329 if (SI.getNumOperands() == 2) {
Nate Begemanf15485a2006-03-27 01:32:24 +00002330 // Update machine-CFG edges.
Bill Wendlingc70ddad2006-10-19 21:46:38 +00002331
Nate Begemanf15485a2006-03-27 01:32:24 +00002332 // If this is not a fall-through branch, emit the branch.
Owen Anderson2d389e82008-06-07 00:00:23 +00002333 CurMBB->addSuccessor(Default);
Chris Lattnerd2c1d222006-10-22 21:36:53 +00002334 if (Default != NextBlock)
Dan Gohman86e1ebf2008-03-27 19:56:19 +00002335 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getControlRoot(),
Chris Lattnerd2c1d222006-10-22 21:36:53 +00002336 DAG.getBasicBlock(Default)));
Owen Anderson2d389e82008-06-07 00:00:23 +00002337
Nate Begemanf15485a2006-03-27 01:32:24 +00002338 return;
2339 }
2340
2341 // If there are any non-default case statements, create a vector of Cases
2342 // representing each one, and sort the vector so that we can efficiently
2343 // create a binary search tree from them.
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002344 CaseVector Cases;
2345 unsigned numCmps = Clusterify(Cases, SI);
2346 DOUT << "Clusterify finished. Total clusters: " << Cases.size()
2347 << ". Total compares: " << numCmps << "\n";
Bill Wendlingc70ddad2006-10-19 21:46:38 +00002348
Nate Begemanf15485a2006-03-27 01:32:24 +00002349 // Get the Value to be switched on and default basic blocks, which will be
2350 // inserted into CaseBlock records, representing basic blocks in the binary
2351 // search tree.
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002352 Value *SV = SI.getOperand(0);
Nate Begeman37efe672006-04-22 18:53:45 +00002353
Nate Begemanf15485a2006-03-27 01:32:24 +00002354 // Push the initial CaseRec onto the worklist
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00002355 CaseRecVector WorkList;
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00002356 WorkList.push_back(CaseRec(CurMBB,0,0,CaseRange(Cases.begin(),Cases.end())));
2357
2358 while (!WorkList.empty()) {
Nate Begemanf15485a2006-03-27 01:32:24 +00002359 // Grab a record representing a case range to process off the worklist
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00002360 CaseRec CR = WorkList.back();
2361 WorkList.pop_back();
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00002362
Anton Korobeynikov4198c582007-04-09 12:31:58 +00002363 if (handleBitTestsSwitchCase(CR, WorkList, SV, Default))
2364 continue;
2365
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00002366 // If the range has few cases (two or less) emit a series of specific
2367 // tests.
Anton Korobeynikovdd433212007-03-27 12:05:48 +00002368 if (handleSmallSwitchRange(CR, WorkList, SV, Default))
2369 continue;
2370
Anton Korobeynikov4198c582007-04-09 12:31:58 +00002371 // If the switch has more than 5 blocks, and at least 40% dense, and the
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00002372 // target supports indirect branches, then emit a jump table rather than
2373 // lowering the switch to a binary tree of conditional branches.
Anton Korobeynikovdd433212007-03-27 12:05:48 +00002374 if (handleJTSwitchCase(CR, WorkList, SV, Default))
2375 continue;
2376
2377 // Emit binary tree. We need to pick a pivot, and push left and right ranges
2378 // onto the worklist. Leafs are handled via handleSmallSwitchRange() call.
2379 handleBTSplitSwitchCase(CR, WorkList, SV, Default);
Nate Begemanf15485a2006-03-27 01:32:24 +00002380 }
2381}
2382
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00002383
Chris Lattnerb9fccc42005-04-02 05:04:50 +00002384void SelectionDAGLowering::visitSub(User &I) {
2385 // -0.0 - X --> fneg
Reid Spencer24d6da52007-01-21 00:29:26 +00002386 const Type *Ty = I.getType();
Reid Spencer9d6565a2007-02-15 02:26:10 +00002387 if (isa<VectorType>(Ty)) {
Dan Gohman7f321562007-06-25 16:23:39 +00002388 if (ConstantVector *CV = dyn_cast<ConstantVector>(I.getOperand(0))) {
2389 const VectorType *DestTy = cast<VectorType>(I.getType());
2390 const Type *ElTy = DestTy->getElementType();
Evan Chengc45453f2007-06-29 21:44:35 +00002391 if (ElTy->isFloatingPoint()) {
2392 unsigned VL = DestTy->getNumElements();
Dale Johannesen9e3d3ab2007-09-14 22:26:36 +00002393 std::vector<Constant*> NZ(VL, ConstantFP::getNegativeZero(ElTy));
Evan Chengc45453f2007-06-29 21:44:35 +00002394 Constant *CNZ = ConstantVector::get(&NZ[0], NZ.size());
2395 if (CV == CNZ) {
Dan Gohman475871a2008-07-27 21:46:04 +00002396 SDValue Op2 = getValue(I.getOperand(1));
Evan Chengc45453f2007-06-29 21:44:35 +00002397 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
2398 return;
2399 }
Dan Gohman7f321562007-06-25 16:23:39 +00002400 }
2401 }
2402 }
2403 if (Ty->isFloatingPoint()) {
Chris Lattner01b3d732005-09-28 22:28:18 +00002404 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
Dale Johannesen9e3d3ab2007-09-14 22:26:36 +00002405 if (CFP->isExactlyValue(ConstantFP::getNegativeZero(Ty)->getValueAPF())) {
Dan Gohman475871a2008-07-27 21:46:04 +00002406 SDValue Op2 = getValue(I.getOperand(1));
Chris Lattner01b3d732005-09-28 22:28:18 +00002407 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
2408 return;
2409 }
Dan Gohman7f321562007-06-25 16:23:39 +00002410 }
2411
2412 visitBinary(I, Ty->isFPOrFPVector() ? ISD::FSUB : ISD::SUB);
Chris Lattnerb9fccc42005-04-02 05:04:50 +00002413}
2414
Dan Gohman7f321562007-06-25 16:23:39 +00002415void SelectionDAGLowering::visitBinary(User &I, unsigned OpCode) {
Dan Gohman475871a2008-07-27 21:46:04 +00002416 SDValue Op1 = getValue(I.getOperand(0));
2417 SDValue Op2 = getValue(I.getOperand(1));
Reid Spencer24d6da52007-01-21 00:29:26 +00002418
2419 setValue(&I, DAG.getNode(OpCode, Op1.getValueType(), Op1, Op2));
Reid Spencer1628cec2006-10-26 06:15:43 +00002420}
2421
Nate Begemane21ea612005-11-18 07:42:56 +00002422void SelectionDAGLowering::visitShift(User &I, unsigned Opcode) {
Dan Gohman475871a2008-07-27 21:46:04 +00002423 SDValue Op1 = getValue(I.getOperand(0));
2424 SDValue Op2 = getValue(I.getOperand(1));
Nate Begeman5bc1ea02008-07-29 15:49:41 +00002425 if (!isa<VectorType>(I.getType())) {
2426 if (TLI.getShiftAmountTy().bitsLT(Op2.getValueType()))
2427 Op2 = DAG.getNode(ISD::TRUNCATE, TLI.getShiftAmountTy(), Op2);
2428 else if (TLI.getShiftAmountTy().bitsGT(Op2.getValueType()))
2429 Op2 = DAG.getNode(ISD::ANY_EXTEND, TLI.getShiftAmountTy(), Op2);
2430 }
Nate Begemane21ea612005-11-18 07:42:56 +00002431
Chris Lattner1c08c712005-01-07 07:47:53 +00002432 setValue(&I, DAG.getNode(Opcode, Op1.getValueType(), Op1, Op2));
2433}
2434
Reid Spencer45fb3f32006-11-20 01:22:35 +00002435void SelectionDAGLowering::visitICmp(User &I) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002436 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
2437 if (ICmpInst *IC = dyn_cast<ICmpInst>(&I))
2438 predicate = IC->getPredicate();
2439 else if (ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
2440 predicate = ICmpInst::Predicate(IC->getPredicate());
Dan Gohman475871a2008-07-27 21:46:04 +00002441 SDValue Op1 = getValue(I.getOperand(0));
2442 SDValue Op2 = getValue(I.getOperand(1));
Reid Spencer45fb3f32006-11-20 01:22:35 +00002443 ISD::CondCode Opcode;
Reid Spencere4d87aa2006-12-23 06:05:41 +00002444 switch (predicate) {
Reid Spencer45fb3f32006-11-20 01:22:35 +00002445 case ICmpInst::ICMP_EQ : Opcode = ISD::SETEQ; break;
2446 case ICmpInst::ICMP_NE : Opcode = ISD::SETNE; break;
2447 case ICmpInst::ICMP_UGT : Opcode = ISD::SETUGT; break;
2448 case ICmpInst::ICMP_UGE : Opcode = ISD::SETUGE; break;
2449 case ICmpInst::ICMP_ULT : Opcode = ISD::SETULT; break;
2450 case ICmpInst::ICMP_ULE : Opcode = ISD::SETULE; break;
2451 case ICmpInst::ICMP_SGT : Opcode = ISD::SETGT; break;
2452 case ICmpInst::ICMP_SGE : Opcode = ISD::SETGE; break;
2453 case ICmpInst::ICMP_SLT : Opcode = ISD::SETLT; break;
2454 case ICmpInst::ICMP_SLE : Opcode = ISD::SETLE; break;
2455 default:
2456 assert(!"Invalid ICmp predicate value");
2457 Opcode = ISD::SETEQ;
2458 break;
2459 }
2460 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Opcode));
2461}
2462
2463void SelectionDAGLowering::visitFCmp(User &I) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002464 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
2465 if (FCmpInst *FC = dyn_cast<FCmpInst>(&I))
2466 predicate = FC->getPredicate();
2467 else if (ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
2468 predicate = FCmpInst::Predicate(FC->getPredicate());
Dan Gohman475871a2008-07-27 21:46:04 +00002469 SDValue Op1 = getValue(I.getOperand(0));
2470 SDValue Op2 = getValue(I.getOperand(1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00002471 ISD::CondCode Condition, FOC, FPC;
2472 switch (predicate) {
2473 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
2474 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
2475 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
2476 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
2477 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
2478 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
2479 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
Dan Gohmancba3b442008-05-01 23:40:44 +00002480 case FCmpInst::FCMP_ORD: FOC = FPC = ISD::SETO; break;
2481 case FCmpInst::FCMP_UNO: FOC = FPC = ISD::SETUO; break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00002482 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
2483 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
2484 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
2485 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
2486 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
2487 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
2488 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
2489 default:
2490 assert(!"Invalid FCmp predicate value");
2491 FOC = FPC = ISD::SETFALSE;
2492 break;
2493 }
2494 if (FiniteOnlyFPMath())
2495 Condition = FOC;
2496 else
2497 Condition = FPC;
2498 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Condition));
Chris Lattner1c08c712005-01-07 07:47:53 +00002499}
2500
Nate Begemanb43e9c12008-05-12 19:40:03 +00002501void SelectionDAGLowering::visitVICmp(User &I) {
2502 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
2503 if (VICmpInst *IC = dyn_cast<VICmpInst>(&I))
2504 predicate = IC->getPredicate();
2505 else if (ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
2506 predicate = ICmpInst::Predicate(IC->getPredicate());
Dan Gohman475871a2008-07-27 21:46:04 +00002507 SDValue Op1 = getValue(I.getOperand(0));
2508 SDValue Op2 = getValue(I.getOperand(1));
Nate Begemanb43e9c12008-05-12 19:40:03 +00002509 ISD::CondCode Opcode;
2510 switch (predicate) {
2511 case ICmpInst::ICMP_EQ : Opcode = ISD::SETEQ; break;
2512 case ICmpInst::ICMP_NE : Opcode = ISD::SETNE; break;
2513 case ICmpInst::ICMP_UGT : Opcode = ISD::SETUGT; break;
2514 case ICmpInst::ICMP_UGE : Opcode = ISD::SETUGE; break;
2515 case ICmpInst::ICMP_ULT : Opcode = ISD::SETULT; break;
2516 case ICmpInst::ICMP_ULE : Opcode = ISD::SETULE; break;
2517 case ICmpInst::ICMP_SGT : Opcode = ISD::SETGT; break;
2518 case ICmpInst::ICMP_SGE : Opcode = ISD::SETGE; break;
2519 case ICmpInst::ICMP_SLT : Opcode = ISD::SETLT; break;
2520 case ICmpInst::ICMP_SLE : Opcode = ISD::SETLE; break;
2521 default:
2522 assert(!"Invalid ICmp predicate value");
2523 Opcode = ISD::SETEQ;
2524 break;
2525 }
2526 setValue(&I, DAG.getVSetCC(Op1.getValueType(), Op1, Op2, Opcode));
2527}
2528
2529void SelectionDAGLowering::visitVFCmp(User &I) {
2530 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
2531 if (VFCmpInst *FC = dyn_cast<VFCmpInst>(&I))
2532 predicate = FC->getPredicate();
2533 else if (ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
2534 predicate = FCmpInst::Predicate(FC->getPredicate());
Dan Gohman475871a2008-07-27 21:46:04 +00002535 SDValue Op1 = getValue(I.getOperand(0));
2536 SDValue Op2 = getValue(I.getOperand(1));
Nate Begemanb43e9c12008-05-12 19:40:03 +00002537 ISD::CondCode Condition, FOC, FPC;
2538 switch (predicate) {
2539 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
2540 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
2541 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
2542 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
2543 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
2544 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
2545 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
2546 case FCmpInst::FCMP_ORD: FOC = FPC = ISD::SETO; break;
2547 case FCmpInst::FCMP_UNO: FOC = FPC = ISD::SETUO; break;
2548 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
2549 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
2550 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
2551 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
2552 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
2553 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
2554 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
2555 default:
2556 assert(!"Invalid VFCmp predicate value");
2557 FOC = FPC = ISD::SETFALSE;
2558 break;
2559 }
2560 if (FiniteOnlyFPMath())
2561 Condition = FOC;
2562 else
2563 Condition = FPC;
2564
Duncan Sands83ec4b62008-06-06 12:08:01 +00002565 MVT DestVT = TLI.getValueType(I.getType());
Nate Begemanb43e9c12008-05-12 19:40:03 +00002566
2567 setValue(&I, DAG.getVSetCC(DestVT, Op1, Op2, Condition));
2568}
2569
Chris Lattner1c08c712005-01-07 07:47:53 +00002570void SelectionDAGLowering::visitSelect(User &I) {
Dan Gohman475871a2008-07-27 21:46:04 +00002571 SDValue Cond = getValue(I.getOperand(0));
2572 SDValue TrueVal = getValue(I.getOperand(1));
2573 SDValue FalseVal = getValue(I.getOperand(2));
Dan Gohman7f321562007-06-25 16:23:39 +00002574 setValue(&I, DAG.getNode(ISD::SELECT, TrueVal.getValueType(), Cond,
2575 TrueVal, FalseVal));
Chris Lattner1c08c712005-01-07 07:47:53 +00002576}
2577
Reid Spencer3da59db2006-11-27 01:05:10 +00002578
2579void SelectionDAGLowering::visitTrunc(User &I) {
2580 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
Dan Gohman475871a2008-07-27 21:46:04 +00002581 SDValue N = getValue(I.getOperand(0));
Duncan Sands83ec4b62008-06-06 12:08:01 +00002582 MVT DestVT = TLI.getValueType(I.getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00002583 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
2584}
2585
2586void SelectionDAGLowering::visitZExt(User &I) {
2587 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2588 // ZExt also can't be a cast to bool for same reason. So, nothing much to do
Dan Gohman475871a2008-07-27 21:46:04 +00002589 SDValue N = getValue(I.getOperand(0));
Duncan Sands83ec4b62008-06-06 12:08:01 +00002590 MVT DestVT = TLI.getValueType(I.getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00002591 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
2592}
2593
2594void SelectionDAGLowering::visitSExt(User &I) {
2595 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2596 // SExt also can't be a cast to bool for same reason. So, nothing much to do
Dan Gohman475871a2008-07-27 21:46:04 +00002597 SDValue N = getValue(I.getOperand(0));
Duncan Sands83ec4b62008-06-06 12:08:01 +00002598 MVT DestVT = TLI.getValueType(I.getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00002599 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, DestVT, N));
2600}
2601
2602void SelectionDAGLowering::visitFPTrunc(User &I) {
2603 // FPTrunc is never a no-op cast, no need to check
Dan Gohman475871a2008-07-27 21:46:04 +00002604 SDValue N = getValue(I.getOperand(0));
Duncan Sands83ec4b62008-06-06 12:08:01 +00002605 MVT DestVT = TLI.getValueType(I.getType());
Chris Lattner0bd48932008-01-17 07:00:52 +00002606 setValue(&I, DAG.getNode(ISD::FP_ROUND, DestVT, N, DAG.getIntPtrConstant(0)));
Reid Spencer3da59db2006-11-27 01:05:10 +00002607}
2608
2609void SelectionDAGLowering::visitFPExt(User &I){
2610 // FPTrunc is never a no-op cast, no need to check
Dan Gohman475871a2008-07-27 21:46:04 +00002611 SDValue N = getValue(I.getOperand(0));
Duncan Sands83ec4b62008-06-06 12:08:01 +00002612 MVT DestVT = TLI.getValueType(I.getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00002613 setValue(&I, DAG.getNode(ISD::FP_EXTEND, DestVT, N));
2614}
2615
2616void SelectionDAGLowering::visitFPToUI(User &I) {
2617 // FPToUI is never a no-op cast, no need to check
Dan Gohman475871a2008-07-27 21:46:04 +00002618 SDValue N = getValue(I.getOperand(0));
Duncan Sands83ec4b62008-06-06 12:08:01 +00002619 MVT DestVT = TLI.getValueType(I.getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00002620 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, DestVT, N));
2621}
2622
2623void SelectionDAGLowering::visitFPToSI(User &I) {
2624 // FPToSI is never a no-op cast, no need to check
Dan Gohman475871a2008-07-27 21:46:04 +00002625 SDValue N = getValue(I.getOperand(0));
Duncan Sands83ec4b62008-06-06 12:08:01 +00002626 MVT DestVT = TLI.getValueType(I.getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00002627 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, DestVT, N));
2628}
2629
2630void SelectionDAGLowering::visitUIToFP(User &I) {
2631 // UIToFP is never a no-op cast, no need to check
Dan Gohman475871a2008-07-27 21:46:04 +00002632 SDValue N = getValue(I.getOperand(0));
Duncan Sands83ec4b62008-06-06 12:08:01 +00002633 MVT DestVT = TLI.getValueType(I.getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00002634 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, DestVT, N));
2635}
2636
2637void SelectionDAGLowering::visitSIToFP(User &I){
2638 // UIToFP is never a no-op cast, no need to check
Dan Gohman475871a2008-07-27 21:46:04 +00002639 SDValue N = getValue(I.getOperand(0));
Duncan Sands83ec4b62008-06-06 12:08:01 +00002640 MVT DestVT = TLI.getValueType(I.getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00002641 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, DestVT, N));
2642}
2643
2644void SelectionDAGLowering::visitPtrToInt(User &I) {
2645 // What to do depends on the size of the integer and the size of the pointer.
2646 // We can either truncate, zero extend, or no-op, accordingly.
Dan Gohman475871a2008-07-27 21:46:04 +00002647 SDValue N = getValue(I.getOperand(0));
Duncan Sands83ec4b62008-06-06 12:08:01 +00002648 MVT SrcVT = N.getValueType();
2649 MVT DestVT = TLI.getValueType(I.getType());
Dan Gohman475871a2008-07-27 21:46:04 +00002650 SDValue Result;
Duncan Sands8e4eb092008-06-08 20:54:56 +00002651 if (DestVT.bitsLT(SrcVT))
Reid Spencer3da59db2006-11-27 01:05:10 +00002652 Result = DAG.getNode(ISD::TRUNCATE, DestVT, N);
2653 else
2654 // Note: ZERO_EXTEND can handle cases where the sizes are equal too
2655 Result = DAG.getNode(ISD::ZERO_EXTEND, DestVT, N);
2656 setValue(&I, Result);
2657}
Chris Lattner1c08c712005-01-07 07:47:53 +00002658
Reid Spencer3da59db2006-11-27 01:05:10 +00002659void SelectionDAGLowering::visitIntToPtr(User &I) {
2660 // What to do depends on the size of the integer and the size of the pointer.
2661 // We can either truncate, zero extend, or no-op, accordingly.
Dan Gohman475871a2008-07-27 21:46:04 +00002662 SDValue N = getValue(I.getOperand(0));
Duncan Sands83ec4b62008-06-06 12:08:01 +00002663 MVT SrcVT = N.getValueType();
2664 MVT DestVT = TLI.getValueType(I.getType());
Duncan Sands8e4eb092008-06-08 20:54:56 +00002665 if (DestVT.bitsLT(SrcVT))
Reid Spencer3da59db2006-11-27 01:05:10 +00002666 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
2667 else
2668 // Note: ZERO_EXTEND can handle cases where the sizes are equal too
2669 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
2670}
2671
2672void SelectionDAGLowering::visitBitCast(User &I) {
Dan Gohman475871a2008-07-27 21:46:04 +00002673 SDValue N = getValue(I.getOperand(0));
Duncan Sands83ec4b62008-06-06 12:08:01 +00002674 MVT DestVT = TLI.getValueType(I.getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00002675
2676 // BitCast assures us that source and destination are the same size so this
2677 // is either a BIT_CONVERT or a no-op.
2678 if (DestVT != N.getValueType())
2679 setValue(&I, DAG.getNode(ISD::BIT_CONVERT, DestVT, N)); // convert types
2680 else
2681 setValue(&I, N); // noop cast.
Chris Lattner1c08c712005-01-07 07:47:53 +00002682}
2683
Chris Lattner2bbd8102006-03-29 00:11:43 +00002684void SelectionDAGLowering::visitInsertElement(User &I) {
Dan Gohman475871a2008-07-27 21:46:04 +00002685 SDValue InVec = getValue(I.getOperand(0));
2686 SDValue InVal = getValue(I.getOperand(1));
2687 SDValue InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
Chris Lattnerc7029802006-03-18 01:44:44 +00002688 getValue(I.getOperand(2)));
2689
Dan Gohman7f321562007-06-25 16:23:39 +00002690 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT,
2691 TLI.getValueType(I.getType()),
2692 InVec, InVal, InIdx));
Chris Lattnerc7029802006-03-18 01:44:44 +00002693}
2694
Chris Lattner2bbd8102006-03-29 00:11:43 +00002695void SelectionDAGLowering::visitExtractElement(User &I) {
Dan Gohman475871a2008-07-27 21:46:04 +00002696 SDValue InVec = getValue(I.getOperand(0));
2697 SDValue InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
Chris Lattner384504c2006-03-21 20:44:12 +00002698 getValue(I.getOperand(1)));
Dan Gohman7f321562007-06-25 16:23:39 +00002699 setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
Chris Lattner384504c2006-03-21 20:44:12 +00002700 TLI.getValueType(I.getType()), InVec, InIdx));
2701}
Chris Lattnerc7029802006-03-18 01:44:44 +00002702
Chris Lattner3e104b12006-04-08 04:15:24 +00002703void SelectionDAGLowering::visitShuffleVector(User &I) {
Dan Gohman475871a2008-07-27 21:46:04 +00002704 SDValue V1 = getValue(I.getOperand(0));
2705 SDValue V2 = getValue(I.getOperand(1));
2706 SDValue Mask = getValue(I.getOperand(2));
Chris Lattner3e104b12006-04-08 04:15:24 +00002707
Dan Gohman7f321562007-06-25 16:23:39 +00002708 setValue(&I, DAG.getNode(ISD::VECTOR_SHUFFLE,
2709 TLI.getValueType(I.getType()),
2710 V1, V2, Mask));
Chris Lattner3e104b12006-04-08 04:15:24 +00002711}
2712
Dan Gohman1d685a42008-06-07 02:02:36 +00002713void SelectionDAGLowering::visitInsertValue(InsertValueInst &I) {
2714 const Value *Op0 = I.getOperand(0);
2715 const Value *Op1 = I.getOperand(1);
2716 const Type *AggTy = I.getType();
2717 const Type *ValTy = Op1->getType();
2718 bool IntoUndef = isa<UndefValue>(Op0);
2719 bool FromUndef = isa<UndefValue>(Op1);
2720
2721 unsigned LinearIndex = ComputeLinearIndex(TLI, AggTy,
2722 I.idx_begin(), I.idx_end());
2723
2724 SmallVector<MVT, 4> AggValueVTs;
2725 ComputeValueVTs(TLI, AggTy, AggValueVTs);
2726 SmallVector<MVT, 4> ValValueVTs;
2727 ComputeValueVTs(TLI, ValTy, ValValueVTs);
2728
2729 unsigned NumAggValues = AggValueVTs.size();
2730 unsigned NumValValues = ValValueVTs.size();
Dan Gohman475871a2008-07-27 21:46:04 +00002731 SmallVector<SDValue, 4> Values(NumAggValues);
Dan Gohman1d685a42008-06-07 02:02:36 +00002732
Dan Gohman475871a2008-07-27 21:46:04 +00002733 SDValue Agg = getValue(Op0);
2734 SDValue Val = getValue(Op1);
Dan Gohman1d685a42008-06-07 02:02:36 +00002735 unsigned i = 0;
2736 // Copy the beginning value(s) from the original aggregate.
2737 for (; i != LinearIndex; ++i)
2738 Values[i] = IntoUndef ? DAG.getNode(ISD::UNDEF, AggValueVTs[i]) :
Dan Gohman475871a2008-07-27 21:46:04 +00002739 SDValue(Agg.Val, Agg.ResNo + i);
Dan Gohman1d685a42008-06-07 02:02:36 +00002740 // Copy values from the inserted value(s).
2741 for (; i != LinearIndex + NumValValues; ++i)
2742 Values[i] = FromUndef ? DAG.getNode(ISD::UNDEF, AggValueVTs[i]) :
Dan Gohman475871a2008-07-27 21:46:04 +00002743 SDValue(Val.Val, Val.ResNo + i - LinearIndex);
Dan Gohman1d685a42008-06-07 02:02:36 +00002744 // Copy remaining value(s) from the original aggregate.
2745 for (; i != NumAggValues; ++i)
2746 Values[i] = IntoUndef ? DAG.getNode(ISD::UNDEF, AggValueVTs[i]) :
Dan Gohman475871a2008-07-27 21:46:04 +00002747 SDValue(Agg.Val, Agg.ResNo + i);
Dan Gohman1d685a42008-06-07 02:02:36 +00002748
Duncan Sandsf9516202008-06-30 10:19:09 +00002749 setValue(&I, DAG.getMergeValues(DAG.getVTList(&AggValueVTs[0], NumAggValues),
2750 &Values[0], NumAggValues));
Dan Gohman041e2eb2008-05-15 19:50:34 +00002751}
2752
Dan Gohman1d685a42008-06-07 02:02:36 +00002753void SelectionDAGLowering::visitExtractValue(ExtractValueInst &I) {
2754 const Value *Op0 = I.getOperand(0);
2755 const Type *AggTy = Op0->getType();
2756 const Type *ValTy = I.getType();
2757 bool OutOfUndef = isa<UndefValue>(Op0);
2758
2759 unsigned LinearIndex = ComputeLinearIndex(TLI, AggTy,
2760 I.idx_begin(), I.idx_end());
2761
2762 SmallVector<MVT, 4> ValValueVTs;
2763 ComputeValueVTs(TLI, ValTy, ValValueVTs);
2764
2765 unsigned NumValValues = ValValueVTs.size();
Dan Gohman475871a2008-07-27 21:46:04 +00002766 SmallVector<SDValue, 4> Values(NumValValues);
Dan Gohman1d685a42008-06-07 02:02:36 +00002767
Dan Gohman475871a2008-07-27 21:46:04 +00002768 SDValue Agg = getValue(Op0);
Dan Gohman1d685a42008-06-07 02:02:36 +00002769 // Copy out the selected value(s).
2770 for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
2771 Values[i - LinearIndex] =
Dan Gohmandded0fd2008-06-20 00:54:19 +00002772 OutOfUndef ? DAG.getNode(ISD::UNDEF, Agg.Val->getValueType(Agg.ResNo + i)) :
Dan Gohman475871a2008-07-27 21:46:04 +00002773 SDValue(Agg.Val, Agg.ResNo + i);
Dan Gohman1d685a42008-06-07 02:02:36 +00002774
Duncan Sandsf9516202008-06-30 10:19:09 +00002775 setValue(&I, DAG.getMergeValues(DAG.getVTList(&ValValueVTs[0], NumValValues),
2776 &Values[0], NumValValues));
Dan Gohman041e2eb2008-05-15 19:50:34 +00002777}
2778
Chris Lattner3e104b12006-04-08 04:15:24 +00002779
Chris Lattner1c08c712005-01-07 07:47:53 +00002780void SelectionDAGLowering::visitGetElementPtr(User &I) {
Dan Gohman475871a2008-07-27 21:46:04 +00002781 SDValue N = getValue(I.getOperand(0));
Chris Lattner1c08c712005-01-07 07:47:53 +00002782 const Type *Ty = I.getOperand(0)->getType();
Chris Lattner1c08c712005-01-07 07:47:53 +00002783
2784 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
2785 OI != E; ++OI) {
2786 Value *Idx = *OI;
Chris Lattnerc88d8e92005-12-05 07:10:48 +00002787 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002788 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
Chris Lattner1c08c712005-01-07 07:47:53 +00002789 if (Field) {
2790 // N = N + Offset
Chris Lattnerb1919e22007-02-10 19:55:17 +00002791 uint64_t Offset = TD->getStructLayout(StTy)->getElementOffset(Field);
Chris Lattner1c08c712005-01-07 07:47:53 +00002792 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
Chris Lattner0bd48932008-01-17 07:00:52 +00002793 DAG.getIntPtrConstant(Offset));
Chris Lattner1c08c712005-01-07 07:47:53 +00002794 }
2795 Ty = StTy->getElementType(Field);
2796 } else {
2797 Ty = cast<SequentialType>(Ty)->getElementType();
Chris Lattner7cc47772005-01-07 21:56:57 +00002798
Chris Lattner7c0104b2005-11-09 04:45:33 +00002799 // If this is a constant subscript, handle it quickly.
2800 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002801 if (CI->getZExtValue() == 0) continue;
Reid Spencer47857812006-12-31 05:55:36 +00002802 uint64_t Offs =
Dale Johannesena7ac2bd2007-10-01 23:08:35 +00002803 TD->getABITypeSize(Ty)*cast<ConstantInt>(CI)->getSExtValue();
Chris Lattner0bd48932008-01-17 07:00:52 +00002804 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
2805 DAG.getIntPtrConstant(Offs));
Chris Lattner7c0104b2005-11-09 04:45:33 +00002806 continue;
Chris Lattner1c08c712005-01-07 07:47:53 +00002807 }
Chris Lattner7c0104b2005-11-09 04:45:33 +00002808
2809 // N = N + Idx * ElementSize;
Dale Johannesena7ac2bd2007-10-01 23:08:35 +00002810 uint64_t ElementSize = TD->getABITypeSize(Ty);
Dan Gohman475871a2008-07-27 21:46:04 +00002811 SDValue IdxN = getValue(Idx);
Chris Lattner7c0104b2005-11-09 04:45:33 +00002812
2813 // If the index is smaller or larger than intptr_t, truncate or extend
2814 // it.
Evan Cheng83785c82008-08-20 22:45:34 +00002815 if (IdxN.getValueType().bitsLT(N.getValueType()))
Reid Spencer47857812006-12-31 05:55:36 +00002816 IdxN = DAG.getNode(ISD::SIGN_EXTEND, N.getValueType(), IdxN);
Evan Cheng83785c82008-08-20 22:45:34 +00002817 else if (IdxN.getValueType().bitsGT(N.getValueType()))
Chris Lattner7c0104b2005-11-09 04:45:33 +00002818 IdxN = DAG.getNode(ISD::TRUNCATE, N.getValueType(), IdxN);
2819
2820 // If this is a multiply by a power of two, turn it into a shl
2821 // immediately. This is a very common case.
Dan Gohman66799062008-08-23 01:06:51 +00002822 if (ElementSize != 1) {
2823 if (isPowerOf2_64(ElementSize)) {
2824 unsigned Amt = Log2_64(ElementSize);
2825 IdxN = DAG.getNode(ISD::SHL, N.getValueType(), IdxN,
2826 DAG.getConstant(Amt, TLI.getShiftAmountTy()));
2827 } else {
2828 SDValue Scale = DAG.getIntPtrConstant(ElementSize);
2829 IdxN = DAG.getNode(ISD::MUL, N.getValueType(), IdxN, Scale);
2830 }
Chris Lattner7c0104b2005-11-09 04:45:33 +00002831 }
Dan Gohman66799062008-08-23 01:06:51 +00002832
Chris Lattner7c0104b2005-11-09 04:45:33 +00002833 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
Chris Lattner1c08c712005-01-07 07:47:53 +00002834 }
2835 }
2836 setValue(&I, N);
2837}
2838
2839void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
2840 // If this is a fixed sized alloca in the entry block of the function,
2841 // allocate it statically on the stack.
2842 if (FuncInfo.StaticAllocaMap.count(&I))
2843 return; // getValue will auto-populate this.
2844
2845 const Type *Ty = I.getAllocatedType();
Duncan Sands514ab342007-11-01 20:53:16 +00002846 uint64_t TySize = TLI.getTargetData()->getABITypeSize(Ty);
Chris Lattner58092e32007-01-20 22:35:55 +00002847 unsigned Align =
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00002848 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
Chris Lattner58092e32007-01-20 22:35:55 +00002849 I.getAlignment());
Chris Lattner1c08c712005-01-07 07:47:53 +00002850
Dan Gohman475871a2008-07-27 21:46:04 +00002851 SDValue AllocSize = getValue(I.getArraySize());
Duncan Sands83ec4b62008-06-06 12:08:01 +00002852 MVT IntPtr = TLI.getPointerTy();
Duncan Sands8e4eb092008-06-08 20:54:56 +00002853 if (IntPtr.bitsLT(AllocSize.getValueType()))
Chris Lattner68cd65e2005-01-22 23:04:37 +00002854 AllocSize = DAG.getNode(ISD::TRUNCATE, IntPtr, AllocSize);
Duncan Sands8e4eb092008-06-08 20:54:56 +00002855 else if (IntPtr.bitsGT(AllocSize.getValueType()))
Chris Lattner68cd65e2005-01-22 23:04:37 +00002856 AllocSize = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, AllocSize);
Chris Lattner1c08c712005-01-07 07:47:53 +00002857
Chris Lattner68cd65e2005-01-22 23:04:37 +00002858 AllocSize = DAG.getNode(ISD::MUL, IntPtr, AllocSize,
Chris Lattner0bd48932008-01-17 07:00:52 +00002859 DAG.getIntPtrConstant(TySize));
Chris Lattner1c08c712005-01-07 07:47:53 +00002860
Evan Cheng45157792007-08-16 23:46:29 +00002861 // Handle alignment. If the requested alignment is less than or equal to
2862 // the stack alignment, ignore it. If the size is greater than or equal to
2863 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
Chris Lattner1c08c712005-01-07 07:47:53 +00002864 unsigned StackAlign =
2865 TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
Evan Cheng45157792007-08-16 23:46:29 +00002866 if (Align <= StackAlign)
Chris Lattner1c08c712005-01-07 07:47:53 +00002867 Align = 0;
Evan Cheng45157792007-08-16 23:46:29 +00002868
2869 // Round the size of the allocation up to the stack alignment size
2870 // by add SA-1 to the size.
2871 AllocSize = DAG.getNode(ISD::ADD, AllocSize.getValueType(), AllocSize,
Chris Lattner0bd48932008-01-17 07:00:52 +00002872 DAG.getIntPtrConstant(StackAlign-1));
Evan Cheng45157792007-08-16 23:46:29 +00002873 // Mask out the low bits for alignment purposes.
2874 AllocSize = DAG.getNode(ISD::AND, AllocSize.getValueType(), AllocSize,
Chris Lattner0bd48932008-01-17 07:00:52 +00002875 DAG.getIntPtrConstant(~(uint64_t)(StackAlign-1)));
Chris Lattner1c08c712005-01-07 07:47:53 +00002876
Dan Gohman475871a2008-07-27 21:46:04 +00002877 SDValue Ops[] = { getRoot(), AllocSize, DAG.getIntPtrConstant(Align) };
Duncan Sands83ec4b62008-06-06 12:08:01 +00002878 const MVT *VTs = DAG.getNodeValueTypes(AllocSize.getValueType(),
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00002879 MVT::Other);
Dan Gohman475871a2008-07-27 21:46:04 +00002880 SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, VTs, 2, Ops, 3);
Chris Lattner0da331f2007-02-04 01:31:47 +00002881 setValue(&I, DSA);
2882 DAG.setRoot(DSA.getValue(1));
Chris Lattner1c08c712005-01-07 07:47:53 +00002883
2884 // Inform the Frame Information that we have just allocated a variable-sized
2885 // object.
2886 CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
2887}
2888
Chris Lattner1c08c712005-01-07 07:47:53 +00002889void SelectionDAGLowering::visitLoad(LoadInst &I) {
Dan Gohman8a6ccb52008-06-09 15:21:47 +00002890 const Value *SV = I.getOperand(0);
Dan Gohman475871a2008-07-27 21:46:04 +00002891 SDValue Ptr = getValue(SV);
Dan Gohman8a6ccb52008-06-09 15:21:47 +00002892
2893 const Type *Ty = I.getType();
2894 bool isVolatile = I.isVolatile();
2895 unsigned Alignment = I.getAlignment();
2896
2897 SmallVector<MVT, 4> ValueVTs;
2898 SmallVector<uint64_t, 4> Offsets;
2899 ComputeValueVTs(TLI, Ty, ValueVTs, &Offsets);
2900 unsigned NumValues = ValueVTs.size();
2901 if (NumValues == 0)
2902 return;
Misha Brukmanedf128a2005-04-21 22:36:52 +00002903
Dan Gohman475871a2008-07-27 21:46:04 +00002904 SDValue Root;
Dan Gohman8b4588f2008-07-25 00:04:14 +00002905 bool ConstantMemory = false;
Chris Lattnerd3948112005-01-17 22:19:26 +00002906 if (I.isVolatile())
Dan Gohman8b4588f2008-07-25 00:04:14 +00002907 // Serialize volatile loads with other side effects.
Chris Lattnerd3948112005-01-17 22:19:26 +00002908 Root = getRoot();
Dan Gohman8b4588f2008-07-25 00:04:14 +00002909 else if (AA.pointsToConstantMemory(SV)) {
2910 // Do not serialize (non-volatile) loads of constant memory with anything.
2911 Root = DAG.getEntryNode();
2912 ConstantMemory = true;
2913 } else {
Chris Lattnerd3948112005-01-17 22:19:26 +00002914 // Do not serialize non-volatile loads against each other.
2915 Root = DAG.getRoot();
2916 }
Chris Lattner28b5b1c2006-03-15 22:19:46 +00002917
Dan Gohman475871a2008-07-27 21:46:04 +00002918 SmallVector<SDValue, 4> Values(NumValues);
2919 SmallVector<SDValue, 4> Chains(NumValues);
Dan Gohman1d685a42008-06-07 02:02:36 +00002920 MVT PtrVT = Ptr.getValueType();
2921 for (unsigned i = 0; i != NumValues; ++i) {
Dan Gohman475871a2008-07-27 21:46:04 +00002922 SDValue L = DAG.getLoad(ValueVTs[i], Root,
Dan Gohman1d685a42008-06-07 02:02:36 +00002923 DAG.getNode(ISD::ADD, PtrVT, Ptr,
2924 DAG.getConstant(Offsets[i], PtrVT)),
2925 SV, Offsets[i],
2926 isVolatile, Alignment);
2927 Values[i] = L;
2928 Chains[i] = L.getValue(1);
2929 }
Chris Lattner28b5b1c2006-03-15 22:19:46 +00002930
Dan Gohman8b4588f2008-07-25 00:04:14 +00002931 if (!ConstantMemory) {
Dan Gohman475871a2008-07-27 21:46:04 +00002932 SDValue Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
Dan Gohman8b4588f2008-07-25 00:04:14 +00002933 &Chains[0], NumValues);
2934 if (isVolatile)
2935 DAG.setRoot(Chain);
2936 else
2937 PendingLoads.push_back(Chain);
2938 }
Dan Gohman1d685a42008-06-07 02:02:36 +00002939
Duncan Sandsf9516202008-06-30 10:19:09 +00002940 setValue(&I, DAG.getMergeValues(DAG.getVTList(&ValueVTs[0], NumValues),
2941 &Values[0], NumValues));
Chris Lattner1c08c712005-01-07 07:47:53 +00002942}
2943
2944
2945void SelectionDAGLowering::visitStore(StoreInst &I) {
2946 Value *SrcV = I.getOperand(0);
Dan Gohman1d685a42008-06-07 02:02:36 +00002947 Value *PtrV = I.getOperand(1);
Dan Gohman1d685a42008-06-07 02:02:36 +00002948
2949 SmallVector<MVT, 4> ValueVTs;
2950 SmallVector<uint64_t, 4> Offsets;
2951 ComputeValueVTs(TLI, SrcV->getType(), ValueVTs, &Offsets);
2952 unsigned NumValues = ValueVTs.size();
Dan Gohman8a6ccb52008-06-09 15:21:47 +00002953 if (NumValues == 0)
2954 return;
Dan Gohman1d685a42008-06-07 02:02:36 +00002955
Dan Gohman90d33ee2008-07-30 18:36:51 +00002956 // Get the lowered operands. Note that we do this after
2957 // checking if NumResults is zero, because with zero results
2958 // the operands won't have values in the map.
2959 SDValue Src = getValue(SrcV);
2960 SDValue Ptr = getValue(PtrV);
2961
Dan Gohman475871a2008-07-27 21:46:04 +00002962 SDValue Root = getRoot();
2963 SmallVector<SDValue, 4> Chains(NumValues);
Dan Gohman1d685a42008-06-07 02:02:36 +00002964 MVT PtrVT = Ptr.getValueType();
2965 bool isVolatile = I.isVolatile();
2966 unsigned Alignment = I.getAlignment();
2967 for (unsigned i = 0; i != NumValues; ++i)
Dan Gohman475871a2008-07-27 21:46:04 +00002968 Chains[i] = DAG.getStore(Root, SDValue(Src.Val, Src.ResNo + i),
Dan Gohman1d685a42008-06-07 02:02:36 +00002969 DAG.getNode(ISD::ADD, PtrVT, Ptr,
2970 DAG.getConstant(Offsets[i], PtrVT)),
2971 PtrV, Offsets[i],
2972 isVolatile, Alignment);
2973
2974 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other, &Chains[0], NumValues));
Chris Lattner1c08c712005-01-07 07:47:53 +00002975}
2976
Chris Lattner0eade312006-03-24 02:22:33 +00002977/// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
2978/// node.
2979void SelectionDAGLowering::visitTargetIntrinsic(CallInst &I,
2980 unsigned Intrinsic) {
Duncan Sandsa3355ff2007-12-03 20:06:50 +00002981 bool HasChain = !I.doesNotAccessMemory();
2982 bool OnlyLoad = HasChain && I.onlyReadsMemory();
2983
Chris Lattner0eade312006-03-24 02:22:33 +00002984 // Build the operand list.
Dan Gohman475871a2008-07-27 21:46:04 +00002985 SmallVector<SDValue, 8> Ops;
Chris Lattnere58a7802006-04-02 03:41:14 +00002986 if (HasChain) { // If this intrinsic has side-effects, chainify it.
2987 if (OnlyLoad) {
2988 // We don't need to serialize loads against other loads.
2989 Ops.push_back(DAG.getRoot());
2990 } else {
2991 Ops.push_back(getRoot());
2992 }
2993 }
Chris Lattner0eade312006-03-24 02:22:33 +00002994
2995 // Add the intrinsic ID as an integer operand.
2996 Ops.push_back(DAG.getConstant(Intrinsic, TLI.getPointerTy()));
2997
2998 // Add all operands of the call to the operand list.
2999 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
Dan Gohman475871a2008-07-27 21:46:04 +00003000 SDValue Op = getValue(I.getOperand(i));
Chris Lattner0eade312006-03-24 02:22:33 +00003001 assert(TLI.isTypeLegal(Op.getValueType()) &&
3002 "Intrinsic uses a non-legal type?");
3003 Ops.push_back(Op);
3004 }
3005
Duncan Sands83ec4b62008-06-06 12:08:01 +00003006 std::vector<MVT> VTs;
Chris Lattner0eade312006-03-24 02:22:33 +00003007 if (I.getType() != Type::VoidTy) {
Duncan Sands83ec4b62008-06-06 12:08:01 +00003008 MVT VT = TLI.getValueType(I.getType());
3009 if (VT.isVector()) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00003010 const VectorType *DestTy = cast<VectorType>(I.getType());
Duncan Sands83ec4b62008-06-06 12:08:01 +00003011 MVT EltVT = TLI.getValueType(DestTy->getElementType());
Chris Lattner0eade312006-03-24 02:22:33 +00003012
Duncan Sands83ec4b62008-06-06 12:08:01 +00003013 VT = MVT::getVectorVT(EltVT, DestTy->getNumElements());
Chris Lattner0eade312006-03-24 02:22:33 +00003014 assert(VT != MVT::Other && "Intrinsic uses a non-legal type?");
3015 }
3016
3017 assert(TLI.isTypeLegal(VT) && "Intrinsic uses a non-legal type?");
3018 VTs.push_back(VT);
3019 }
3020 if (HasChain)
3021 VTs.push_back(MVT::Other);
3022
Duncan Sands83ec4b62008-06-06 12:08:01 +00003023 const MVT *VTList = DAG.getNodeValueTypes(VTs);
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00003024
Chris Lattner0eade312006-03-24 02:22:33 +00003025 // Create the node.
Dan Gohman475871a2008-07-27 21:46:04 +00003026 SDValue Result;
Chris Lattner48b61a72006-03-28 00:40:33 +00003027 if (!HasChain)
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00003028 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VTList, VTs.size(),
3029 &Ops[0], Ops.size());
Chris Lattner48b61a72006-03-28 00:40:33 +00003030 else if (I.getType() != Type::VoidTy)
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00003031 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, VTList, VTs.size(),
3032 &Ops[0], Ops.size());
Chris Lattner48b61a72006-03-28 00:40:33 +00003033 else
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00003034 Result = DAG.getNode(ISD::INTRINSIC_VOID, VTList, VTs.size(),
3035 &Ops[0], Ops.size());
Chris Lattner48b61a72006-03-28 00:40:33 +00003036
Chris Lattnere58a7802006-04-02 03:41:14 +00003037 if (HasChain) {
Dan Gohman475871a2008-07-27 21:46:04 +00003038 SDValue Chain = Result.getValue(Result.Val->getNumValues()-1);
Chris Lattnere58a7802006-04-02 03:41:14 +00003039 if (OnlyLoad)
3040 PendingLoads.push_back(Chain);
3041 else
3042 DAG.setRoot(Chain);
3043 }
Chris Lattner0eade312006-03-24 02:22:33 +00003044 if (I.getType() != Type::VoidTy) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00003045 if (const VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
Duncan Sands83ec4b62008-06-06 12:08:01 +00003046 MVT VT = TLI.getValueType(PTy);
Dan Gohman7f321562007-06-25 16:23:39 +00003047 Result = DAG.getNode(ISD::BIT_CONVERT, VT, Result);
Chris Lattner0eade312006-03-24 02:22:33 +00003048 }
3049 setValue(&I, Result);
3050 }
3051}
3052
Duncan Sandsb4fd45e2007-07-06 09:10:03 +00003053/// ExtractTypeInfo - Returns the type info, possibly bitcast, encoded in V.
Duncan Sandscf26d7c2007-07-04 20:52:51 +00003054static GlobalVariable *ExtractTypeInfo (Value *V) {
Anton Korobeynikov0b12ecf2008-05-07 22:54:15 +00003055 V = V->stripPointerCasts();
Duncan Sandsb4fd45e2007-07-06 09:10:03 +00003056 GlobalVariable *GV = dyn_cast<GlobalVariable>(V);
Anton Korobeynikov4c71dfe2008-02-20 11:10:28 +00003057 assert ((GV || isa<ConstantPointerNull>(V)) &&
Duncan Sandscf26d7c2007-07-04 20:52:51 +00003058 "TypeInfo must be a global variable or NULL");
3059 return GV;
3060}
3061
Duncan Sandsf4070822007-06-15 19:04:19 +00003062/// addCatchInfo - Extract the personality and type infos from an eh.selector
Duncan Sandscf26d7c2007-07-04 20:52:51 +00003063/// call, and add them to the specified machine basic block.
Duncan Sandsf4070822007-06-15 19:04:19 +00003064static void addCatchInfo(CallInst &I, MachineModuleInfo *MMI,
3065 MachineBasicBlock *MBB) {
3066 // Inform the MachineModuleInfo of the personality for this landing pad.
3067 ConstantExpr *CE = cast<ConstantExpr>(I.getOperand(2));
3068 assert(CE->getOpcode() == Instruction::BitCast &&
3069 isa<Function>(CE->getOperand(0)) &&
3070 "Personality should be a function");
3071 MMI->addPersonality(MBB, cast<Function>(CE->getOperand(0)));
3072
3073 // Gather all the type infos for this landing pad and pass them along to
3074 // MachineModuleInfo.
3075 std::vector<GlobalVariable *> TyInfo;
Duncan Sandscf26d7c2007-07-04 20:52:51 +00003076 unsigned N = I.getNumOperands();
3077
3078 for (unsigned i = N - 1; i > 2; --i) {
3079 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(i))) {
3080 unsigned FilterLength = CI->getZExtValue();
Duncan Sands6590b042007-08-27 15:47:50 +00003081 unsigned FirstCatch = i + FilterLength + !FilterLength;
Duncan Sandscf26d7c2007-07-04 20:52:51 +00003082 assert (FirstCatch <= N && "Invalid filter length");
3083
3084 if (FirstCatch < N) {
3085 TyInfo.reserve(N - FirstCatch);
3086 for (unsigned j = FirstCatch; j < N; ++j)
3087 TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
3088 MMI->addCatchTypeInfo(MBB, TyInfo);
3089 TyInfo.clear();
3090 }
3091
Duncan Sands6590b042007-08-27 15:47:50 +00003092 if (!FilterLength) {
3093 // Cleanup.
3094 MMI->addCleanup(MBB);
3095 } else {
3096 // Filter.
3097 TyInfo.reserve(FilterLength - 1);
3098 for (unsigned j = i + 1; j < FirstCatch; ++j)
3099 TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
3100 MMI->addFilterTypeInfo(MBB, TyInfo);
3101 TyInfo.clear();
3102 }
Duncan Sandscf26d7c2007-07-04 20:52:51 +00003103
3104 N = i;
3105 }
Duncan Sandsf4070822007-06-15 19:04:19 +00003106 }
Duncan Sandscf26d7c2007-07-04 20:52:51 +00003107
3108 if (N > 3) {
3109 TyInfo.reserve(N - 3);
3110 for (unsigned j = 3; j < N; ++j)
3111 TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
Duncan Sandsf4070822007-06-15 19:04:19 +00003112 MMI->addCatchTypeInfo(MBB, TyInfo);
Duncan Sandscf26d7c2007-07-04 20:52:51 +00003113 }
Duncan Sandsf4070822007-06-15 19:04:19 +00003114}
3115
Mon P Wang63307c32008-05-05 19:05:59 +00003116
3117/// Inlined utility function to implement binary input atomic intrinsics for
3118// visitIntrinsicCall: I is a call instruction
3119// Op is the associated NodeType for I
3120const char *
3121SelectionDAGLowering::implVisitBinaryAtomic(CallInst& I, ISD::NodeType Op) {
Dan Gohman475871a2008-07-27 21:46:04 +00003122 SDValue Root = getRoot();
3123 SDValue L = DAG.getAtomic(Op, Root,
Mon P Wang63307c32008-05-05 19:05:59 +00003124 getValue(I.getOperand(1)),
Dan Gohmanfd4418f2008-06-25 16:07:49 +00003125 getValue(I.getOperand(2)),
Mon P Wang28873102008-06-25 08:15:39 +00003126 I.getOperand(1));
Mon P Wang63307c32008-05-05 19:05:59 +00003127 setValue(&I, L);
3128 DAG.setRoot(L.getValue(1));
3129 return 0;
3130}
3131
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003132/// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
3133/// we want to emit this as a call to a named external function, return the name
3134/// otherwise lower it and return null.
3135const char *
3136SelectionDAGLowering::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
3137 switch (Intrinsic) {
Chris Lattner0eade312006-03-24 02:22:33 +00003138 default:
3139 // By default, turn this into a target intrinsic node.
3140 visitTargetIntrinsic(I, Intrinsic);
3141 return 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003142 case Intrinsic::vastart: visitVAStart(I); return 0;
3143 case Intrinsic::vaend: visitVAEnd(I); return 0;
3144 case Intrinsic::vacopy: visitVACopy(I); return 0;
Nate Begemanbcc5f362007-01-29 22:58:52 +00003145 case Intrinsic::returnaddress:
3146 setValue(&I, DAG.getNode(ISD::RETURNADDR, TLI.getPointerTy(),
3147 getValue(I.getOperand(1))));
3148 return 0;
3149 case Intrinsic::frameaddress:
3150 setValue(&I, DAG.getNode(ISD::FRAMEADDR, TLI.getPointerTy(),
3151 getValue(I.getOperand(1))));
3152 return 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003153 case Intrinsic::setjmp:
Anton Korobeynikovd27a2582006-12-10 23:12:42 +00003154 return "_setjmp"+!TLI.usesUnderscoreSetJmp();
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003155 break;
3156 case Intrinsic::longjmp:
Anton Korobeynikovd27a2582006-12-10 23:12:42 +00003157 return "_longjmp"+!TLI.usesUnderscoreLongJmp();
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003158 break;
Chris Lattner03dd4652006-03-03 00:00:25 +00003159 case Intrinsic::memcpy_i32:
Dan Gohman707e0182008-04-12 04:36:06 +00003160 case Intrinsic::memcpy_i64: {
Dan Gohman475871a2008-07-27 21:46:04 +00003161 SDValue Op1 = getValue(I.getOperand(1));
3162 SDValue Op2 = getValue(I.getOperand(2));
3163 SDValue Op3 = getValue(I.getOperand(3));
Dan Gohman707e0182008-04-12 04:36:06 +00003164 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
3165 DAG.setRoot(DAG.getMemcpy(getRoot(), Op1, Op2, Op3, Align, false,
3166 I.getOperand(1), 0, I.getOperand(2), 0));
Chris Lattner03dd4652006-03-03 00:00:25 +00003167 return 0;
Dan Gohman707e0182008-04-12 04:36:06 +00003168 }
Chris Lattner03dd4652006-03-03 00:00:25 +00003169 case Intrinsic::memset_i32:
Dan Gohman707e0182008-04-12 04:36:06 +00003170 case Intrinsic::memset_i64: {
Dan Gohman475871a2008-07-27 21:46:04 +00003171 SDValue Op1 = getValue(I.getOperand(1));
3172 SDValue Op2 = getValue(I.getOperand(2));
3173 SDValue Op3 = getValue(I.getOperand(3));
Dan Gohman707e0182008-04-12 04:36:06 +00003174 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
3175 DAG.setRoot(DAG.getMemset(getRoot(), Op1, Op2, Op3, Align,
3176 I.getOperand(1), 0));
Chris Lattner03dd4652006-03-03 00:00:25 +00003177 return 0;
Dan Gohman707e0182008-04-12 04:36:06 +00003178 }
Chris Lattner03dd4652006-03-03 00:00:25 +00003179 case Intrinsic::memmove_i32:
Dan Gohman707e0182008-04-12 04:36:06 +00003180 case Intrinsic::memmove_i64: {
Dan Gohman475871a2008-07-27 21:46:04 +00003181 SDValue Op1 = getValue(I.getOperand(1));
3182 SDValue Op2 = getValue(I.getOperand(2));
3183 SDValue Op3 = getValue(I.getOperand(3));
Dan Gohman707e0182008-04-12 04:36:06 +00003184 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
3185
3186 // If the source and destination are known to not be aliases, we can
3187 // lower memmove as memcpy.
3188 uint64_t Size = -1ULL;
3189 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op3))
3190 Size = C->getValue();
3191 if (AA.alias(I.getOperand(1), Size, I.getOperand(2), Size) ==
3192 AliasAnalysis::NoAlias) {
3193 DAG.setRoot(DAG.getMemcpy(getRoot(), Op1, Op2, Op3, Align, false,
3194 I.getOperand(1), 0, I.getOperand(2), 0));
3195 return 0;
3196 }
3197
3198 DAG.setRoot(DAG.getMemmove(getRoot(), Op1, Op2, Op3, Align,
3199 I.getOperand(1), 0, I.getOperand(2), 0));
Chris Lattner03dd4652006-03-03 00:00:25 +00003200 return 0;
Dan Gohman707e0182008-04-12 04:36:06 +00003201 }
Chris Lattner86cb6432005-12-13 17:40:33 +00003202 case Intrinsic::dbg_stoppoint: {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00003203 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskey43970fe2006-03-23 18:06:46 +00003204 DbgStopPointInst &SPI = cast<DbgStopPointInst>(I);
Jim Laskey44c3b9f2007-01-26 21:22:28 +00003205 if (MMI && SPI.getContext() && MMI->Verify(SPI.getContext())) {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00003206 DebugInfoDesc *DD = MMI->getDescFor(SPI.getContext());
Jim Laskeyce72b172006-02-11 01:01:30 +00003207 assert(DD && "Not a debug information descriptor");
Dan Gohman7f460202008-06-30 20:59:49 +00003208 DAG.setRoot(DAG.getDbgStopPoint(getRoot(),
3209 SPI.getLine(),
3210 SPI.getColumn(),
3211 cast<CompileUnitDesc>(DD)));
Chris Lattner86cb6432005-12-13 17:40:33 +00003212 }
Jim Laskey43970fe2006-03-23 18:06:46 +00003213
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +00003214 return 0;
Chris Lattner36ce6912005-11-29 06:21:05 +00003215 }
Jim Laskey43970fe2006-03-23 18:06:46 +00003216 case Intrinsic::dbg_region_start: {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00003217 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskey43970fe2006-03-23 18:06:46 +00003218 DbgRegionStartInst &RSI = cast<DbgRegionStartInst>(I);
Jim Laskey44c3b9f2007-01-26 21:22:28 +00003219 if (MMI && RSI.getContext() && MMI->Verify(RSI.getContext())) {
3220 unsigned LabelID = MMI->RecordRegionStart(RSI.getContext());
Dan Gohman44066042008-07-01 00:05:16 +00003221 DAG.setRoot(DAG.getLabel(ISD::DBG_LABEL, getRoot(), LabelID));
Jim Laskey43970fe2006-03-23 18:06:46 +00003222 }
3223
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +00003224 return 0;
Jim Laskey43970fe2006-03-23 18:06:46 +00003225 }
3226 case Intrinsic::dbg_region_end: {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00003227 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskey43970fe2006-03-23 18:06:46 +00003228 DbgRegionEndInst &REI = cast<DbgRegionEndInst>(I);
Jim Laskey44c3b9f2007-01-26 21:22:28 +00003229 if (MMI && REI.getContext() && MMI->Verify(REI.getContext())) {
3230 unsigned LabelID = MMI->RecordRegionEnd(REI.getContext());
Dan Gohman44066042008-07-01 00:05:16 +00003231 DAG.setRoot(DAG.getLabel(ISD::DBG_LABEL, getRoot(), LabelID));
Jim Laskey43970fe2006-03-23 18:06:46 +00003232 }
3233
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +00003234 return 0;
Jim Laskey43970fe2006-03-23 18:06:46 +00003235 }
3236 case Intrinsic::dbg_func_start: {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00003237 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Evan Cheng1b08bbc2008-02-01 09:10:45 +00003238 if (!MMI) return 0;
Jim Laskey43970fe2006-03-23 18:06:46 +00003239 DbgFuncStartInst &FSI = cast<DbgFuncStartInst>(I);
Evan Cheng1b08bbc2008-02-01 09:10:45 +00003240 Value *SP = FSI.getSubprogram();
3241 if (SP && MMI->Verify(SP)) {
3242 // llvm.dbg.func.start implicitly defines a dbg_stoppoint which is
3243 // what (most?) gdb expects.
3244 DebugInfoDesc *DD = MMI->getDescFor(SP);
3245 assert(DD && "Not a debug information descriptor");
3246 SubprogramDesc *Subprogram = cast<SubprogramDesc>(DD);
3247 const CompileUnitDesc *CompileUnit = Subprogram->getFile();
Dan Gohman99fe47b2008-06-30 22:21:03 +00003248 unsigned SrcFile = MMI->RecordSource(CompileUnit);
Evan Cheng1b08bbc2008-02-01 09:10:45 +00003249 // Record the source line but does create a label. It will be emitted
3250 // at asm emission time.
3251 MMI->RecordSourceLine(Subprogram->getLine(), 0, SrcFile);
Jim Laskey43970fe2006-03-23 18:06:46 +00003252 }
3253
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +00003254 return 0;
Jim Laskey43970fe2006-03-23 18:06:46 +00003255 }
3256 case Intrinsic::dbg_declare: {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00003257 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskey43970fe2006-03-23 18:06:46 +00003258 DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
Evan Chenga844bde2008-02-02 04:07:54 +00003259 Value *Variable = DI.getVariable();
3260 if (MMI && Variable && MMI->Verify(Variable))
3261 DAG.setRoot(DAG.getNode(ISD::DECLARE, MVT::Other, getRoot(),
3262 getValue(DI.getAddress()), getValue(Variable)));
Jim Laskey43970fe2006-03-23 18:06:46 +00003263 return 0;
3264 }
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003265
Jim Laskeyb180aa12007-02-21 22:53:45 +00003266 case Intrinsic::eh_exception: {
Dale Johannesen1532f3d2008-04-02 00:25:04 +00003267 if (!CurMBB->isLandingPad()) {
3268 // FIXME: Mark exception register as live in. Hack for PR1508.
3269 unsigned Reg = TLI.getExceptionAddressRegister();
3270 if (Reg) CurMBB->addLiveIn(Reg);
Jim Laskey735b6f82007-02-22 15:38:06 +00003271 }
Dale Johannesen1532f3d2008-04-02 00:25:04 +00003272 // Insert the EXCEPTIONADDR instruction.
3273 SDVTList VTs = DAG.getVTList(TLI.getPointerTy(), MVT::Other);
Dan Gohman475871a2008-07-27 21:46:04 +00003274 SDValue Ops[1];
Dale Johannesen1532f3d2008-04-02 00:25:04 +00003275 Ops[0] = DAG.getRoot();
Dan Gohman475871a2008-07-27 21:46:04 +00003276 SDValue Op = DAG.getNode(ISD::EXCEPTIONADDR, VTs, Ops, 1);
Dale Johannesen1532f3d2008-04-02 00:25:04 +00003277 setValue(&I, Op);
3278 DAG.setRoot(Op.getValue(1));
Jim Laskeyb180aa12007-02-21 22:53:45 +00003279 return 0;
3280 }
3281
Anton Korobeynikov8806c7b2007-09-07 11:39:35 +00003282 case Intrinsic::eh_selector_i32:
3283 case Intrinsic::eh_selector_i64: {
Jim Laskeyb180aa12007-02-21 22:53:45 +00003284 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Duncan Sands83ec4b62008-06-06 12:08:01 +00003285 MVT VT = (Intrinsic == Intrinsic::eh_selector_i32 ?
Anton Korobeynikov8806c7b2007-09-07 11:39:35 +00003286 MVT::i32 : MVT::i64);
3287
Dale Johannesen1532f3d2008-04-02 00:25:04 +00003288 if (MMI) {
Duncan Sandsf4070822007-06-15 19:04:19 +00003289 if (CurMBB->isLandingPad())
3290 addCatchInfo(I, MMI, CurMBB);
Evan Chenge47c3332007-06-27 18:45:32 +00003291 else {
Duncan Sandsf4070822007-06-15 19:04:19 +00003292#ifndef NDEBUG
Duncan Sandsf4070822007-06-15 19:04:19 +00003293 FuncInfo.CatchInfoLost.insert(&I);
3294#endif
Duncan Sands90291952007-07-06 09:18:59 +00003295 // FIXME: Mark exception selector register as live in. Hack for PR1508.
3296 unsigned Reg = TLI.getExceptionSelectorRegister();
3297 if (Reg) CurMBB->addLiveIn(Reg);
Evan Chenge47c3332007-06-27 18:45:32 +00003298 }
Jim Laskey735b6f82007-02-22 15:38:06 +00003299
3300 // Insert the EHSELECTION instruction.
Anton Korobeynikov8806c7b2007-09-07 11:39:35 +00003301 SDVTList VTs = DAG.getVTList(VT, MVT::Other);
Dan Gohman475871a2008-07-27 21:46:04 +00003302 SDValue Ops[2];
Jim Laskey735b6f82007-02-22 15:38:06 +00003303 Ops[0] = getValue(I.getOperand(1));
3304 Ops[1] = getRoot();
Dan Gohman475871a2008-07-27 21:46:04 +00003305 SDValue Op = DAG.getNode(ISD::EHSELECTION, VTs, Ops, 2);
Jim Laskey735b6f82007-02-22 15:38:06 +00003306 setValue(&I, Op);
3307 DAG.setRoot(Op.getValue(1));
Jim Laskey7a1de982007-02-24 09:45:44 +00003308 } else {
Anton Korobeynikov8806c7b2007-09-07 11:39:35 +00003309 setValue(&I, DAG.getConstant(0, VT));
Jim Laskey735b6f82007-02-22 15:38:06 +00003310 }
Jim Laskeyb180aa12007-02-21 22:53:45 +00003311
3312 return 0;
3313 }
Anton Korobeynikov8806c7b2007-09-07 11:39:35 +00003314
3315 case Intrinsic::eh_typeid_for_i32:
3316 case Intrinsic::eh_typeid_for_i64: {
Jim Laskeyb180aa12007-02-21 22:53:45 +00003317 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Duncan Sands83ec4b62008-06-06 12:08:01 +00003318 MVT VT = (Intrinsic == Intrinsic::eh_typeid_for_i32 ?
Anton Korobeynikov8806c7b2007-09-07 11:39:35 +00003319 MVT::i32 : MVT::i64);
Jim Laskeyb180aa12007-02-21 22:53:45 +00003320
Jim Laskey735b6f82007-02-22 15:38:06 +00003321 if (MMI) {
3322 // Find the type id for the given typeinfo.
Duncan Sandscf26d7c2007-07-04 20:52:51 +00003323 GlobalVariable *GV = ExtractTypeInfo(I.getOperand(1));
Duncan Sands3b346362007-05-04 17:12:26 +00003324
Jim Laskey735b6f82007-02-22 15:38:06 +00003325 unsigned TypeID = MMI->getTypeIDFor(GV);
Anton Korobeynikov8806c7b2007-09-07 11:39:35 +00003326 setValue(&I, DAG.getConstant(TypeID, VT));
Jim Laskey7a1de982007-02-24 09:45:44 +00003327 } else {
Duncan Sandsf664e412007-07-06 14:46:23 +00003328 // Return something different to eh_selector.
Anton Korobeynikov8806c7b2007-09-07 11:39:35 +00003329 setValue(&I, DAG.getConstant(1, VT));
Jim Laskey735b6f82007-02-22 15:38:06 +00003330 }
Jim Laskeyb180aa12007-02-21 22:53:45 +00003331
3332 return 0;
3333 }
3334
Anton Korobeynikov2365f512007-07-14 14:06:15 +00003335 case Intrinsic::eh_return: {
3336 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3337
Dale Johannesen1532f3d2008-04-02 00:25:04 +00003338 if (MMI) {
Anton Korobeynikov2365f512007-07-14 14:06:15 +00003339 MMI->setCallsEHReturn(true);
3340 DAG.setRoot(DAG.getNode(ISD::EH_RETURN,
3341 MVT::Other,
Dan Gohman86e1ebf2008-03-27 19:56:19 +00003342 getControlRoot(),
Anton Korobeynikov2365f512007-07-14 14:06:15 +00003343 getValue(I.getOperand(1)),
3344 getValue(I.getOperand(2))));
3345 } else {
3346 setValue(&I, DAG.getConstant(0, TLI.getPointerTy()));
3347 }
3348
3349 return 0;
3350 }
3351
3352 case Intrinsic::eh_unwind_init: {
3353 if (MachineModuleInfo *MMI = DAG.getMachineModuleInfo()) {
3354 MMI->setCallsUnwindInit(true);
3355 }
3356
3357 return 0;
3358 }
3359
3360 case Intrinsic::eh_dwarf_cfa: {
Duncan Sands83ec4b62008-06-06 12:08:01 +00003361 MVT VT = getValue(I.getOperand(1)).getValueType();
Dan Gohman475871a2008-07-27 21:46:04 +00003362 SDValue CfaArg;
Duncan Sands8e4eb092008-06-08 20:54:56 +00003363 if (VT.bitsGT(TLI.getPointerTy()))
Dale Johannesen1532f3d2008-04-02 00:25:04 +00003364 CfaArg = DAG.getNode(ISD::TRUNCATE,
3365 TLI.getPointerTy(), getValue(I.getOperand(1)));
3366 else
3367 CfaArg = DAG.getNode(ISD::SIGN_EXTEND,
3368 TLI.getPointerTy(), getValue(I.getOperand(1)));
Anton Korobeynikov2365f512007-07-14 14:06:15 +00003369
Dan Gohman475871a2008-07-27 21:46:04 +00003370 SDValue Offset = DAG.getNode(ISD::ADD,
Dale Johannesen1532f3d2008-04-02 00:25:04 +00003371 TLI.getPointerTy(),
3372 DAG.getNode(ISD::FRAME_TO_ARGS_OFFSET,
3373 TLI.getPointerTy()),
3374 CfaArg);
3375 setValue(&I, DAG.getNode(ISD::ADD,
3376 TLI.getPointerTy(),
3377 DAG.getNode(ISD::FRAMEADDR,
3378 TLI.getPointerTy(),
3379 DAG.getConstant(0,
3380 TLI.getPointerTy())),
3381 Offset));
Anton Korobeynikov2365f512007-07-14 14:06:15 +00003382 return 0;
3383 }
3384
Dale Johannesen9ab7fb32007-10-02 17:43:59 +00003385 case Intrinsic::sqrt:
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003386 setValue(&I, DAG.getNode(ISD::FSQRT,
3387 getValue(I.getOperand(1)).getValueType(),
3388 getValue(I.getOperand(1))));
3389 return 0;
Dale Johannesen9ab7fb32007-10-02 17:43:59 +00003390 case Intrinsic::powi:
Chris Lattner6ddf8ed2006-09-09 06:03:30 +00003391 setValue(&I, DAG.getNode(ISD::FPOWI,
3392 getValue(I.getOperand(1)).getValueType(),
3393 getValue(I.getOperand(1)),
3394 getValue(I.getOperand(2))));
3395 return 0;
Dan Gohmanac9385a2007-10-12 00:01:22 +00003396 case Intrinsic::sin:
3397 setValue(&I, DAG.getNode(ISD::FSIN,
3398 getValue(I.getOperand(1)).getValueType(),
3399 getValue(I.getOperand(1))));
3400 return 0;
3401 case Intrinsic::cos:
3402 setValue(&I, DAG.getNode(ISD::FCOS,
3403 getValue(I.getOperand(1)).getValueType(),
3404 getValue(I.getOperand(1))));
3405 return 0;
3406 case Intrinsic::pow:
3407 setValue(&I, DAG.getNode(ISD::FPOW,
3408 getValue(I.getOperand(1)).getValueType(),
3409 getValue(I.getOperand(1)),
3410 getValue(I.getOperand(2))));
3411 return 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003412 case Intrinsic::pcmarker: {
Dan Gohman475871a2008-07-27 21:46:04 +00003413 SDValue Tmp = getValue(I.getOperand(1));
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003414 DAG.setRoot(DAG.getNode(ISD::PCMARKER, MVT::Other, getRoot(), Tmp));
3415 return 0;
3416 }
Andrew Lenharth8b91c772005-11-11 22:48:54 +00003417 case Intrinsic::readcyclecounter: {
Dan Gohman475871a2008-07-27 21:46:04 +00003418 SDValue Op = getRoot();
3419 SDValue Tmp = DAG.getNode(ISD::READCYCLECOUNTER,
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00003420 DAG.getNodeValueTypes(MVT::i64, MVT::Other), 2,
3421 &Op, 1);
Andrew Lenharth8b91c772005-11-11 22:48:54 +00003422 setValue(&I, Tmp);
3423 DAG.setRoot(Tmp.getValue(1));
Andrew Lenharth51b8d542005-11-11 16:47:30 +00003424 return 0;
Andrew Lenharth8b91c772005-11-11 22:48:54 +00003425 }
Chris Lattnerc6eb6d72007-04-10 03:20:39 +00003426 case Intrinsic::part_select: {
Reid Spencer3f108cb2007-04-05 01:20:18 +00003427 // Currently not implemented: just abort
Reid Spencerf75b8742007-04-12 02:48:46 +00003428 assert(0 && "part_select intrinsic not implemented");
3429 abort();
3430 }
3431 case Intrinsic::part_set: {
3432 // Currently not implemented: just abort
3433 assert(0 && "part_set intrinsic not implemented");
Reid Spencer3f108cb2007-04-05 01:20:18 +00003434 abort();
Reid Spenceraddd11d2007-04-04 23:48:25 +00003435 }
Reid Spencera4f9c4d2007-04-01 07:34:11 +00003436 case Intrinsic::bswap:
Nate Begemand88fc032006-01-14 03:14:10 +00003437 setValue(&I, DAG.getNode(ISD::BSWAP,
3438 getValue(I.getOperand(1)).getValueType(),
3439 getValue(I.getOperand(1))));
3440 return 0;
Reid Spencera4f9c4d2007-04-01 07:34:11 +00003441 case Intrinsic::cttz: {
Dan Gohman475871a2008-07-27 21:46:04 +00003442 SDValue Arg = getValue(I.getOperand(1));
Duncan Sands83ec4b62008-06-06 12:08:01 +00003443 MVT Ty = Arg.getValueType();
Dan Gohman475871a2008-07-27 21:46:04 +00003444 SDValue result = DAG.getNode(ISD::CTTZ, Ty, Arg);
Reid Spencera4f9c4d2007-04-01 07:34:11 +00003445 setValue(&I, result);
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003446 return 0;
Reid Spencera4f9c4d2007-04-01 07:34:11 +00003447 }
3448 case Intrinsic::ctlz: {
Dan Gohman475871a2008-07-27 21:46:04 +00003449 SDValue Arg = getValue(I.getOperand(1));
Duncan Sands83ec4b62008-06-06 12:08:01 +00003450 MVT Ty = Arg.getValueType();
Dan Gohman475871a2008-07-27 21:46:04 +00003451 SDValue result = DAG.getNode(ISD::CTLZ, Ty, Arg);
Reid Spencera4f9c4d2007-04-01 07:34:11 +00003452 setValue(&I, result);
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003453 return 0;
Reid Spencera4f9c4d2007-04-01 07:34:11 +00003454 }
3455 case Intrinsic::ctpop: {
Dan Gohman475871a2008-07-27 21:46:04 +00003456 SDValue Arg = getValue(I.getOperand(1));
Duncan Sands83ec4b62008-06-06 12:08:01 +00003457 MVT Ty = Arg.getValueType();
Dan Gohman475871a2008-07-27 21:46:04 +00003458 SDValue result = DAG.getNode(ISD::CTPOP, Ty, Arg);
Reid Spencera4f9c4d2007-04-01 07:34:11 +00003459 setValue(&I, result);
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003460 return 0;
Reid Spencera4f9c4d2007-04-01 07:34:11 +00003461 }
Chris Lattner140d53c2006-01-13 02:50:02 +00003462 case Intrinsic::stacksave: {
Dan Gohman475871a2008-07-27 21:46:04 +00003463 SDValue Op = getRoot();
3464 SDValue Tmp = DAG.getNode(ISD::STACKSAVE,
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00003465 DAG.getNodeValueTypes(TLI.getPointerTy(), MVT::Other), 2, &Op, 1);
Chris Lattner140d53c2006-01-13 02:50:02 +00003466 setValue(&I, Tmp);
3467 DAG.setRoot(Tmp.getValue(1));
3468 return 0;
3469 }
Chris Lattner39a17dd2006-01-23 05:22:07 +00003470 case Intrinsic::stackrestore: {
Dan Gohman475871a2008-07-27 21:46:04 +00003471 SDValue Tmp = getValue(I.getOperand(1));
Chris Lattner39a17dd2006-01-23 05:22:07 +00003472 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, MVT::Other, getRoot(), Tmp));
Chris Lattner140d53c2006-01-13 02:50:02 +00003473 return 0;
Chris Lattner39a17dd2006-01-23 05:22:07 +00003474 }
Tanya Lattner24e5aad2007-06-15 22:26:58 +00003475 case Intrinsic::var_annotation:
3476 // Discard annotate attributes
3477 return 0;
Duncan Sands36397f52007-07-27 12:58:54 +00003478
Duncan Sands36397f52007-07-27 12:58:54 +00003479 case Intrinsic::init_trampoline: {
Anton Korobeynikov0b12ecf2008-05-07 22:54:15 +00003480 const Function *F = cast<Function>(I.getOperand(2)->stripPointerCasts());
Duncan Sands36397f52007-07-27 12:58:54 +00003481
Dan Gohman475871a2008-07-27 21:46:04 +00003482 SDValue Ops[6];
Duncan Sands36397f52007-07-27 12:58:54 +00003483 Ops[0] = getRoot();
3484 Ops[1] = getValue(I.getOperand(1));
3485 Ops[2] = getValue(I.getOperand(2));
3486 Ops[3] = getValue(I.getOperand(3));
3487 Ops[4] = DAG.getSrcValue(I.getOperand(1));
3488 Ops[5] = DAG.getSrcValue(F);
3489
Dan Gohman475871a2008-07-27 21:46:04 +00003490 SDValue Tmp = DAG.getNode(ISD::TRAMPOLINE,
Duncan Sandsf7331b32007-09-11 14:10:23 +00003491 DAG.getNodeValueTypes(TLI.getPointerTy(),
3492 MVT::Other), 2,
3493 Ops, 6);
3494
3495 setValue(&I, Tmp);
3496 DAG.setRoot(Tmp.getValue(1));
Duncan Sands36397f52007-07-27 12:58:54 +00003497 return 0;
3498 }
Gordon Henriksence224772008-01-07 01:30:38 +00003499
3500 case Intrinsic::gcroot:
Gordon Henriksen5eca0752008-08-17 18:44:35 +00003501 if (GFI) {
Gordon Henriksence224772008-01-07 01:30:38 +00003502 Value *Alloca = I.getOperand(1);
3503 Constant *TypeMap = cast<Constant>(I.getOperand(2));
3504
3505 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).Val);
Gordon Henriksen5eca0752008-08-17 18:44:35 +00003506 GFI->addStackRoot(FI->getIndex(), TypeMap);
Gordon Henriksence224772008-01-07 01:30:38 +00003507 }
3508 return 0;
3509
3510 case Intrinsic::gcread:
3511 case Intrinsic::gcwrite:
Gordon Henriksen5eca0752008-08-17 18:44:35 +00003512 assert(0 && "GC failed to lower gcread/gcwrite intrinsics!");
Gordon Henriksence224772008-01-07 01:30:38 +00003513 return 0;
3514
Anton Korobeynikov917c2a62007-11-15 23:25:33 +00003515 case Intrinsic::flt_rounds: {
Dan Gohman1a024862008-01-31 00:41:03 +00003516 setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, MVT::i32));
Anton Korobeynikov917c2a62007-11-15 23:25:33 +00003517 return 0;
3518 }
Anton Korobeynikov66fac792008-01-15 07:02:33 +00003519
3520 case Intrinsic::trap: {
3521 DAG.setRoot(DAG.getNode(ISD::TRAP, MVT::Other, getRoot()));
3522 return 0;
3523 }
Evan Cheng27b7db52008-03-08 00:58:38 +00003524 case Intrinsic::prefetch: {
Dan Gohman475871a2008-07-27 21:46:04 +00003525 SDValue Ops[4];
Evan Cheng27b7db52008-03-08 00:58:38 +00003526 Ops[0] = getRoot();
3527 Ops[1] = getValue(I.getOperand(1));
3528 Ops[2] = getValue(I.getOperand(2));
3529 Ops[3] = getValue(I.getOperand(3));
3530 DAG.setRoot(DAG.getNode(ISD::PREFETCH, MVT::Other, &Ops[0], 4));
3531 return 0;
3532 }
3533
Andrew Lenharth22c5c1b2008-02-16 01:24:58 +00003534 case Intrinsic::memory_barrier: {
Dan Gohman475871a2008-07-27 21:46:04 +00003535 SDValue Ops[6];
Andrew Lenharth22c5c1b2008-02-16 01:24:58 +00003536 Ops[0] = getRoot();
3537 for (int x = 1; x < 6; ++x)
3538 Ops[x] = getValue(I.getOperand(x));
3539
3540 DAG.setRoot(DAG.getNode(ISD::MEMBARRIER, MVT::Other, &Ops[0], 6));
3541 return 0;
3542 }
Mon P Wang28873102008-06-25 08:15:39 +00003543 case Intrinsic::atomic_cmp_swap: {
Dan Gohman475871a2008-07-27 21:46:04 +00003544 SDValue Root = getRoot();
3545 SDValue L = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, Root,
Andrew Lenharthab0b9492008-02-21 06:45:13 +00003546 getValue(I.getOperand(1)),
3547 getValue(I.getOperand(2)),
Dan Gohmanfd4418f2008-06-25 16:07:49 +00003548 getValue(I.getOperand(3)),
Mon P Wang28873102008-06-25 08:15:39 +00003549 I.getOperand(1));
Andrew Lenharthab0b9492008-02-21 06:45:13 +00003550 setValue(&I, L);
3551 DAG.setRoot(L.getValue(1));
3552 return 0;
3553 }
Mon P Wang28873102008-06-25 08:15:39 +00003554 case Intrinsic::atomic_load_add:
3555 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_ADD);
3556 case Intrinsic::atomic_load_sub:
3557 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_SUB);
Mon P Wang63307c32008-05-05 19:05:59 +00003558 case Intrinsic::atomic_load_and:
3559 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_AND);
3560 case Intrinsic::atomic_load_or:
3561 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_OR);
3562 case Intrinsic::atomic_load_xor:
3563 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_XOR);
Andrew Lenharth507a58a2008-06-14 05:48:15 +00003564 case Intrinsic::atomic_load_nand:
3565 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_NAND);
Mon P Wang63307c32008-05-05 19:05:59 +00003566 case Intrinsic::atomic_load_min:
3567 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MIN);
3568 case Intrinsic::atomic_load_max:
3569 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MAX);
3570 case Intrinsic::atomic_load_umin:
3571 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMIN);
3572 case Intrinsic::atomic_load_umax:
3573 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMAX);
3574 case Intrinsic::atomic_swap:
3575 return implVisitBinaryAtomic(I, ISD::ATOMIC_SWAP);
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003576 }
3577}
3578
3579
Dan Gohman475871a2008-07-27 21:46:04 +00003580void SelectionDAGLowering::LowerCallTo(CallSite CS, SDValue Callee,
Jim Laskey1da20a72007-02-23 21:45:01 +00003581 bool IsTailCall,
Anton Korobeynikov070280e2007-05-23 11:08:31 +00003582 MachineBasicBlock *LandingPad) {
Duncan Sands6f74b482007-12-19 09:48:52 +00003583 const PointerType *PT = cast<PointerType>(CS.getCalledValue()->getType());
Jim Laskey735b6f82007-02-22 15:38:06 +00003584 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
Anton Korobeynikov070280e2007-05-23 11:08:31 +00003585 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3586 unsigned BeginLabel = 0, EndLabel = 0;
Duncan Sands6f74b482007-12-19 09:48:52 +00003587
Jim Laskey735b6f82007-02-22 15:38:06 +00003588 TargetLowering::ArgListTy Args;
3589 TargetLowering::ArgListEntry Entry;
Duncan Sands6f74b482007-12-19 09:48:52 +00003590 Args.reserve(CS.arg_size());
3591 for (CallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
3592 i != e; ++i) {
Dan Gohman475871a2008-07-27 21:46:04 +00003593 SDValue ArgNode = getValue(*i);
Duncan Sands6f74b482007-12-19 09:48:52 +00003594 Entry.Node = ArgNode; Entry.Ty = (*i)->getType();
Duncan Sands4fee7032007-05-07 20:49:28 +00003595
Duncan Sands6f74b482007-12-19 09:48:52 +00003596 unsigned attrInd = i - CS.arg_begin() + 1;
3597 Entry.isSExt = CS.paramHasAttr(attrInd, ParamAttr::SExt);
3598 Entry.isZExt = CS.paramHasAttr(attrInd, ParamAttr::ZExt);
3599 Entry.isInReg = CS.paramHasAttr(attrInd, ParamAttr::InReg);
3600 Entry.isSRet = CS.paramHasAttr(attrInd, ParamAttr::StructRet);
3601 Entry.isNest = CS.paramHasAttr(attrInd, ParamAttr::Nest);
3602 Entry.isByVal = CS.paramHasAttr(attrInd, ParamAttr::ByVal);
Dale Johannesen08e78b12008-02-22 17:49:45 +00003603 Entry.Alignment = CS.getParamAlignment(attrInd);
Jim Laskey735b6f82007-02-22 15:38:06 +00003604 Args.push_back(Entry);
3605 }
3606
Dale Johannesen1532f3d2008-04-02 00:25:04 +00003607 if (LandingPad && MMI) {
Anton Korobeynikov070280e2007-05-23 11:08:31 +00003608 // Insert a label before the invoke call to mark the try range. This can be
3609 // used to detect deletion of the invoke via the MachineModuleInfo.
3610 BeginLabel = MMI->NextLabelID();
Dale Johannesena4091d32008-04-04 23:48:31 +00003611 // Both PendingLoads and PendingExports must be flushed here;
3612 // this call might not return.
3613 (void)getRoot();
Dan Gohman44066042008-07-01 00:05:16 +00003614 DAG.setRoot(DAG.getLabel(ISD::EH_LABEL, getControlRoot(), BeginLabel));
Anton Korobeynikov070280e2007-05-23 11:08:31 +00003615 }
Duncan Sands6f74b482007-12-19 09:48:52 +00003616
Dan Gohman475871a2008-07-27 21:46:04 +00003617 std::pair<SDValue,SDValue> Result =
Duncan Sands6f74b482007-12-19 09:48:52 +00003618 TLI.LowerCallTo(getRoot(), CS.getType(),
3619 CS.paramHasAttr(0, ParamAttr::SExt),
Duncan Sands00fee652008-02-14 17:28:50 +00003620 CS.paramHasAttr(0, ParamAttr::ZExt),
Duncan Sands6f74b482007-12-19 09:48:52 +00003621 FTy->isVarArg(), CS.getCallingConv(), IsTailCall,
Jim Laskey735b6f82007-02-22 15:38:06 +00003622 Callee, Args, DAG);
Duncan Sands6f74b482007-12-19 09:48:52 +00003623 if (CS.getType() != Type::VoidTy)
3624 setValue(CS.getInstruction(), Result.first);
Jim Laskey735b6f82007-02-22 15:38:06 +00003625 DAG.setRoot(Result.second);
Anton Korobeynikov070280e2007-05-23 11:08:31 +00003626
Dale Johannesen1532f3d2008-04-02 00:25:04 +00003627 if (LandingPad && MMI) {
Anton Korobeynikov070280e2007-05-23 11:08:31 +00003628 // Insert a label at the end of the invoke call to mark the try range. This
3629 // can be used to detect deletion of the invoke via the MachineModuleInfo.
3630 EndLabel = MMI->NextLabelID();
Dan Gohman44066042008-07-01 00:05:16 +00003631 DAG.setRoot(DAG.getLabel(ISD::EH_LABEL, getRoot(), EndLabel));
Anton Korobeynikov070280e2007-05-23 11:08:31 +00003632
Duncan Sands6f74b482007-12-19 09:48:52 +00003633 // Inform MachineModuleInfo of range.
Anton Korobeynikov070280e2007-05-23 11:08:31 +00003634 MMI->addInvoke(LandingPad, BeginLabel, EndLabel);
3635 }
Jim Laskey735b6f82007-02-22 15:38:06 +00003636}
3637
3638
Chris Lattner1c08c712005-01-07 07:47:53 +00003639void SelectionDAGLowering::visitCall(CallInst &I) {
Chris Lattner64e14b12005-01-08 22:48:57 +00003640 const char *RenameFn = 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003641 if (Function *F = I.getCalledFunction()) {
Chris Lattner87b51bc2007-09-10 21:15:22 +00003642 if (F->isDeclaration()) {
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003643 if (unsigned IID = F->getIntrinsicID()) {
3644 RenameFn = visitIntrinsicCall(I, IID);
3645 if (!RenameFn)
3646 return;
Chris Lattner87b51bc2007-09-10 21:15:22 +00003647 }
3648 }
3649
3650 // Check for well-known libc/libm calls. If the function is internal, it
3651 // can't be a library call.
3652 unsigned NameLen = F->getNameLen();
3653 if (!F->hasInternalLinkage() && NameLen) {
3654 const char *NameStr = F->getNameStart();
3655 if (NameStr[0] == 'c' &&
3656 ((NameLen == 8 && !strcmp(NameStr, "copysign")) ||
3657 (NameLen == 9 && !strcmp(NameStr, "copysignf")))) {
3658 if (I.getNumOperands() == 3 && // Basic sanity checks.
3659 I.getOperand(1)->getType()->isFloatingPoint() &&
3660 I.getType() == I.getOperand(1)->getType() &&
3661 I.getType() == I.getOperand(2)->getType()) {
Dan Gohman475871a2008-07-27 21:46:04 +00003662 SDValue LHS = getValue(I.getOperand(1));
3663 SDValue RHS = getValue(I.getOperand(2));
Chris Lattner87b51bc2007-09-10 21:15:22 +00003664 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, LHS.getValueType(),
3665 LHS, RHS));
3666 return;
3667 }
3668 } else if (NameStr[0] == 'f' &&
3669 ((NameLen == 4 && !strcmp(NameStr, "fabs")) ||
Dale Johannesen2f429012007-09-26 21:10:55 +00003670 (NameLen == 5 && !strcmp(NameStr, "fabsf")) ||
3671 (NameLen == 5 && !strcmp(NameStr, "fabsl")))) {
Chris Lattner87b51bc2007-09-10 21:15:22 +00003672 if (I.getNumOperands() == 2 && // Basic sanity checks.
3673 I.getOperand(1)->getType()->isFloatingPoint() &&
3674 I.getType() == I.getOperand(1)->getType()) {
Dan Gohman475871a2008-07-27 21:46:04 +00003675 SDValue Tmp = getValue(I.getOperand(1));
Chris Lattner87b51bc2007-09-10 21:15:22 +00003676 setValue(&I, DAG.getNode(ISD::FABS, Tmp.getValueType(), Tmp));
3677 return;
3678 }
3679 } else if (NameStr[0] == 's' &&
3680 ((NameLen == 3 && !strcmp(NameStr, "sin")) ||
Dale Johannesen2f429012007-09-26 21:10:55 +00003681 (NameLen == 4 && !strcmp(NameStr, "sinf")) ||
3682 (NameLen == 4 && !strcmp(NameStr, "sinl")))) {
Chris Lattner87b51bc2007-09-10 21:15:22 +00003683 if (I.getNumOperands() == 2 && // Basic sanity checks.
3684 I.getOperand(1)->getType()->isFloatingPoint() &&
3685 I.getType() == I.getOperand(1)->getType()) {
Dan Gohman475871a2008-07-27 21:46:04 +00003686 SDValue Tmp = getValue(I.getOperand(1));
Chris Lattner87b51bc2007-09-10 21:15:22 +00003687 setValue(&I, DAG.getNode(ISD::FSIN, Tmp.getValueType(), Tmp));
3688 return;
3689 }
3690 } else if (NameStr[0] == 'c' &&
3691 ((NameLen == 3 && !strcmp(NameStr, "cos")) ||
Dale Johannesen2f429012007-09-26 21:10:55 +00003692 (NameLen == 4 && !strcmp(NameStr, "cosf")) ||
3693 (NameLen == 4 && !strcmp(NameStr, "cosl")))) {
Chris Lattner87b51bc2007-09-10 21:15:22 +00003694 if (I.getNumOperands() == 2 && // Basic sanity checks.
3695 I.getOperand(1)->getType()->isFloatingPoint() &&
3696 I.getType() == I.getOperand(1)->getType()) {
Dan Gohman475871a2008-07-27 21:46:04 +00003697 SDValue Tmp = getValue(I.getOperand(1));
Chris Lattner87b51bc2007-09-10 21:15:22 +00003698 setValue(&I, DAG.getNode(ISD::FCOS, Tmp.getValueType(), Tmp));
3699 return;
Chris Lattnerf76e7dc2005-04-30 04:43:14 +00003700 }
Chris Lattner1ca85d52005-05-14 13:56:55 +00003701 }
Chris Lattner87b51bc2007-09-10 21:15:22 +00003702 }
Chris Lattnerce7518c2006-01-26 22:24:51 +00003703 } else if (isa<InlineAsm>(I.getOperand(0))) {
Duncan Sandsfd7b3262007-12-17 18:08:19 +00003704 visitInlineAsm(&I);
Chris Lattnerce7518c2006-01-26 22:24:51 +00003705 return;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003706 }
Misha Brukmanedf128a2005-04-21 22:36:52 +00003707
Dan Gohman475871a2008-07-27 21:46:04 +00003708 SDValue Callee;
Chris Lattner64e14b12005-01-08 22:48:57 +00003709 if (!RenameFn)
3710 Callee = getValue(I.getOperand(0));
3711 else
3712 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
Anton Korobeynikov070280e2007-05-23 11:08:31 +00003713
Duncan Sands6f74b482007-12-19 09:48:52 +00003714 LowerCallTo(&I, Callee, I.isTailCall());
Chris Lattner1c08c712005-01-07 07:47:53 +00003715}
3716
Jim Laskey735b6f82007-02-22 15:38:06 +00003717
Dan Gohmanb6f5b002007-06-28 23:29:44 +00003718/// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
3719/// this value and returns the result as a ValueVT value. This uses
3720/// Chain/Flag as the input and updates them for the output Chain/Flag.
3721/// If the Flag pointer is NULL, no flag is used.
Dan Gohman475871a2008-07-27 21:46:04 +00003722SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
3723 SDValue &Chain,
3724 SDValue *Flag) const {
Dan Gohman23ce5022008-04-25 18:27:55 +00003725 // Assemble the legal parts into the final values.
Dan Gohman475871a2008-07-27 21:46:04 +00003726 SmallVector<SDValue, 4> Values(ValueVTs.size());
3727 SmallVector<SDValue, 8> Parts;
Chris Lattner6833b062008-04-28 07:16:35 +00003728 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
Dan Gohman23ce5022008-04-25 18:27:55 +00003729 // Copy the legal parts from the registers.
Duncan Sands83ec4b62008-06-06 12:08:01 +00003730 MVT ValueVT = ValueVTs[Value];
Dan Gohman23ce5022008-04-25 18:27:55 +00003731 unsigned NumRegs = TLI->getNumRegisters(ValueVT);
Duncan Sands83ec4b62008-06-06 12:08:01 +00003732 MVT RegisterVT = RegVTs[Value];
Dan Gohman23ce5022008-04-25 18:27:55 +00003733
Chris Lattner6833b062008-04-28 07:16:35 +00003734 Parts.resize(NumRegs);
Dan Gohman23ce5022008-04-25 18:27:55 +00003735 for (unsigned i = 0; i != NumRegs; ++i) {
Dan Gohman475871a2008-07-27 21:46:04 +00003736 SDValue P;
Chris Lattner6833b062008-04-28 07:16:35 +00003737 if (Flag == 0)
3738 P = DAG.getCopyFromReg(Chain, Regs[Part+i], RegisterVT);
3739 else {
3740 P = DAG.getCopyFromReg(Chain, Regs[Part+i], RegisterVT, *Flag);
Dan Gohman23ce5022008-04-25 18:27:55 +00003741 *Flag = P.getValue(2);
Chris Lattner6833b062008-04-28 07:16:35 +00003742 }
3743 Chain = P.getValue(1);
Chris Lattneread0d882008-06-17 06:09:18 +00003744
3745 // If the source register was virtual and if we know something about it,
3746 // add an assert node.
3747 if (TargetRegisterInfo::isVirtualRegister(Regs[Part+i]) &&
3748 RegisterVT.isInteger() && !RegisterVT.isVector()) {
3749 unsigned SlotNo = Regs[Part+i]-TargetRegisterInfo::FirstVirtualRegister;
3750 FunctionLoweringInfo &FLI = DAG.getFunctionLoweringInfo();
3751 if (FLI.LiveOutRegInfo.size() > SlotNo) {
3752 FunctionLoweringInfo::LiveOutInfo &LOI = FLI.LiveOutRegInfo[SlotNo];
3753
3754 unsigned RegSize = RegisterVT.getSizeInBits();
3755 unsigned NumSignBits = LOI.NumSignBits;
3756 unsigned NumZeroBits = LOI.KnownZero.countLeadingOnes();
3757
3758 // FIXME: We capture more information than the dag can represent. For
3759 // now, just use the tightest assertzext/assertsext possible.
3760 bool isSExt = true;
3761 MVT FromVT(MVT::Other);
3762 if (NumSignBits == RegSize)
3763 isSExt = true, FromVT = MVT::i1; // ASSERT SEXT 1
3764 else if (NumZeroBits >= RegSize-1)
3765 isSExt = false, FromVT = MVT::i1; // ASSERT ZEXT 1
3766 else if (NumSignBits > RegSize-8)
3767 isSExt = true, FromVT = MVT::i8; // ASSERT SEXT 8
3768 else if (NumZeroBits >= RegSize-9)
3769 isSExt = false, FromVT = MVT::i8; // ASSERT ZEXT 8
3770 else if (NumSignBits > RegSize-16)
3771 isSExt = true, FromVT = MVT::i16; // ASSERT SEXT 16
3772 else if (NumZeroBits >= RegSize-17)
3773 isSExt = false, FromVT = MVT::i16; // ASSERT ZEXT 16
3774 else if (NumSignBits > RegSize-32)
3775 isSExt = true, FromVT = MVT::i32; // ASSERT SEXT 32
3776 else if (NumZeroBits >= RegSize-33)
3777 isSExt = false, FromVT = MVT::i32; // ASSERT ZEXT 32
3778
3779 if (FromVT != MVT::Other) {
3780 P = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext,
3781 RegisterVT, P, DAG.getValueType(FromVT));
3782
3783 }
3784 }
3785 }
3786
Dan Gohman23ce5022008-04-25 18:27:55 +00003787 Parts[Part+i] = P;
3788 }
Chris Lattner5df99b32007-03-25 05:00:54 +00003789
Dan Gohman23ce5022008-04-25 18:27:55 +00003790 Values[Value] = getCopyFromParts(DAG, &Parts[Part], NumRegs, RegisterVT,
3791 ValueVT);
3792 Part += NumRegs;
3793 }
Duncan Sands4bdcb612008-07-02 17:40:58 +00003794
Duncan Sandsf9516202008-06-30 10:19:09 +00003795 return DAG.getMergeValues(DAG.getVTList(&ValueVTs[0], ValueVTs.size()),
3796 &Values[0], ValueVTs.size());
Chris Lattner864635a2006-02-22 22:37:12 +00003797}
3798
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00003799/// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
3800/// specified value into the registers specified by this object. This uses
3801/// Chain/Flag as the input and updates them for the output Chain/Flag.
Dan Gohmanb6f5b002007-06-28 23:29:44 +00003802/// If the Flag pointer is NULL, no flag is used.
Dan Gohman475871a2008-07-27 21:46:04 +00003803void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG,
3804 SDValue &Chain, SDValue *Flag) const {
Dan Gohmanb6f5b002007-06-28 23:29:44 +00003805 // Get the list of the values's legal parts.
Dan Gohman23ce5022008-04-25 18:27:55 +00003806 unsigned NumRegs = Regs.size();
Dan Gohman475871a2008-07-27 21:46:04 +00003807 SmallVector<SDValue, 8> Parts(NumRegs);
Chris Lattner6833b062008-04-28 07:16:35 +00003808 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
Duncan Sands83ec4b62008-06-06 12:08:01 +00003809 MVT ValueVT = ValueVTs[Value];
Dan Gohman23ce5022008-04-25 18:27:55 +00003810 unsigned NumParts = TLI->getNumRegisters(ValueVT);
Duncan Sands83ec4b62008-06-06 12:08:01 +00003811 MVT RegisterVT = RegVTs[Value];
Dan Gohman23ce5022008-04-25 18:27:55 +00003812
3813 getCopyToParts(DAG, Val.getValue(Val.ResNo + Value),
3814 &Parts[Part], NumParts, RegisterVT);
3815 Part += NumParts;
3816 }
Dan Gohmanb6f5b002007-06-28 23:29:44 +00003817
3818 // Copy the parts into the registers.
Dan Gohman475871a2008-07-27 21:46:04 +00003819 SmallVector<SDValue, 8> Chains(NumRegs);
Dan Gohman23ce5022008-04-25 18:27:55 +00003820 for (unsigned i = 0; i != NumRegs; ++i) {
Dan Gohman475871a2008-07-27 21:46:04 +00003821 SDValue Part;
Chris Lattner6833b062008-04-28 07:16:35 +00003822 if (Flag == 0)
3823 Part = DAG.getCopyToReg(Chain, Regs[i], Parts[i]);
3824 else {
3825 Part = DAG.getCopyToReg(Chain, Regs[i], Parts[i], *Flag);
Dan Gohmanb6f5b002007-06-28 23:29:44 +00003826 *Flag = Part.getValue(1);
Chris Lattner6833b062008-04-28 07:16:35 +00003827 }
3828 Chains[i] = Part.getValue(0);
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00003829 }
Chris Lattner6833b062008-04-28 07:16:35 +00003830
Evan Cheng33bf38a2008-04-28 22:07:13 +00003831 if (NumRegs == 1 || Flag)
3832 // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is
3833 // flagged to it. That is the CopyToReg nodes and the user are considered
3834 // a single scheduling unit. If we create a TokenFactor and return it as
3835 // chain, then the TokenFactor is both a predecessor (operand) of the
3836 // user as well as a successor (the TF operands are flagged to the user).
3837 // c1, f1 = CopyToReg
3838 // c2, f2 = CopyToReg
3839 // c3 = TokenFactor c1, c2
3840 // ...
3841 // = op c3, ..., f2
3842 Chain = Chains[NumRegs-1];
Chris Lattner6833b062008-04-28 07:16:35 +00003843 else
3844 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other, &Chains[0], NumRegs);
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00003845}
Chris Lattner864635a2006-02-22 22:37:12 +00003846
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00003847/// AddInlineAsmOperands - Add this value to the specified inlineasm node
3848/// operand list. This adds the code marker and includes the number of
3849/// values added into it.
3850void RegsForValue::AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
Dan Gohman475871a2008-07-27 21:46:04 +00003851 std::vector<SDValue> &Ops) const {
Duncan Sands83ec4b62008-06-06 12:08:01 +00003852 MVT IntPtrTy = DAG.getTargetLoweringInfo().getPointerTy();
Chris Lattner4b993b12007-04-09 00:33:58 +00003853 Ops.push_back(DAG.getTargetConstant(Code | (Regs.size() << 3), IntPtrTy));
Chris Lattner6833b062008-04-28 07:16:35 +00003854 for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
3855 unsigned NumRegs = TLI->getNumRegisters(ValueVTs[Value]);
Duncan Sands83ec4b62008-06-06 12:08:01 +00003856 MVT RegisterVT = RegVTs[Value];
Chris Lattner6833b062008-04-28 07:16:35 +00003857 for (unsigned i = 0; i != NumRegs; ++i)
3858 Ops.push_back(DAG.getRegister(Regs[Reg++], RegisterVT));
Dan Gohman23ce5022008-04-25 18:27:55 +00003859 }
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00003860}
Chris Lattner864635a2006-02-22 22:37:12 +00003861
3862/// isAllocatableRegister - If the specified register is safe to allocate,
3863/// i.e. it isn't a stack pointer or some other special register, return the
3864/// register class for the register. Otherwise, return null.
3865static const TargetRegisterClass *
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00003866isAllocatableRegister(unsigned Reg, MachineFunction &MF,
Dan Gohman6f0d0242008-02-10 18:45:23 +00003867 const TargetLowering &TLI,
3868 const TargetRegisterInfo *TRI) {
Duncan Sands83ec4b62008-06-06 12:08:01 +00003869 MVT FoundVT = MVT::Other;
Chris Lattnerf8814cf2006-04-02 00:24:45 +00003870 const TargetRegisterClass *FoundRC = 0;
Dan Gohman6f0d0242008-02-10 18:45:23 +00003871 for (TargetRegisterInfo::regclass_iterator RCI = TRI->regclass_begin(),
3872 E = TRI->regclass_end(); RCI != E; ++RCI) {
Duncan Sands83ec4b62008-06-06 12:08:01 +00003873 MVT ThisVT = MVT::Other;
Chris Lattnerf8814cf2006-04-02 00:24:45 +00003874
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00003875 const TargetRegisterClass *RC = *RCI;
3876 // If none of the the value types for this register class are valid, we
3877 // can't use it. For example, 64-bit reg classes on 32-bit targets.
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00003878 for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
3879 I != E; ++I) {
3880 if (TLI.isTypeLegal(*I)) {
Chris Lattnerf8814cf2006-04-02 00:24:45 +00003881 // If we have already found this register in a different register class,
3882 // choose the one with the largest VT specified. For example, on
3883 // PowerPC, we favor f64 register classes over f32.
Duncan Sands8e4eb092008-06-08 20:54:56 +00003884 if (FoundVT == MVT::Other || FoundVT.bitsLT(*I)) {
Chris Lattnerf8814cf2006-04-02 00:24:45 +00003885 ThisVT = *I;
3886 break;
3887 }
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00003888 }
3889 }
3890
Chris Lattnerf8814cf2006-04-02 00:24:45 +00003891 if (ThisVT == MVT::Other) continue;
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00003892
Chris Lattner864635a2006-02-22 22:37:12 +00003893 // NOTE: This isn't ideal. In particular, this might allocate the
3894 // frame pointer in functions that need it (due to them not being taken
3895 // out of allocation, because a variable sized allocation hasn't been seen
3896 // yet). This is a slight code pessimization, but should still work.
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00003897 for (TargetRegisterClass::iterator I = RC->allocation_order_begin(MF),
3898 E = RC->allocation_order_end(MF); I != E; ++I)
Chris Lattnerf8814cf2006-04-02 00:24:45 +00003899 if (*I == Reg) {
3900 // We found a matching register class. Keep looking at others in case
3901 // we find one with larger registers that this physreg is also in.
3902 FoundRC = RC;
3903 FoundVT = ThisVT;
3904 break;
3905 }
Chris Lattner4e4b5762006-02-01 18:59:47 +00003906 }
Chris Lattnerf8814cf2006-04-02 00:24:45 +00003907 return FoundRC;
Chris Lattner864635a2006-02-22 22:37:12 +00003908}
3909
Chris Lattner4e4b5762006-02-01 18:59:47 +00003910
Chris Lattner0c583402007-04-28 20:49:53 +00003911namespace {
3912/// AsmOperandInfo - This contains information for each constraint that we are
3913/// lowering.
Evan Cheng5c807602008-02-26 02:33:44 +00003914struct SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo {
3915 /// CallOperand - If this is the result output operand or a clobber
3916 /// this is null, otherwise it is the incoming operand to the CallInst.
3917 /// This gets modified as the asm is processed.
Dan Gohman475871a2008-07-27 21:46:04 +00003918 SDValue CallOperand;
Evan Cheng5c807602008-02-26 02:33:44 +00003919
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003920 /// AssignedRegs - If this is a register or register class operand, this
3921 /// contains the set of register corresponding to the operand.
3922 RegsForValue AssignedRegs;
3923
Dan Gohman23ce5022008-04-25 18:27:55 +00003924 explicit SDISelAsmOperandInfo(const InlineAsm::ConstraintInfo &info)
Evan Cheng5c807602008-02-26 02:33:44 +00003925 : TargetLowering::AsmOperandInfo(info), CallOperand(0,0) {
Chris Lattner0c583402007-04-28 20:49:53 +00003926 }
Chris Lattner3ff90dc2007-04-30 17:16:27 +00003927
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003928 /// MarkAllocatedRegs - Once AssignedRegs is set, mark the assigned registers
3929 /// busy in OutputRegs/InputRegs.
3930 void MarkAllocatedRegs(bool isOutReg, bool isInReg,
3931 std::set<unsigned> &OutputRegs,
Chris Lattner7cbeb242008-02-21 04:55:52 +00003932 std::set<unsigned> &InputRegs,
3933 const TargetRegisterInfo &TRI) const {
3934 if (isOutReg) {
3935 for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i)
3936 MarkRegAndAliases(AssignedRegs.Regs[i], OutputRegs, TRI);
3937 }
3938 if (isInReg) {
3939 for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i)
3940 MarkRegAndAliases(AssignedRegs.Regs[i], InputRegs, TRI);
3941 }
3942 }
3943
3944private:
3945 /// MarkRegAndAliases - Mark the specified register and all aliases in the
3946 /// specified set.
3947 static void MarkRegAndAliases(unsigned Reg, std::set<unsigned> &Regs,
3948 const TargetRegisterInfo &TRI) {
3949 assert(TargetRegisterInfo::isPhysicalRegister(Reg) && "Isn't a physreg");
3950 Regs.insert(Reg);
3951 if (const unsigned *Aliases = TRI.getAliasSet(Reg))
3952 for (; *Aliases; ++Aliases)
3953 Regs.insert(*Aliases);
3954 }
Chris Lattner0c583402007-04-28 20:49:53 +00003955};
3956} // end anon namespace.
Chris Lattner864635a2006-02-22 22:37:12 +00003957
Chris Lattner3ff90dc2007-04-30 17:16:27 +00003958
Chris Lattner0fe71e92008-02-21 19:43:13 +00003959/// GetRegistersForValue - Assign registers (virtual or physical) for the
3960/// specified operand. We prefer to assign virtual registers, to allow the
3961/// register allocator handle the assignment process. However, if the asm uses
3962/// features that we can't model on machineinstrs, we have SDISel do the
3963/// allocation. This produces generally horrible, but correct, code.
3964///
3965/// OpInfo describes the operand.
3966/// HasEarlyClobber is true if there are any early clobber constraints (=&r)
3967/// or any explicitly clobbered registers.
3968/// Input and OutputRegs are the set of already allocated physical registers.
3969///
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003970void SelectionDAGLowering::
Evan Cheng5c807602008-02-26 02:33:44 +00003971GetRegistersForValue(SDISelAsmOperandInfo &OpInfo, bool HasEarlyClobber,
Chris Lattnerbf996f12007-04-30 17:29:31 +00003972 std::set<unsigned> &OutputRegs,
3973 std::set<unsigned> &InputRegs) {
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003974 // Compute whether this value requires an input register, an output register,
3975 // or both.
3976 bool isOutReg = false;
3977 bool isInReg = false;
3978 switch (OpInfo.Type) {
3979 case InlineAsm::isOutput:
3980 isOutReg = true;
3981
3982 // If this is an early-clobber output, or if there is an input
3983 // constraint that matches this, we need to reserve the input register
3984 // so no other inputs allocate to it.
3985 isInReg = OpInfo.isEarlyClobber || OpInfo.hasMatchingInput;
3986 break;
3987 case InlineAsm::isInput:
3988 isInReg = true;
3989 isOutReg = false;
3990 break;
3991 case InlineAsm::isClobber:
3992 isOutReg = true;
3993 isInReg = true;
3994 break;
3995 }
3996
3997
3998 MachineFunction &MF = DAG.getMachineFunction();
Chris Lattnerb606dba2008-04-28 06:44:42 +00003999 SmallVector<unsigned, 4> Regs;
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004000
4001 // If this is a constraint for a single physreg, or a constraint for a
4002 // register class, find it.
4003 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
4004 TLI.getRegForInlineAsmConstraint(OpInfo.ConstraintCode,
4005 OpInfo.ConstraintVT);
Chris Lattnerbf996f12007-04-30 17:29:31 +00004006
4007 unsigned NumRegs = 1;
4008 if (OpInfo.ConstraintVT != MVT::Other)
Dan Gohmanb9f10192007-06-21 14:42:22 +00004009 NumRegs = TLI.getNumRegisters(OpInfo.ConstraintVT);
Duncan Sands83ec4b62008-06-06 12:08:01 +00004010 MVT RegVT;
4011 MVT ValueVT = OpInfo.ConstraintVT;
Chris Lattnerbf996f12007-04-30 17:29:31 +00004012
Chris Lattnerbf996f12007-04-30 17:29:31 +00004013
4014 // If this is a constraint for a specific physical register, like {r17},
4015 // assign it now.
4016 if (PhysReg.first) {
4017 if (OpInfo.ConstraintVT == MVT::Other)
4018 ValueVT = *PhysReg.second->vt_begin();
4019
4020 // Get the actual register value type. This is important, because the user
4021 // may have asked for (e.g.) the AX register in i32 type. We need to
4022 // remember that AX is actually i16 to get the right extension.
4023 RegVT = *PhysReg.second->vt_begin();
4024
4025 // This is a explicit reference to a physical register.
4026 Regs.push_back(PhysReg.first);
4027
4028 // If this is an expanded reference, add the rest of the regs to Regs.
4029 if (NumRegs != 1) {
4030 TargetRegisterClass::iterator I = PhysReg.second->begin();
Chris Lattnerbf996f12007-04-30 17:29:31 +00004031 for (; *I != PhysReg.first; ++I)
Evan Cheng50871242008-05-14 20:07:51 +00004032 assert(I != PhysReg.second->end() && "Didn't find reg!");
Chris Lattnerbf996f12007-04-30 17:29:31 +00004033
4034 // Already added the first reg.
4035 --NumRegs; ++I;
4036 for (; NumRegs; --NumRegs, ++I) {
Evan Cheng50871242008-05-14 20:07:51 +00004037 assert(I != PhysReg.second->end() && "Ran out of registers to allocate!");
Chris Lattnerbf996f12007-04-30 17:29:31 +00004038 Regs.push_back(*I);
4039 }
4040 }
Dan Gohman23ce5022008-04-25 18:27:55 +00004041 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, RegVT, ValueVT);
Chris Lattner7cbeb242008-02-21 04:55:52 +00004042 const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
4043 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TRI);
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004044 return;
Chris Lattnerbf996f12007-04-30 17:29:31 +00004045 }
4046
4047 // Otherwise, if this was a reference to an LLVM register class, create vregs
4048 // for this reference.
4049 std::vector<unsigned> RegClassRegs;
Chris Lattnerc2c28fc2007-06-15 19:11:01 +00004050 const TargetRegisterClass *RC = PhysReg.second;
4051 if (RC) {
Chris Lattnerbf996f12007-04-30 17:29:31 +00004052 // If this is an early clobber or tied register, our regalloc doesn't know
4053 // how to maintain the constraint. If it isn't, go ahead and create vreg
4054 // and let the regalloc do the right thing.
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004055 if (!OpInfo.hasMatchingInput && !OpInfo.isEarlyClobber &&
4056 // If there is some other early clobber and this is an input register,
4057 // then we are forced to pre-allocate the input reg so it doesn't
4058 // conflict with the earlyclobber.
4059 !(OpInfo.Type == InlineAsm::isInput && HasEarlyClobber)) {
Chris Lattnerbf996f12007-04-30 17:29:31 +00004060 RegVT = *PhysReg.second->vt_begin();
4061
4062 if (OpInfo.ConstraintVT == MVT::Other)
4063 ValueVT = RegVT;
4064
4065 // Create the appropriate number of virtual registers.
Chris Lattner84bc5422007-12-31 04:13:23 +00004066 MachineRegisterInfo &RegInfo = MF.getRegInfo();
Chris Lattnerbf996f12007-04-30 17:29:31 +00004067 for (; NumRegs; --NumRegs)
Chris Lattner84bc5422007-12-31 04:13:23 +00004068 Regs.push_back(RegInfo.createVirtualRegister(PhysReg.second));
Chris Lattnerbf996f12007-04-30 17:29:31 +00004069
Dan Gohman23ce5022008-04-25 18:27:55 +00004070 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, RegVT, ValueVT);
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004071 return;
Chris Lattnerbf996f12007-04-30 17:29:31 +00004072 }
4073
4074 // Otherwise, we can't allocate it. Let the code below figure out how to
4075 // maintain these constraints.
4076 RegClassRegs.assign(PhysReg.second->begin(), PhysReg.second->end());
4077
4078 } else {
4079 // This is a reference to a register class that doesn't directly correspond
4080 // to an LLVM register class. Allocate NumRegs consecutive, available,
4081 // registers from the class.
4082 RegClassRegs = TLI.getRegClassForInlineAsmConstraint(OpInfo.ConstraintCode,
4083 OpInfo.ConstraintVT);
4084 }
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004085
Dan Gohman6f0d0242008-02-10 18:45:23 +00004086 const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
Chris Lattnerbf996f12007-04-30 17:29:31 +00004087 unsigned NumAllocated = 0;
4088 for (unsigned i = 0, e = RegClassRegs.size(); i != e; ++i) {
4089 unsigned Reg = RegClassRegs[i];
4090 // See if this register is available.
4091 if ((isOutReg && OutputRegs.count(Reg)) || // Already used.
4092 (isInReg && InputRegs.count(Reg))) { // Already used.
4093 // Make sure we find consecutive registers.
4094 NumAllocated = 0;
4095 continue;
4096 }
4097
4098 // Check to see if this register is allocatable (i.e. don't give out the
4099 // stack pointer).
Chris Lattnerc2c28fc2007-06-15 19:11:01 +00004100 if (RC == 0) {
Dan Gohman6f0d0242008-02-10 18:45:23 +00004101 RC = isAllocatableRegister(Reg, MF, TLI, TRI);
Chris Lattnerc2c28fc2007-06-15 19:11:01 +00004102 if (!RC) { // Couldn't allocate this register.
4103 // Reset NumAllocated to make sure we return consecutive registers.
4104 NumAllocated = 0;
4105 continue;
4106 }
Chris Lattnerbf996f12007-04-30 17:29:31 +00004107 }
4108
4109 // Okay, this register is good, we can use it.
4110 ++NumAllocated;
4111
4112 // If we allocated enough consecutive registers, succeed.
4113 if (NumAllocated == NumRegs) {
4114 unsigned RegStart = (i-NumAllocated)+1;
4115 unsigned RegEnd = i+1;
4116 // Mark all of the allocated registers used.
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004117 for (unsigned i = RegStart; i != RegEnd; ++i)
4118 Regs.push_back(RegClassRegs[i]);
Chris Lattnerbf996f12007-04-30 17:29:31 +00004119
Dan Gohman23ce5022008-04-25 18:27:55 +00004120 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, *RC->vt_begin(),
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004121 OpInfo.ConstraintVT);
Chris Lattner7cbeb242008-02-21 04:55:52 +00004122 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TRI);
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004123 return;
Chris Lattnerbf996f12007-04-30 17:29:31 +00004124 }
4125 }
4126
4127 // Otherwise, we couldn't allocate enough registers for this.
Chris Lattnerbf996f12007-04-30 17:29:31 +00004128}
4129
4130
Chris Lattnerce7518c2006-01-26 22:24:51 +00004131/// visitInlineAsm - Handle a call to an InlineAsm object.
4132///
Duncan Sandsfd7b3262007-12-17 18:08:19 +00004133void SelectionDAGLowering::visitInlineAsm(CallSite CS) {
4134 InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
Chris Lattnerce7518c2006-01-26 22:24:51 +00004135
Chris Lattner0c583402007-04-28 20:49:53 +00004136 /// ConstraintOperands - Information about all of the constraints.
Evan Cheng5c807602008-02-26 02:33:44 +00004137 std::vector<SDISelAsmOperandInfo> ConstraintOperands;
Chris Lattnerce7518c2006-01-26 22:24:51 +00004138
Dan Gohman475871a2008-07-27 21:46:04 +00004139 SDValue Chain = getRoot();
4140 SDValue Flag;
Chris Lattnerce7518c2006-01-26 22:24:51 +00004141
Chris Lattner4e4b5762006-02-01 18:59:47 +00004142 std::set<unsigned> OutputRegs, InputRegs;
Chris Lattner1efa40f2006-02-22 00:56:39 +00004143
Chris Lattner0c583402007-04-28 20:49:53 +00004144 // Do a prepass over the constraints, canonicalizing them, and building up the
4145 // ConstraintOperands list.
4146 std::vector<InlineAsm::ConstraintInfo>
4147 ConstraintInfos = IA->ParseConstraints();
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004148
4149 // SawEarlyClobber - Keep track of whether we saw an earlyclobber output
4150 // constraint. If so, we can't let the register allocator allocate any input
4151 // registers, because it will not know to avoid the earlyclobbered output reg.
4152 bool SawEarlyClobber = false;
4153
Duncan Sandsfd7b3262007-12-17 18:08:19 +00004154 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst.
Chris Lattneracf8b012008-04-27 23:44:28 +00004155 unsigned ResNo = 0; // ResNo - The result number of the next output.
Chris Lattner0c583402007-04-28 20:49:53 +00004156 for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) {
Evan Cheng5c807602008-02-26 02:33:44 +00004157 ConstraintOperands.push_back(SDISelAsmOperandInfo(ConstraintInfos[i]));
4158 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
Chris Lattner0c583402007-04-28 20:49:53 +00004159
Duncan Sands83ec4b62008-06-06 12:08:01 +00004160 MVT OpVT = MVT::Other;
Chris Lattner0c583402007-04-28 20:49:53 +00004161
4162 // Compute the value type for each operand.
4163 switch (OpInfo.Type) {
Chris Lattner1efa40f2006-02-22 00:56:39 +00004164 case InlineAsm::isOutput:
Chris Lattneracf8b012008-04-27 23:44:28 +00004165 // Indirect outputs just consume an argument.
4166 if (OpInfo.isIndirect) {
Duncan Sandsfd7b3262007-12-17 18:08:19 +00004167 OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
Chris Lattneracf8b012008-04-27 23:44:28 +00004168 break;
Chris Lattner1efa40f2006-02-22 00:56:39 +00004169 }
Chris Lattneracf8b012008-04-27 23:44:28 +00004170 // The return value of the call is this value. As such, there is no
4171 // corresponding argument.
4172 assert(CS.getType() != Type::VoidTy && "Bad inline asm!");
4173 if (const StructType *STy = dyn_cast<StructType>(CS.getType())) {
4174 OpVT = TLI.getValueType(STy->getElementType(ResNo));
4175 } else {
4176 assert(ResNo == 0 && "Asm only has one result!");
4177 OpVT = TLI.getValueType(CS.getType());
4178 }
4179 ++ResNo;
Chris Lattner1efa40f2006-02-22 00:56:39 +00004180 break;
4181 case InlineAsm::isInput:
Duncan Sandsfd7b3262007-12-17 18:08:19 +00004182 OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
Chris Lattner1efa40f2006-02-22 00:56:39 +00004183 break;
4184 case InlineAsm::isClobber:
Chris Lattner0c583402007-04-28 20:49:53 +00004185 // Nothing to do.
Chris Lattner1efa40f2006-02-22 00:56:39 +00004186 break;
4187 }
Chris Lattner1efa40f2006-02-22 00:56:39 +00004188
Chris Lattner0c583402007-04-28 20:49:53 +00004189 // If this is an input or an indirect output, process the call argument.
Dale Johanneseneb57ea72007-11-05 21:20:28 +00004190 // BasicBlocks are labels, currently appearing only in asm's.
Chris Lattner0c583402007-04-28 20:49:53 +00004191 if (OpInfo.CallOperandVal) {
Chris Lattner507ffd22008-04-27 00:16:18 +00004192 if (BasicBlock *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal))
4193 OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
Dale Johanneseneb57ea72007-11-05 21:20:28 +00004194 else {
4195 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
4196 const Type *OpTy = OpInfo.CallOperandVal->getType();
4197 // If this is an indirect operand, the operand is a pointer to the
4198 // accessed type.
4199 if (OpInfo.isIndirect)
4200 OpTy = cast<PointerType>(OpTy)->getElementType();
4201
Dan Gohman4fa2a3f2008-05-23 00:34:04 +00004202 // If OpTy is not a single value, it may be a struct/union that we
Dale Johanneseneb57ea72007-11-05 21:20:28 +00004203 // can tile with integers.
Dan Gohman4fa2a3f2008-05-23 00:34:04 +00004204 if (!OpTy->isSingleValueType() && OpTy->isSized()) {
Dale Johanneseneb57ea72007-11-05 21:20:28 +00004205 unsigned BitSize = TD->getTypeSizeInBits(OpTy);
4206 switch (BitSize) {
4207 default: break;
4208 case 1:
4209 case 8:
4210 case 16:
4211 case 32:
4212 case 64:
4213 OpTy = IntegerType::get(BitSize);
4214 break;
4215 }
Chris Lattner6995cf62007-04-29 18:58:03 +00004216 }
Dale Johanneseneb57ea72007-11-05 21:20:28 +00004217
4218 OpVT = TLI.getValueType(OpTy, true);
Chris Lattner0c583402007-04-28 20:49:53 +00004219 }
4220 }
4221
4222 OpInfo.ConstraintVT = OpVT;
Chris Lattner2a600be2007-04-28 21:01:43 +00004223
Chris Lattner3ff90dc2007-04-30 17:16:27 +00004224 // Compute the constraint code and ConstraintType to use.
Chris Lattner5a096902008-04-27 00:37:18 +00004225 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
Chris Lattner0c583402007-04-28 20:49:53 +00004226
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004227 // Keep track of whether we see an earlyclobber.
4228 SawEarlyClobber |= OpInfo.isEarlyClobber;
Chris Lattner09e4b7e2007-04-28 21:12:06 +00004229
Chris Lattner0fe71e92008-02-21 19:43:13 +00004230 // If we see a clobber of a register, it is an early clobber.
Chris Lattner69e6a8d2008-02-21 20:54:31 +00004231 if (!SawEarlyClobber &&
4232 OpInfo.Type == InlineAsm::isClobber &&
4233 OpInfo.ConstraintType == TargetLowering::C_Register) {
4234 // Note that we want to ignore things that we don't trick here, like
4235 // dirflag, fpsr, flags, etc.
4236 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
4237 TLI.getRegForInlineAsmConstraint(OpInfo.ConstraintCode,
4238 OpInfo.ConstraintVT);
4239 if (PhysReg.first || PhysReg.second) {
4240 // This is a register we know of.
4241 SawEarlyClobber = true;
4242 }
4243 }
Chris Lattner0fe71e92008-02-21 19:43:13 +00004244
Chris Lattner09e4b7e2007-04-28 21:12:06 +00004245 // If this is a memory input, and if the operand is not indirect, do what we
4246 // need to to provide an address for the memory input.
4247 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
4248 !OpInfo.isIndirect) {
4249 assert(OpInfo.Type == InlineAsm::isInput &&
4250 "Can only indirectify direct input operands!");
4251
4252 // Memory operands really want the address of the value. If we don't have
4253 // an indirect input, put it in the constpool if we can, otherwise spill
4254 // it to a stack slot.
4255
4256 // If the operand is a float, integer, or vector constant, spill to a
4257 // constant pool entry to get its address.
4258 Value *OpVal = OpInfo.CallOperandVal;
4259 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
4260 isa<ConstantVector>(OpVal)) {
4261 OpInfo.CallOperand = DAG.getConstantPool(cast<Constant>(OpVal),
4262 TLI.getPointerTy());
4263 } else {
4264 // Otherwise, create a stack slot and emit a store to it before the
4265 // asm.
4266 const Type *Ty = OpVal->getType();
Duncan Sands514ab342007-11-01 20:53:16 +00004267 uint64_t TySize = TLI.getTargetData()->getABITypeSize(Ty);
Chris Lattner09e4b7e2007-04-28 21:12:06 +00004268 unsigned Align = TLI.getTargetData()->getPrefTypeAlignment(Ty);
4269 MachineFunction &MF = DAG.getMachineFunction();
4270 int SSFI = MF.getFrameInfo()->CreateStackObject(TySize, Align);
Dan Gohman475871a2008-07-27 21:46:04 +00004271 SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getPointerTy());
Chris Lattner09e4b7e2007-04-28 21:12:06 +00004272 Chain = DAG.getStore(Chain, OpInfo.CallOperand, StackSlot, NULL, 0);
4273 OpInfo.CallOperand = StackSlot;
4274 }
4275
4276 // There is no longer a Value* corresponding to this operand.
4277 OpInfo.CallOperandVal = 0;
4278 // It is now an indirect operand.
4279 OpInfo.isIndirect = true;
4280 }
4281
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004282 // If this constraint is for a specific register, allocate it before
4283 // anything else.
4284 if (OpInfo.ConstraintType == TargetLowering::C_Register)
4285 GetRegistersForValue(OpInfo, SawEarlyClobber, OutputRegs, InputRegs);
Chris Lattner0c583402007-04-28 20:49:53 +00004286 }
Chris Lattner0c583402007-04-28 20:49:53 +00004287 ConstraintInfos.clear();
4288
4289
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004290 // Second pass - Loop over all of the operands, assigning virtual or physregs
4291 // to registerclass operands.
4292 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
Evan Cheng5c807602008-02-26 02:33:44 +00004293 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004294
4295 // C_Register operands have already been allocated, Other/Memory don't need
4296 // to be.
4297 if (OpInfo.ConstraintType == TargetLowering::C_RegisterClass)
4298 GetRegistersForValue(OpInfo, SawEarlyClobber, OutputRegs, InputRegs);
4299 }
4300
Chris Lattner0c583402007-04-28 20:49:53 +00004301 // AsmNodeOperands - The operands for the ISD::INLINEASM node.
Dan Gohman475871a2008-07-27 21:46:04 +00004302 std::vector<SDValue> AsmNodeOperands;
4303 AsmNodeOperands.push_back(SDValue()); // reserve space for input chain
Chris Lattner0c583402007-04-28 20:49:53 +00004304 AsmNodeOperands.push_back(
4305 DAG.getTargetExternalSymbol(IA->getAsmString().c_str(), MVT::Other));
4306
Chris Lattner2cc2f662006-02-01 01:28:23 +00004307
Chris Lattner0f0b7d42006-02-21 23:12:12 +00004308 // Loop over all of the inputs, copying the operand values into the
4309 // appropriate registers and processing the output regs.
Chris Lattner864635a2006-02-22 22:37:12 +00004310 RegsForValue RetValRegs;
Chris Lattner41f62592008-04-29 04:29:54 +00004311
Chris Lattner0c583402007-04-28 20:49:53 +00004312 // IndirectStoresToEmit - The set of stores to emit after the inline asm node.
4313 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
4314
4315 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
Evan Cheng5c807602008-02-26 02:33:44 +00004316 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
Chris Lattner1efa40f2006-02-22 00:56:39 +00004317
Chris Lattner0c583402007-04-28 20:49:53 +00004318 switch (OpInfo.Type) {
Chris Lattner2cc2f662006-02-01 01:28:23 +00004319 case InlineAsm::isOutput: {
Chris Lattnerc83994e2007-04-28 21:03:16 +00004320 if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass &&
4321 OpInfo.ConstraintType != TargetLowering::C_Register) {
Chris Lattnerf2f3cd52007-04-28 06:08:13 +00004322 // Memory output, or 'other' output (e.g. 'X' constraint).
Chris Lattner09e4b7e2007-04-28 21:12:06 +00004323 assert(OpInfo.isIndirect && "Memory output must be indirect operand");
Chris Lattner22873462006-02-27 23:45:39 +00004324
Chris Lattner22873462006-02-27 23:45:39 +00004325 // Add information to the INLINEASM node to know about this output.
4326 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
Chris Lattnerc90233b2007-05-15 01:33:58 +00004327 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
4328 TLI.getPointerTy()));
Chris Lattner09e4b7e2007-04-28 21:12:06 +00004329 AsmNodeOperands.push_back(OpInfo.CallOperand);
Chris Lattner22873462006-02-27 23:45:39 +00004330 break;
4331 }
4332
Chris Lattner2a600be2007-04-28 21:01:43 +00004333 // Otherwise, this is a register or register class output.
Chris Lattner22873462006-02-27 23:45:39 +00004334
Chris Lattner864635a2006-02-22 22:37:12 +00004335 // Copy the output from the appropriate register. Find a register that
Chris Lattner1efa40f2006-02-22 00:56:39 +00004336 // we can use.
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004337 if (OpInfo.AssignedRegs.Regs.empty()) {
Duncan Sandsa47c6c32008-06-17 03:24:13 +00004338 cerr << "Couldn't allocate output reg for constraint '"
Chris Lattner0c583402007-04-28 20:49:53 +00004339 << OpInfo.ConstraintCode << "'!\n";
Chris Lattnerd03f1582006-10-31 07:33:13 +00004340 exit(1);
4341 }
Chris Lattner1efa40f2006-02-22 00:56:39 +00004342
Chris Lattner41f62592008-04-29 04:29:54 +00004343 // If this is an indirect operand, store through the pointer after the
4344 // asm.
4345 if (OpInfo.isIndirect) {
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004346 IndirectStoresToEmit.push_back(std::make_pair(OpInfo.AssignedRegs,
Chris Lattner0c583402007-04-28 20:49:53 +00004347 OpInfo.CallOperandVal));
Chris Lattner41f62592008-04-29 04:29:54 +00004348 } else {
4349 // This is the result value of the call.
4350 assert(CS.getType() != Type::VoidTy && "Bad inline asm!");
4351 // Concatenate this output onto the outputs list.
4352 RetValRegs.append(OpInfo.AssignedRegs);
Chris Lattner2cc2f662006-02-01 01:28:23 +00004353 }
Chris Lattner6656dd12006-01-31 02:03:41 +00004354
4355 // Add information to the INLINEASM node to know that this register is
4356 // set.
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004357 OpInfo.AssignedRegs.AddInlineAsmOperands(2 /*REGDEF*/, DAG,
4358 AsmNodeOperands);
Chris Lattner6656dd12006-01-31 02:03:41 +00004359 break;
4360 }
4361 case InlineAsm::isInput: {
Dan Gohman475871a2008-07-27 21:46:04 +00004362 SDValue InOperandVal = OpInfo.CallOperand;
Chris Lattner3d81fee2006-02-04 02:16:44 +00004363
Chris Lattner0c583402007-04-28 20:49:53 +00004364 if (isdigit(OpInfo.ConstraintCode[0])) { // Matching constraint?
Chris Lattner2223aea2006-02-02 00:25:23 +00004365 // If this is required to match an output register we have already set,
4366 // just use its register.
Chris Lattner0c583402007-04-28 20:49:53 +00004367 unsigned OperandNo = atoi(OpInfo.ConstraintCode.c_str());
Chris Lattner3d81fee2006-02-04 02:16:44 +00004368
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00004369 // Scan until we find the definition we already emitted of this operand.
4370 // When we find it, create a RegsForValue operand.
4371 unsigned CurOp = 2; // The first operand.
4372 for (; OperandNo; --OperandNo) {
4373 // Advance to the next operand.
4374 unsigned NumOps =
4375 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
Chris Lattnera15cf702006-07-20 19:02:21 +00004376 assert(((NumOps & 7) == 2 /*REGDEF*/ ||
4377 (NumOps & 7) == 4 /*MEM*/) &&
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00004378 "Skipped past definitions?");
4379 CurOp += (NumOps>>3)+1;
4380 }
4381
4382 unsigned NumOps =
4383 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
Chris Lattner527fae12007-02-01 01:21:12 +00004384 if ((NumOps & 7) == 2 /*REGDEF*/) {
4385 // Add NumOps>>3 registers to MatchedRegs.
4386 RegsForValue MatchedRegs;
Dan Gohman23ce5022008-04-25 18:27:55 +00004387 MatchedRegs.TLI = &TLI;
Dan Gohman1fa850b2008-05-02 00:03:54 +00004388 MatchedRegs.ValueVTs.push_back(InOperandVal.getValueType());
4389 MatchedRegs.RegVTs.push_back(AsmNodeOperands[CurOp+1].getValueType());
Chris Lattner527fae12007-02-01 01:21:12 +00004390 for (unsigned i = 0, e = NumOps>>3; i != e; ++i) {
4391 unsigned Reg =
4392 cast<RegisterSDNode>(AsmNodeOperands[++CurOp])->getReg();
4393 MatchedRegs.Regs.push_back(Reg);
4394 }
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00004395
Chris Lattner527fae12007-02-01 01:21:12 +00004396 // Use the produced MatchedRegs object to
Dan Gohmanb6f5b002007-06-28 23:29:44 +00004397 MatchedRegs.getCopyToRegs(InOperandVal, DAG, Chain, &Flag);
Chris Lattner527fae12007-02-01 01:21:12 +00004398 MatchedRegs.AddInlineAsmOperands(1 /*REGUSE*/, DAG, AsmNodeOperands);
4399 break;
4400 } else {
4401 assert((NumOps & 7) == 4/*MEM*/ && "Unknown matching constraint!");
Chris Lattnerf9853bc2008-02-21 05:27:19 +00004402 assert((NumOps >> 3) == 1 && "Unexpected number of operands");
4403 // Add information to the INLINEASM node to know about this input.
4404 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
4405 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
4406 TLI.getPointerTy()));
4407 AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
4408 break;
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00004409 }
Chris Lattner2223aea2006-02-02 00:25:23 +00004410 }
Chris Lattner87bc3bd2006-02-24 01:11:24 +00004411
Chris Lattner2a600be2007-04-28 21:01:43 +00004412 if (OpInfo.ConstraintType == TargetLowering::C_Other) {
Chris Lattner0c583402007-04-28 20:49:53 +00004413 assert(!OpInfo.isIndirect &&
Chris Lattner44b2c502007-04-28 06:42:38 +00004414 "Don't know how to handle indirect other inputs yet!");
4415
Dan Gohman475871a2008-07-27 21:46:04 +00004416 std::vector<SDValue> Ops;
Chris Lattner48884cd2007-08-25 00:47:38 +00004417 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode[0],
4418 Ops, DAG);
4419 if (Ops.empty()) {
Bill Wendling832171c2006-12-07 20:04:42 +00004420 cerr << "Invalid operand for inline asm constraint '"
Chris Lattner0c583402007-04-28 20:49:53 +00004421 << OpInfo.ConstraintCode << "'!\n";
Chris Lattner53069fb2006-10-31 19:41:18 +00004422 exit(1);
4423 }
Chris Lattner87bc3bd2006-02-24 01:11:24 +00004424
4425 // Add information to the INLINEASM node to know about this input.
Chris Lattner48884cd2007-08-25 00:47:38 +00004426 unsigned ResOpType = 3 /*IMM*/ | (Ops.size() << 3);
Chris Lattnerc90233b2007-05-15 01:33:58 +00004427 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
4428 TLI.getPointerTy()));
Chris Lattner48884cd2007-08-25 00:47:38 +00004429 AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end());
Chris Lattner87bc3bd2006-02-24 01:11:24 +00004430 break;
Chris Lattner2a600be2007-04-28 21:01:43 +00004431 } else if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
Chris Lattner09e4b7e2007-04-28 21:12:06 +00004432 assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
Chris Lattner44b2c502007-04-28 06:42:38 +00004433 assert(InOperandVal.getValueType() == TLI.getPointerTy() &&
4434 "Memory operands expect pointer values");
4435
Chris Lattner87bc3bd2006-02-24 01:11:24 +00004436 // Add information to the INLINEASM node to know about this input.
4437 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
Chris Lattnerc90233b2007-05-15 01:33:58 +00004438 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
4439 TLI.getPointerTy()));
Chris Lattner87bc3bd2006-02-24 01:11:24 +00004440 AsmNodeOperands.push_back(InOperandVal);
4441 break;
4442 }
4443
Chris Lattner2a600be2007-04-28 21:01:43 +00004444 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
4445 OpInfo.ConstraintType == TargetLowering::C_Register) &&
4446 "Unknown constraint type!");
Chris Lattner0c583402007-04-28 20:49:53 +00004447 assert(!OpInfo.isIndirect &&
Chris Lattner44b2c502007-04-28 06:42:38 +00004448 "Don't know how to handle indirect register inputs yet!");
Chris Lattner87bc3bd2006-02-24 01:11:24 +00004449
4450 // Copy the input into the appropriate registers.
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004451 assert(!OpInfo.AssignedRegs.Regs.empty() &&
4452 "Couldn't allocate input reg!");
Chris Lattner87bc3bd2006-02-24 01:11:24 +00004453
Dan Gohmanb6f5b002007-06-28 23:29:44 +00004454 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, Chain, &Flag);
Chris Lattner87bc3bd2006-02-24 01:11:24 +00004455
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004456 OpInfo.AssignedRegs.AddInlineAsmOperands(1/*REGUSE*/, DAG,
4457 AsmNodeOperands);
Chris Lattner6656dd12006-01-31 02:03:41 +00004458 break;
4459 }
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00004460 case InlineAsm::isClobber: {
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00004461 // Add the clobbered value to the operand list, so that the register
4462 // allocator is aware that the physreg got clobbered.
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004463 if (!OpInfo.AssignedRegs.Regs.empty())
4464 OpInfo.AssignedRegs.AddInlineAsmOperands(2/*REGDEF*/, DAG,
4465 AsmNodeOperands);
Chris Lattner6656dd12006-01-31 02:03:41 +00004466 break;
4467 }
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00004468 }
Chris Lattner6656dd12006-01-31 02:03:41 +00004469 }
Chris Lattnerce7518c2006-01-26 22:24:51 +00004470
4471 // Finish up input operands.
4472 AsmNodeOperands[0] = Chain;
4473 if (Flag.Val) AsmNodeOperands.push_back(Flag);
4474
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00004475 Chain = DAG.getNode(ISD::INLINEASM,
4476 DAG.getNodeValueTypes(MVT::Other, MVT::Flag), 2,
Chris Lattnerbd564bf2006-08-08 02:23:42 +00004477 &AsmNodeOperands[0], AsmNodeOperands.size());
Chris Lattnerce7518c2006-01-26 22:24:51 +00004478 Flag = Chain.getValue(1);
4479
Chris Lattner6656dd12006-01-31 02:03:41 +00004480 // If this asm returns a register value, copy the result from that register
4481 // and set it as the value of the call.
Chris Lattner3a508c92007-04-12 06:00:20 +00004482 if (!RetValRegs.Regs.empty()) {
Dan Gohman475871a2008-07-27 21:46:04 +00004483 SDValue Val = RetValRegs.getCopyFromRegs(DAG, Chain, &Flag);
Chris Lattner3fb29682008-04-29 04:48:56 +00004484
4485 // If any of the results of the inline asm is a vector, it may have the
4486 // wrong width/num elts. This can happen for register classes that can
4487 // contain multiple different value types. The preg or vreg allocated may
4488 // not have the same VT as was expected. Convert it to the right type with
Dan Gohman7f321562007-06-25 16:23:39 +00004489 // bit_convert.
Chris Lattner3fb29682008-04-29 04:48:56 +00004490 if (const StructType *ResSTy = dyn_cast<StructType>(CS.getType())) {
4491 for (unsigned i = 0, e = ResSTy->getNumElements(); i != e; ++i) {
Duncan Sands83ec4b62008-06-06 12:08:01 +00004492 if (Val.Val->getValueType(i).isVector())
Chris Lattner3fb29682008-04-29 04:48:56 +00004493 Val = DAG.getNode(ISD::BIT_CONVERT,
4494 TLI.getValueType(ResSTy->getElementType(i)), Val);
4495 }
4496 } else {
Duncan Sands83ec4b62008-06-06 12:08:01 +00004497 if (Val.getValueType().isVector())
Chris Lattner3fb29682008-04-29 04:48:56 +00004498 Val = DAG.getNode(ISD::BIT_CONVERT, TLI.getValueType(CS.getType()),
4499 Val);
Chris Lattner3a508c92007-04-12 06:00:20 +00004500 }
Chris Lattner3fb29682008-04-29 04:48:56 +00004501
Duncan Sandsfd7b3262007-12-17 18:08:19 +00004502 setValue(CS.getInstruction(), Val);
Chris Lattner3a508c92007-04-12 06:00:20 +00004503 }
Chris Lattnerce7518c2006-01-26 22:24:51 +00004504
Dan Gohman475871a2008-07-27 21:46:04 +00004505 std::vector<std::pair<SDValue, Value*> > StoresToEmit;
Chris Lattner6656dd12006-01-31 02:03:41 +00004506
4507 // Process indirect outputs, first output all of the flagged copies out of
4508 // physregs.
4509 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
Chris Lattner864635a2006-02-22 22:37:12 +00004510 RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
Chris Lattner6656dd12006-01-31 02:03:41 +00004511 Value *Ptr = IndirectStoresToEmit[i].second;
Dan Gohman475871a2008-07-27 21:46:04 +00004512 SDValue OutVal = OutRegs.getCopyFromRegs(DAG, Chain, &Flag);
Chris Lattner864635a2006-02-22 22:37:12 +00004513 StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
Chris Lattner6656dd12006-01-31 02:03:41 +00004514 }
4515
4516 // Emit the non-flagged stores from the physregs.
Dan Gohman475871a2008-07-27 21:46:04 +00004517 SmallVector<SDValue, 8> OutChains;
Chris Lattner6656dd12006-01-31 02:03:41 +00004518 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i)
Chris Lattner0c583402007-04-28 20:49:53 +00004519 OutChains.push_back(DAG.getStore(Chain, StoresToEmit[i].first,
Chris Lattner6656dd12006-01-31 02:03:41 +00004520 getValue(StoresToEmit[i].second),
Evan Cheng8b2794a2006-10-13 21:14:26 +00004521 StoresToEmit[i].second, 0));
Chris Lattner6656dd12006-01-31 02:03:41 +00004522 if (!OutChains.empty())
Chris Lattnerbd564bf2006-08-08 02:23:42 +00004523 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
4524 &OutChains[0], OutChains.size());
Chris Lattnerce7518c2006-01-26 22:24:51 +00004525 DAG.setRoot(Chain);
4526}
4527
4528
Chris Lattner1c08c712005-01-07 07:47:53 +00004529void SelectionDAGLowering::visitMalloc(MallocInst &I) {
Dan Gohman475871a2008-07-27 21:46:04 +00004530 SDValue Src = getValue(I.getOperand(0));
Chris Lattner1c08c712005-01-07 07:47:53 +00004531
Duncan Sands83ec4b62008-06-06 12:08:01 +00004532 MVT IntPtr = TLI.getPointerTy();
Chris Lattner68cd65e2005-01-22 23:04:37 +00004533
Duncan Sands8e4eb092008-06-08 20:54:56 +00004534 if (IntPtr.bitsLT(Src.getValueType()))
Chris Lattner68cd65e2005-01-22 23:04:37 +00004535 Src = DAG.getNode(ISD::TRUNCATE, IntPtr, Src);
Duncan Sands8e4eb092008-06-08 20:54:56 +00004536 else if (IntPtr.bitsGT(Src.getValueType()))
Chris Lattner68cd65e2005-01-22 23:04:37 +00004537 Src = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, Src);
Chris Lattner1c08c712005-01-07 07:47:53 +00004538
4539 // Scale the source by the type size.
Duncan Sands514ab342007-11-01 20:53:16 +00004540 uint64_t ElementSize = TD->getABITypeSize(I.getType()->getElementType());
Chris Lattner1c08c712005-01-07 07:47:53 +00004541 Src = DAG.getNode(ISD::MUL, Src.getValueType(),
Chris Lattner0bd48932008-01-17 07:00:52 +00004542 Src, DAG.getIntPtrConstant(ElementSize));
Chris Lattner1c08c712005-01-07 07:47:53 +00004543
Reid Spencer47857812006-12-31 05:55:36 +00004544 TargetLowering::ArgListTy Args;
4545 TargetLowering::ArgListEntry Entry;
4546 Entry.Node = Src;
4547 Entry.Ty = TLI.getTargetData()->getIntPtrType();
Reid Spencer47857812006-12-31 05:55:36 +00004548 Args.push_back(Entry);
Chris Lattnercf5734d2005-01-08 19:26:18 +00004549
Dan Gohman475871a2008-07-27 21:46:04 +00004550 std::pair<SDValue,SDValue> Result =
Duncan Sands00fee652008-02-14 17:28:50 +00004551 TLI.LowerCallTo(getRoot(), I.getType(), false, false, false, CallingConv::C,
4552 true, DAG.getExternalSymbol("malloc", IntPtr), Args, DAG);
Chris Lattnercf5734d2005-01-08 19:26:18 +00004553 setValue(&I, Result.first); // Pointers always fit in registers
4554 DAG.setRoot(Result.second);
Chris Lattner1c08c712005-01-07 07:47:53 +00004555}
4556
4557void SelectionDAGLowering::visitFree(FreeInst &I) {
Reid Spencer47857812006-12-31 05:55:36 +00004558 TargetLowering::ArgListTy Args;
4559 TargetLowering::ArgListEntry Entry;
4560 Entry.Node = getValue(I.getOperand(0));
4561 Entry.Ty = TLI.getTargetData()->getIntPtrType();
Reid Spencer47857812006-12-31 05:55:36 +00004562 Args.push_back(Entry);
Duncan Sands83ec4b62008-06-06 12:08:01 +00004563 MVT IntPtr = TLI.getPointerTy();
Dan Gohman475871a2008-07-27 21:46:04 +00004564 std::pair<SDValue,SDValue> Result =
Duncan Sands00fee652008-02-14 17:28:50 +00004565 TLI.LowerCallTo(getRoot(), Type::VoidTy, false, false, false,
4566 CallingConv::C, true,
Chris Lattnercf5734d2005-01-08 19:26:18 +00004567 DAG.getExternalSymbol("free", IntPtr), Args, DAG);
4568 DAG.setRoot(Result.second);
Chris Lattner1c08c712005-01-07 07:47:53 +00004569}
4570
Evan Chengff9b3732008-01-30 18:18:23 +00004571// EmitInstrWithCustomInserter - This method should be implemented by targets
4572// that mark instructions with the 'usesCustomDAGSchedInserter' flag. These
Chris Lattner025c39b2005-08-26 20:54:47 +00004573// instructions are special in various ways, which require special support to
4574// insert. The specified MachineInstr is created but not inserted into any
4575// basic blocks, and the scheduler passes ownership of it to this method.
Evan Chengff9b3732008-01-30 18:18:23 +00004576MachineBasicBlock *TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
Chris Lattner025c39b2005-08-26 20:54:47 +00004577 MachineBasicBlock *MBB) {
Bill Wendling832171c2006-12-07 20:04:42 +00004578 cerr << "If a target marks an instruction with "
4579 << "'usesCustomDAGSchedInserter', it must implement "
Evan Chengff9b3732008-01-30 18:18:23 +00004580 << "TargetLowering::EmitInstrWithCustomInserter!\n";
Chris Lattner025c39b2005-08-26 20:54:47 +00004581 abort();
4582 return 0;
4583}
4584
Chris Lattner39ae3622005-01-09 00:00:49 +00004585void SelectionDAGLowering::visitVAStart(CallInst &I) {
Nate Begemanacc398c2006-01-25 18:21:52 +00004586 DAG.setRoot(DAG.getNode(ISD::VASTART, MVT::Other, getRoot(),
4587 getValue(I.getOperand(1)),
4588 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner39ae3622005-01-09 00:00:49 +00004589}
4590
4591void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
Dan Gohman475871a2008-07-27 21:46:04 +00004592 SDValue V = DAG.getVAArg(TLI.getValueType(I.getType()), getRoot(),
Nate Begemanacc398c2006-01-25 18:21:52 +00004593 getValue(I.getOperand(0)),
4594 DAG.getSrcValue(I.getOperand(0)));
4595 setValue(&I, V);
4596 DAG.setRoot(V.getValue(1));
Chris Lattner1c08c712005-01-07 07:47:53 +00004597}
4598
4599void SelectionDAGLowering::visitVAEnd(CallInst &I) {
Nate Begemanacc398c2006-01-25 18:21:52 +00004600 DAG.setRoot(DAG.getNode(ISD::VAEND, MVT::Other, getRoot(),
4601 getValue(I.getOperand(1)),
4602 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner1c08c712005-01-07 07:47:53 +00004603}
4604
4605void SelectionDAGLowering::visitVACopy(CallInst &I) {
Nate Begemanacc398c2006-01-25 18:21:52 +00004606 DAG.setRoot(DAG.getNode(ISD::VACOPY, MVT::Other, getRoot(),
4607 getValue(I.getOperand(1)),
4608 getValue(I.getOperand(2)),
4609 DAG.getSrcValue(I.getOperand(1)),
4610 DAG.getSrcValue(I.getOperand(2))));
Chris Lattner1c08c712005-01-07 07:47:53 +00004611}
4612
Chris Lattnerfdfded52006-04-12 16:20:43 +00004613/// TargetLowering::LowerArguments - This is the default LowerArguments
4614/// implementation, which just inserts a FORMAL_ARGUMENTS node. FIXME: When all
Chris Lattnerf4ec8172006-05-16 22:53:20 +00004615/// targets are migrated to using FORMAL_ARGUMENTS, this hook should be
4616/// integrated into SDISel.
Dan Gohmana44b6742008-06-30 20:31:15 +00004617void TargetLowering::LowerArguments(Function &F, SelectionDAG &DAG,
Dan Gohman475871a2008-07-27 21:46:04 +00004618 SmallVectorImpl<SDValue> &ArgValues) {
Chris Lattnerfdfded52006-04-12 16:20:43 +00004619 // Add CC# and isVararg as operands to the FORMAL_ARGUMENTS node.
Dan Gohman475871a2008-07-27 21:46:04 +00004620 SmallVector<SDValue, 3+16> Ops;
Chris Lattner8c0c10c2006-05-16 06:45:34 +00004621 Ops.push_back(DAG.getRoot());
Chris Lattnerfdfded52006-04-12 16:20:43 +00004622 Ops.push_back(DAG.getConstant(F.getCallingConv(), getPointerTy()));
4623 Ops.push_back(DAG.getConstant(F.isVarArg(), getPointerTy()));
4624
4625 // Add one result value for each formal argument.
Dan Gohmana44b6742008-06-30 20:31:15 +00004626 SmallVector<MVT, 16> RetVals;
Anton Korobeynikov6aa279d2007-01-28 18:01:49 +00004627 unsigned j = 1;
Anton Korobeynikovac2b2cf2007-01-28 16:04:40 +00004628 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end();
4629 I != E; ++I, ++j) {
Dan Gohmanf5025cf2008-06-09 21:19:23 +00004630 SmallVector<MVT, 4> ValueVTs;
4631 ComputeValueVTs(*this, I->getType(), ValueVTs);
4632 for (unsigned Value = 0, NumValues = ValueVTs.size();
4633 Value != NumValues; ++Value) {
4634 MVT VT = ValueVTs[Value];
4635 const Type *ArgTy = VT.getTypeForMVT();
4636 ISD::ArgFlagsTy Flags;
4637 unsigned OriginalAlignment =
4638 getTargetData()->getABITypeAlignment(ArgTy);
Lauro Ramos Venancio7aa47b62007-02-13 13:50:08 +00004639
Dan Gohmanf5025cf2008-06-09 21:19:23 +00004640 if (F.paramHasAttr(j, ParamAttr::ZExt))
4641 Flags.setZExt();
4642 if (F.paramHasAttr(j, ParamAttr::SExt))
4643 Flags.setSExt();
4644 if (F.paramHasAttr(j, ParamAttr::InReg))
4645 Flags.setInReg();
4646 if (F.paramHasAttr(j, ParamAttr::StructRet))
4647 Flags.setSRet();
4648 if (F.paramHasAttr(j, ParamAttr::ByVal)) {
4649 Flags.setByVal();
4650 const PointerType *Ty = cast<PointerType>(I->getType());
4651 const Type *ElementTy = Ty->getElementType();
4652 unsigned FrameAlign = getByValTypeAlignment(ElementTy);
4653 unsigned FrameSize = getTargetData()->getABITypeSize(ElementTy);
4654 // For ByVal, alignment should be passed from FE. BE will guess if
4655 // this info is not there but there are cases it cannot get right.
4656 if (F.getParamAlignment(j))
4657 FrameAlign = F.getParamAlignment(j);
4658 Flags.setByValAlign(FrameAlign);
4659 Flags.setByValSize(FrameSize);
4660 }
4661 if (F.paramHasAttr(j, ParamAttr::Nest))
4662 Flags.setNest();
4663 Flags.setOrigAlign(OriginalAlignment);
Duncan Sandsb988bac2008-02-11 20:58:28 +00004664
Dan Gohmanf5025cf2008-06-09 21:19:23 +00004665 MVT RegisterVT = getRegisterType(VT);
4666 unsigned NumRegs = getNumRegisters(VT);
4667 for (unsigned i = 0; i != NumRegs; ++i) {
4668 RetVals.push_back(RegisterVT);
4669 ISD::ArgFlagsTy MyFlags = Flags;
4670 if (NumRegs > 1 && i == 0)
4671 MyFlags.setSplit();
4672 // if it isn't first piece, alignment must be 1
4673 else if (i > 0)
4674 MyFlags.setOrigAlign(1);
4675 Ops.push_back(DAG.getArgFlags(MyFlags));
4676 }
Dan Gohmanb6f5b002007-06-28 23:29:44 +00004677 }
Chris Lattnerfdfded52006-04-12 16:20:43 +00004678 }
Evan Cheng3b0d2862006-04-25 23:03:35 +00004679
Chris Lattner8c0c10c2006-05-16 06:45:34 +00004680 RetVals.push_back(MVT::Other);
Chris Lattnerfdfded52006-04-12 16:20:43 +00004681
4682 // Create the node.
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00004683 SDNode *Result = DAG.getNode(ISD::FORMAL_ARGUMENTS,
Chris Lattner86ca3ca2008-02-13 07:39:09 +00004684 DAG.getVTList(&RetVals[0], RetVals.size()),
Chris Lattnerbd564bf2006-08-08 02:23:42 +00004685 &Ops[0], Ops.size()).Val;
Chris Lattner86ca3ca2008-02-13 07:39:09 +00004686
4687 // Prelower FORMAL_ARGUMENTS. This isn't required for functionality, but
4688 // allows exposing the loads that may be part of the argument access to the
4689 // first DAGCombiner pass.
Dan Gohman475871a2008-07-27 21:46:04 +00004690 SDValue TmpRes = LowerOperation(SDValue(Result, 0), DAG);
Chris Lattner86ca3ca2008-02-13 07:39:09 +00004691
4692 // The number of results should match up, except that the lowered one may have
4693 // an extra flag result.
4694 assert((Result->getNumValues() == TmpRes.Val->getNumValues() ||
4695 (Result->getNumValues()+1 == TmpRes.Val->getNumValues() &&
4696 TmpRes.getValue(Result->getNumValues()).getValueType() == MVT::Flag))
4697 && "Lowering produced unexpected number of results!");
Dan Gohman2dbc1672008-07-21 21:04:07 +00004698
4699 // The FORMAL_ARGUMENTS node itself is likely no longer needed.
4700 if (Result != TmpRes.Val && Result->use_empty()) {
4701 HandleSDNode Dummy(DAG.getRoot());
4702 DAG.RemoveDeadNode(Result);
4703 }
4704
Chris Lattner86ca3ca2008-02-13 07:39:09 +00004705 Result = TmpRes.Val;
4706
Dan Gohman27a70be2007-07-02 16:18:06 +00004707 unsigned NumArgRegs = Result->getNumValues() - 1;
Dan Gohman475871a2008-07-27 21:46:04 +00004708 DAG.setRoot(SDValue(Result, NumArgRegs));
Chris Lattnerfdfded52006-04-12 16:20:43 +00004709
4710 // Set up the return result vector.
Chris Lattnerfdfded52006-04-12 16:20:43 +00004711 unsigned i = 0;
Reid Spencer47857812006-12-31 05:55:36 +00004712 unsigned Idx = 1;
4713 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E;
4714 ++I, ++Idx) {
Dan Gohmanf5025cf2008-06-09 21:19:23 +00004715 SmallVector<MVT, 4> ValueVTs;
4716 ComputeValueVTs(*this, I->getType(), ValueVTs);
4717 for (unsigned Value = 0, NumValues = ValueVTs.size();
4718 Value != NumValues; ++Value) {
4719 MVT VT = ValueVTs[Value];
4720 MVT PartVT = getRegisterType(VT);
Duncan Sandsb988bac2008-02-11 20:58:28 +00004721
Dan Gohmanf5025cf2008-06-09 21:19:23 +00004722 unsigned NumParts = getNumRegisters(VT);
Dan Gohman475871a2008-07-27 21:46:04 +00004723 SmallVector<SDValue, 4> Parts(NumParts);
Dan Gohmanf5025cf2008-06-09 21:19:23 +00004724 for (unsigned j = 0; j != NumParts; ++j)
Dan Gohman475871a2008-07-27 21:46:04 +00004725 Parts[j] = SDValue(Result, i++);
Duncan Sandsb988bac2008-02-11 20:58:28 +00004726
Dan Gohmanf5025cf2008-06-09 21:19:23 +00004727 ISD::NodeType AssertOp = ISD::DELETED_NODE;
4728 if (F.paramHasAttr(Idx, ParamAttr::SExt))
4729 AssertOp = ISD::AssertSext;
4730 else if (F.paramHasAttr(Idx, ParamAttr::ZExt))
4731 AssertOp = ISD::AssertZext;
Duncan Sandsb988bac2008-02-11 20:58:28 +00004732
Dan Gohmana44b6742008-06-30 20:31:15 +00004733 ArgValues.push_back(getCopyFromParts(DAG, &Parts[0], NumParts, PartVT, VT,
4734 AssertOp));
Dan Gohmanf5025cf2008-06-09 21:19:23 +00004735 }
Chris Lattnerfdfded52006-04-12 16:20:43 +00004736 }
Dan Gohman27a70be2007-07-02 16:18:06 +00004737 assert(i == NumArgRegs && "Argument register count mismatch!");
Chris Lattnerfdfded52006-04-12 16:20:43 +00004738}
4739
Chris Lattnerf4ec8172006-05-16 22:53:20 +00004740
4741/// TargetLowering::LowerCallTo - This is the default LowerCallTo
4742/// implementation, which just inserts an ISD::CALL node, which is later custom
4743/// lowered by the target to something concrete. FIXME: When all targets are
4744/// migrated to using ISD::CALL, this hook should be integrated into SDISel.
Dan Gohman475871a2008-07-27 21:46:04 +00004745std::pair<SDValue, SDValue>
4746TargetLowering::LowerCallTo(SDValue Chain, const Type *RetTy,
Duncan Sands00fee652008-02-14 17:28:50 +00004747 bool RetSExt, bool RetZExt, bool isVarArg,
4748 unsigned CallingConv, bool isTailCall,
Dan Gohman475871a2008-07-27 21:46:04 +00004749 SDValue Callee,
Chris Lattnerf4ec8172006-05-16 22:53:20 +00004750 ArgListTy &Args, SelectionDAG &DAG) {
Dan Gohman475871a2008-07-27 21:46:04 +00004751 SmallVector<SDValue, 32> Ops;
Chris Lattnerf4ec8172006-05-16 22:53:20 +00004752 Ops.push_back(Chain); // Op#0 - Chain
4753 Ops.push_back(DAG.getConstant(CallingConv, getPointerTy())); // Op#1 - CC
4754 Ops.push_back(DAG.getConstant(isVarArg, getPointerTy())); // Op#2 - VarArg
4755 Ops.push_back(DAG.getConstant(isTailCall, getPointerTy())); // Op#3 - Tail
4756 Ops.push_back(Callee);
4757
4758 // Handle all of the outgoing arguments.
4759 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
Dan Gohmanf5025cf2008-06-09 21:19:23 +00004760 SmallVector<MVT, 4> ValueVTs;
4761 ComputeValueVTs(*this, Args[i].Ty, ValueVTs);
4762 for (unsigned Value = 0, NumValues = ValueVTs.size();
4763 Value != NumValues; ++Value) {
4764 MVT VT = ValueVTs[Value];
4765 const Type *ArgTy = VT.getTypeForMVT();
Dan Gohman475871a2008-07-27 21:46:04 +00004766 SDValue Op = SDValue(Args[i].Node.Val, Args[i].Node.ResNo + Value);
Dan Gohmanf5025cf2008-06-09 21:19:23 +00004767 ISD::ArgFlagsTy Flags;
4768 unsigned OriginalAlignment =
4769 getTargetData()->getABITypeAlignment(ArgTy);
Duncan Sands276dcbd2008-03-21 09:14:45 +00004770
Dan Gohmanf5025cf2008-06-09 21:19:23 +00004771 if (Args[i].isZExt)
4772 Flags.setZExt();
4773 if (Args[i].isSExt)
4774 Flags.setSExt();
4775 if (Args[i].isInReg)
4776 Flags.setInReg();
4777 if (Args[i].isSRet)
4778 Flags.setSRet();
4779 if (Args[i].isByVal) {
4780 Flags.setByVal();
4781 const PointerType *Ty = cast<PointerType>(Args[i].Ty);
4782 const Type *ElementTy = Ty->getElementType();
4783 unsigned FrameAlign = getByValTypeAlignment(ElementTy);
4784 unsigned FrameSize = getTargetData()->getABITypeSize(ElementTy);
4785 // For ByVal, alignment should come from FE. BE will guess if this
4786 // info is not there but there are cases it cannot get right.
4787 if (Args[i].Alignment)
4788 FrameAlign = Args[i].Alignment;
4789 Flags.setByValAlign(FrameAlign);
4790 Flags.setByValSize(FrameSize);
4791 }
4792 if (Args[i].isNest)
4793 Flags.setNest();
4794 Flags.setOrigAlign(OriginalAlignment);
Dan Gohman27a70be2007-07-02 16:18:06 +00004795
Dan Gohmanf5025cf2008-06-09 21:19:23 +00004796 MVT PartVT = getRegisterType(VT);
4797 unsigned NumParts = getNumRegisters(VT);
Dan Gohman475871a2008-07-27 21:46:04 +00004798 SmallVector<SDValue, 4> Parts(NumParts);
Dan Gohmanf5025cf2008-06-09 21:19:23 +00004799 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
Duncan Sandsb988bac2008-02-11 20:58:28 +00004800
Dan Gohmanf5025cf2008-06-09 21:19:23 +00004801 if (Args[i].isSExt)
4802 ExtendKind = ISD::SIGN_EXTEND;
4803 else if (Args[i].isZExt)
4804 ExtendKind = ISD::ZERO_EXTEND;
Duncan Sandsb988bac2008-02-11 20:58:28 +00004805
Dan Gohmanf5025cf2008-06-09 21:19:23 +00004806 getCopyToParts(DAG, Op, &Parts[0], NumParts, PartVT, ExtendKind);
Duncan Sandsb988bac2008-02-11 20:58:28 +00004807
Dan Gohmanf5025cf2008-06-09 21:19:23 +00004808 for (unsigned i = 0; i != NumParts; ++i) {
4809 // if it isn't first piece, alignment must be 1
4810 ISD::ArgFlagsTy MyFlags = Flags;
4811 if (NumParts > 1 && i == 0)
4812 MyFlags.setSplit();
4813 else if (i != 0)
4814 MyFlags.setOrigAlign(1);
Duncan Sandsb988bac2008-02-11 20:58:28 +00004815
Dan Gohmanf5025cf2008-06-09 21:19:23 +00004816 Ops.push_back(Parts[i]);
4817 Ops.push_back(DAG.getArgFlags(MyFlags));
4818 }
Dan Gohman27a70be2007-07-02 16:18:06 +00004819 }
Chris Lattnerf4ec8172006-05-16 22:53:20 +00004820 }
4821
Dan Gohmanef5d1942008-03-11 21:11:25 +00004822 // Figure out the result value types. We start by making a list of
Dan Gohman23ce5022008-04-25 18:27:55 +00004823 // the potentially illegal return value types.
Duncan Sands83ec4b62008-06-06 12:08:01 +00004824 SmallVector<MVT, 4> LoweredRetTys;
4825 SmallVector<MVT, 4> RetTys;
Dan Gohman23ce5022008-04-25 18:27:55 +00004826 ComputeValueVTs(*this, RetTy, RetTys);
Dan Gohmanef5d1942008-03-11 21:11:25 +00004827
Dan Gohman23ce5022008-04-25 18:27:55 +00004828 // Then we translate that to a list of legal types.
4829 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
Duncan Sands83ec4b62008-06-06 12:08:01 +00004830 MVT VT = RetTys[I];
4831 MVT RegisterVT = getRegisterType(VT);
Dan Gohmanef5d1942008-03-11 21:11:25 +00004832 unsigned NumRegs = getNumRegisters(VT);
4833 for (unsigned i = 0; i != NumRegs; ++i)
4834 LoweredRetTys.push_back(RegisterVT);
4835 }
Chris Lattnerf4ec8172006-05-16 22:53:20 +00004836
Dan Gohmanef5d1942008-03-11 21:11:25 +00004837 LoweredRetTys.push_back(MVT::Other); // Always has a chain.
Chris Lattnerf4ec8172006-05-16 22:53:20 +00004838
Dan Gohmanb6f5b002007-06-28 23:29:44 +00004839 // Create the CALL node.
Dan Gohman475871a2008-07-27 21:46:04 +00004840 SDValue Res = DAG.getNode(ISD::CALL,
Dan Gohmanef5d1942008-03-11 21:11:25 +00004841 DAG.getVTList(&LoweredRetTys[0],
4842 LoweredRetTys.size()),
Chris Lattnerbe384162006-08-16 22:57:46 +00004843 &Ops[0], Ops.size());
Dan Gohmanef5d1942008-03-11 21:11:25 +00004844 Chain = Res.getValue(LoweredRetTys.size() - 1);
Dan Gohmanb6f5b002007-06-28 23:29:44 +00004845
4846 // Gather up the call result into a single value.
4847 if (RetTy != Type::VoidTy) {
Duncan Sands00fee652008-02-14 17:28:50 +00004848 ISD::NodeType AssertOp = ISD::DELETED_NODE;
4849
4850 if (RetSExt)
4851 AssertOp = ISD::AssertSext;
4852 else if (RetZExt)
Dan Gohmanb6f5b002007-06-28 23:29:44 +00004853 AssertOp = ISD::AssertZext;
Duncan Sands00fee652008-02-14 17:28:50 +00004854
Dan Gohman475871a2008-07-27 21:46:04 +00004855 SmallVector<SDValue, 4> ReturnValues;
Dan Gohmanef5d1942008-03-11 21:11:25 +00004856 unsigned RegNo = 0;
Dan Gohman23ce5022008-04-25 18:27:55 +00004857 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
Duncan Sands83ec4b62008-06-06 12:08:01 +00004858 MVT VT = RetTys[I];
4859 MVT RegisterVT = getRegisterType(VT);
Dan Gohmanef5d1942008-03-11 21:11:25 +00004860 unsigned NumRegs = getNumRegisters(VT);
4861 unsigned RegNoEnd = NumRegs + RegNo;
Dan Gohman475871a2008-07-27 21:46:04 +00004862 SmallVector<SDValue, 4> Results;
Dan Gohmanef5d1942008-03-11 21:11:25 +00004863 for (; RegNo != RegNoEnd; ++RegNo)
4864 Results.push_back(Res.getValue(RegNo));
Dan Gohman475871a2008-07-27 21:46:04 +00004865 SDValue ReturnValue =
Dan Gohmanef5d1942008-03-11 21:11:25 +00004866 getCopyFromParts(DAG, &Results[0], NumRegs, RegisterVT, VT,
4867 AssertOp);
4868 ReturnValues.push_back(ReturnValue);
4869 }
Duncan Sandsf9516202008-06-30 10:19:09 +00004870 Res = DAG.getMergeValues(DAG.getVTList(&RetTys[0], RetTys.size()),
4871 &ReturnValues[0], ReturnValues.size());
Chris Lattnerf4ec8172006-05-16 22:53:20 +00004872 }
Dan Gohmanb6f5b002007-06-28 23:29:44 +00004873
4874 return std::make_pair(Res, Chain);
Chris Lattnerf4ec8172006-05-16 22:53:20 +00004875}
4876
Dan Gohman475871a2008-07-27 21:46:04 +00004877SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) {
Chris Lattner171453a2005-01-16 07:28:41 +00004878 assert(0 && "LowerOperation not implemented for this target!");
4879 abort();
Dan Gohman475871a2008-07-27 21:46:04 +00004880 return SDValue();
Chris Lattner171453a2005-01-16 07:28:41 +00004881}
4882
Nate Begeman0aed7842006-01-28 03:14:31 +00004883
Chris Lattner7041ee32005-01-11 05:56:49 +00004884//===----------------------------------------------------------------------===//
4885// SelectionDAGISel code
4886//===----------------------------------------------------------------------===//
Chris Lattner1c08c712005-01-07 07:47:53 +00004887
Duncan Sands83ec4b62008-06-06 12:08:01 +00004888unsigned SelectionDAGISel::MakeReg(MVT VT) {
Chris Lattner84bc5422007-12-31 04:13:23 +00004889 return RegInfo->createVirtualRegister(TLI.getRegClassFor(VT));
Chris Lattner1c08c712005-01-07 07:47:53 +00004890}
4891
Chris Lattner495a0b52005-08-17 06:37:43 +00004892void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const {
Jim Laskeyc7c3f112006-10-16 20:52:31 +00004893 AU.addRequired<AliasAnalysis>();
Gordon Henriksen5eca0752008-08-17 18:44:35 +00004894 AU.addRequired<GCModuleInfo>();
Chris Lattnerc8d288f2007-03-31 04:18:03 +00004895 AU.setPreservesAll();
Chris Lattner495a0b52005-08-17 06:37:43 +00004896}
Chris Lattner1c08c712005-01-07 07:47:53 +00004897
Chris Lattner1c08c712005-01-07 07:47:53 +00004898bool SelectionDAGISel::runOnFunction(Function &Fn) {
Dan Gohman5f43f922007-08-27 16:26:13 +00004899 // Get alias analysis for load/store combining.
4900 AA = &getAnalysis<AliasAnalysis>();
4901
Chris Lattner1c08c712005-01-07 07:47:53 +00004902 MachineFunction &MF = MachineFunction::construct(&Fn, TLI.getTargetMachine());
Gordon Henriksen5eca0752008-08-17 18:44:35 +00004903 if (MF.getFunction()->hasGC())
4904 GFI = &getAnalysis<GCModuleInfo>().getFunctionInfo(*MF.getFunction());
Gordon Henriksence224772008-01-07 01:30:38 +00004905 else
Gordon Henriksen5eca0752008-08-17 18:44:35 +00004906 GFI = 0;
Chris Lattner84bc5422007-12-31 04:13:23 +00004907 RegInfo = &MF.getRegInfo();
Bill Wendling832171c2006-12-07 20:04:42 +00004908 DOUT << "\n\n\n=== " << Fn.getName() << "\n";
Chris Lattner1c08c712005-01-07 07:47:53 +00004909
4910 FunctionLoweringInfo FuncInfo(TLI, Fn, MF);
4911
Dale Johannesen1532f3d2008-04-02 00:25:04 +00004912 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
4913 if (InvokeInst *Invoke = dyn_cast<InvokeInst>(I->getTerminator()))
4914 // Mark landing pad.
4915 FuncInfo.MBBMap[Invoke->getSuccessor(1)]->setIsLandingPad();
Duncan Sands9fac0b52007-06-06 10:05:18 +00004916
Dan Gohman0e5f1302008-07-07 23:02:41 +00004917 SelectAllBasicBlocks(Fn, MF, FuncInfo);
Misha Brukmanedf128a2005-04-21 22:36:52 +00004918
Evan Chengad2070c2007-02-10 02:43:39 +00004919 // Add function live-ins to entry block live-in set.
4920 BasicBlock *EntryBB = &Fn.getEntryBlock();
4921 BB = FuncInfo.MBBMap[EntryBB];
Chris Lattner84bc5422007-12-31 04:13:23 +00004922 if (!RegInfo->livein_empty())
4923 for (MachineRegisterInfo::livein_iterator I = RegInfo->livein_begin(),
4924 E = RegInfo->livein_end(); I != E; ++I)
Evan Chengad2070c2007-02-10 02:43:39 +00004925 BB->addLiveIn(I->first);
4926
Duncan Sandsf4070822007-06-15 19:04:19 +00004927#ifndef NDEBUG
4928 assert(FuncInfo.CatchInfoFound.size() == FuncInfo.CatchInfoLost.size() &&
4929 "Not all catch info was assigned to a landing pad!");
4930#endif
4931
Chris Lattner1c08c712005-01-07 07:47:53 +00004932 return true;
4933}
4934
Chris Lattner6833b062008-04-28 07:16:35 +00004935void SelectionDAGLowering::CopyValueToVirtualRegister(Value *V, unsigned Reg) {
Dan Gohman475871a2008-07-27 21:46:04 +00004936 SDValue Op = getValue(V);
Chris Lattner18c2f132005-01-13 20:50:02 +00004937 assert((Op.getOpcode() != ISD::CopyFromReg ||
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00004938 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
Chris Lattner18c2f132005-01-13 20:50:02 +00004939 "Copy from a reg to the same reg!");
Dan Gohman86e1ebf2008-03-27 19:56:19 +00004940 assert(!TargetRegisterInfo::isPhysicalRegister(Reg) && "Is a physreg");
Dan Gohmanb6f5b002007-06-28 23:29:44 +00004941
Dan Gohman23ce5022008-04-25 18:27:55 +00004942 RegsForValue RFV(TLI, Reg, V->getType());
Dan Gohman475871a2008-07-27 21:46:04 +00004943 SDValue Chain = DAG.getEntryNode();
Dan Gohman23ce5022008-04-25 18:27:55 +00004944 RFV.getCopyToRegs(Op, DAG, Chain, 0);
4945 PendingExports.push_back(Chain);
Chris Lattner1c08c712005-01-07 07:47:53 +00004946}
4947
Chris Lattner068a81e2005-01-17 17:15:02 +00004948void SelectionDAGISel::
Dan Gohman86e1ebf2008-03-27 19:56:19 +00004949LowerArguments(BasicBlock *LLVMBB, SelectionDAGLowering &SDL) {
Chris Lattner068a81e2005-01-17 17:15:02 +00004950 // If this is the entry block, emit arguments.
Evan Cheng15699fc2007-02-10 01:08:18 +00004951 Function &F = *LLVMBB->getParent();
Chris Lattner0afa8e32005-01-17 17:55:19 +00004952 FunctionLoweringInfo &FuncInfo = SDL.FuncInfo;
Dan Gohman475871a2008-07-27 21:46:04 +00004953 SDValue OldRoot = SDL.DAG.getRoot();
4954 SmallVector<SDValue, 16> Args;
Dan Gohmana44b6742008-06-30 20:31:15 +00004955 TLI.LowerArguments(F, SDL.DAG, Args);
Chris Lattner068a81e2005-01-17 17:15:02 +00004956
Chris Lattnerbf209482005-10-30 19:42:35 +00004957 unsigned a = 0;
4958 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
Dan Gohmanf5025cf2008-06-09 21:19:23 +00004959 AI != E; ++AI) {
4960 SmallVector<MVT, 4> ValueVTs;
4961 ComputeValueVTs(TLI, AI->getType(), ValueVTs);
4962 unsigned NumValues = ValueVTs.size();
Chris Lattnerbf209482005-10-30 19:42:35 +00004963 if (!AI->use_empty()) {
Duncan Sands4bdcb612008-07-02 17:40:58 +00004964 SDL.setValue(AI, SDL.DAG.getMergeValues(&Args[a], NumValues));
Chris Lattnerbf209482005-10-30 19:42:35 +00004965 // If this argument is live outside of the entry block, insert a copy from
4966 // whereever we got it to the vreg that other BB's will reference it as.
Chris Lattner251db182007-02-25 18:40:32 +00004967 DenseMap<const Value*, unsigned>::iterator VMI=FuncInfo.ValueMap.find(AI);
4968 if (VMI != FuncInfo.ValueMap.end()) {
Dan Gohman86e1ebf2008-03-27 19:56:19 +00004969 SDL.CopyValueToVirtualRegister(AI, VMI->second);
Chris Lattnerbf209482005-10-30 19:42:35 +00004970 }
Chris Lattner0afa8e32005-01-17 17:55:19 +00004971 }
Dan Gohmanf5025cf2008-06-09 21:19:23 +00004972 a += NumValues;
4973 }
Chris Lattnerbf209482005-10-30 19:42:35 +00004974
Chris Lattnerbf209482005-10-30 19:42:35 +00004975 // Finally, if the target has anything special to do, allow it to do so.
Chris Lattner96645412006-05-16 06:10:58 +00004976 // FIXME: this should insert code into the DAG!
Chris Lattnerbf209482005-10-30 19:42:35 +00004977 EmitFunctionEntryCode(F, SDL.DAG.getMachineFunction());
Chris Lattner068a81e2005-01-17 17:15:02 +00004978}
4979
Duncan Sandsf4070822007-06-15 19:04:19 +00004980static void copyCatchInfo(BasicBlock *SrcBB, BasicBlock *DestBB,
4981 MachineModuleInfo *MMI, FunctionLoweringInfo &FLI) {
Duncan Sandsf4070822007-06-15 19:04:19 +00004982 for (BasicBlock::iterator I = SrcBB->begin(), E = --SrcBB->end(); I != E; ++I)
Duncan Sandscf26d7c2007-07-04 20:52:51 +00004983 if (isSelector(I)) {
Duncan Sandsf4070822007-06-15 19:04:19 +00004984 // Apply the catch info to DestBB.
4985 addCatchInfo(cast<CallInst>(*I), MMI, FLI.MBBMap[DestBB]);
4986#ifndef NDEBUG
Duncan Sands560a7372007-11-15 09:54:37 +00004987 if (!FLI.MBBMap[SrcBB]->isLandingPad())
4988 FLI.CatchInfoFound.insert(I);
Duncan Sandsf4070822007-06-15 19:04:19 +00004989#endif
4990 }
4991}
4992
Arnold Schwaighofer30e62c02008-04-30 09:16:33 +00004993/// IsFixedFrameObjectWithPosOffset - Check if object is a fixed frame object and
4994/// whether object offset >= 0.
4995static bool
Dan Gohman475871a2008-07-27 21:46:04 +00004996IsFixedFrameObjectWithPosOffset(MachineFrameInfo * MFI, SDValue Op) {
Arnold Schwaighofer30e62c02008-04-30 09:16:33 +00004997 if (!isa<FrameIndexSDNode>(Op)) return false;
4998
4999 FrameIndexSDNode * FrameIdxNode = dyn_cast<FrameIndexSDNode>(Op);
5000 int FrameIdx = FrameIdxNode->getIndex();
5001 return MFI->isFixedObjectIndex(FrameIdx) &&
5002 MFI->getObjectOffset(FrameIdx) >= 0;
5003}
5004
5005/// IsPossiblyOverwrittenArgumentOfTailCall - Check if the operand could
5006/// possibly be overwritten when lowering the outgoing arguments in a tail
5007/// call. Currently the implementation of this call is very conservative and
5008/// assumes all arguments sourcing from FORMAL_ARGUMENTS or a CopyFromReg with
5009/// virtual registers would be overwritten by direct lowering.
Dan Gohman475871a2008-07-27 21:46:04 +00005010static bool IsPossiblyOverwrittenArgumentOfTailCall(SDValue Op,
Arnold Schwaighofer30e62c02008-04-30 09:16:33 +00005011 MachineFrameInfo * MFI) {
5012 RegisterSDNode * OpReg = NULL;
5013 if (Op.getOpcode() == ISD::FORMAL_ARGUMENTS ||
5014 (Op.getOpcode()== ISD::CopyFromReg &&
5015 (OpReg = dyn_cast<RegisterSDNode>(Op.getOperand(1))) &&
5016 (OpReg->getReg() >= TargetRegisterInfo::FirstVirtualRegister)) ||
5017 (Op.getOpcode() == ISD::LOAD &&
5018 IsFixedFrameObjectWithPosOffset(MFI, Op.getOperand(1))) ||
5019 (Op.getOpcode() == ISD::MERGE_VALUES &&
5020 Op.getOperand(Op.ResNo).getOpcode() == ISD::LOAD &&
5021 IsFixedFrameObjectWithPosOffset(MFI, Op.getOperand(Op.ResNo).
5022 getOperand(1))))
5023 return true;
5024 return false;
5025}
5026
Arnold Schwaighoferc85e1712007-10-11 19:40:01 +00005027/// CheckDAGForTailCallsAndFixThem - This Function looks for CALL nodes in the
Arnold Schwaighofer48abc5c2007-10-12 21:30:57 +00005028/// DAG and fixes their tailcall attribute operand.
Arnold Schwaighoferc85e1712007-10-11 19:40:01 +00005029static void CheckDAGForTailCallsAndFixThem(SelectionDAG &DAG,
5030 TargetLowering& TLI) {
5031 SDNode * Ret = NULL;
Dan Gohman475871a2008-07-27 21:46:04 +00005032 SDValue Terminator = DAG.getRoot();
Arnold Schwaighoferc85e1712007-10-11 19:40:01 +00005033
5034 // Find RET node.
5035 if (Terminator.getOpcode() == ISD::RET) {
5036 Ret = Terminator.Val;
5037 }
5038
5039 // Fix tail call attribute of CALL nodes.
5040 for (SelectionDAG::allnodes_iterator BE = DAG.allnodes_begin(),
Dan Gohman0e5f1302008-07-07 23:02:41 +00005041 BI = DAG.allnodes_end(); BI != BE; ) {
5042 --BI;
Arnold Schwaighoferc85e1712007-10-11 19:40:01 +00005043 if (BI->getOpcode() == ISD::CALL) {
Dan Gohman475871a2008-07-27 21:46:04 +00005044 SDValue OpRet(Ret, 0);
5045 SDValue OpCall(BI, 0);
Arnold Schwaighoferc85e1712007-10-11 19:40:01 +00005046 bool isMarkedTailCall =
5047 cast<ConstantSDNode>(OpCall.getOperand(3))->getValue() != 0;
5048 // If CALL node has tail call attribute set to true and the call is not
5049 // eligible (no RET or the target rejects) the attribute is fixed to
Arnold Schwaighofer48abc5c2007-10-12 21:30:57 +00005050 // false. The TargetLowering::IsEligibleForTailCallOptimization function
Arnold Schwaighoferc85e1712007-10-11 19:40:01 +00005051 // must correctly identify tail call optimizable calls.
Arnold Schwaighofer30e62c02008-04-30 09:16:33 +00005052 if (!isMarkedTailCall) continue;
5053 if (Ret==NULL ||
5054 !TLI.IsEligibleForTailCallOptimization(OpCall, OpRet, DAG)) {
5055 // Not eligible. Mark CALL node as non tail call.
Dan Gohman475871a2008-07-27 21:46:04 +00005056 SmallVector<SDValue, 32> Ops;
Arnold Schwaighoferc85e1712007-10-11 19:40:01 +00005057 unsigned idx=0;
Arnold Schwaighofer30e62c02008-04-30 09:16:33 +00005058 for(SDNode::op_iterator I =OpCall.Val->op_begin(),
5059 E = OpCall.Val->op_end(); I != E; I++, idx++) {
Arnold Schwaighoferc85e1712007-10-11 19:40:01 +00005060 if (idx!=3)
5061 Ops.push_back(*I);
Arnold Schwaighofer30e62c02008-04-30 09:16:33 +00005062 else
Arnold Schwaighoferc85e1712007-10-11 19:40:01 +00005063 Ops.push_back(DAG.getConstant(false, TLI.getPointerTy()));
5064 }
5065 DAG.UpdateNodeOperands(OpCall, Ops.begin(), Ops.size());
Arnold Schwaighofer30e62c02008-04-30 09:16:33 +00005066 } else {
5067 // Look for tail call clobbered arguments. Emit a series of
5068 // copyto/copyfrom virtual register nodes to protect them.
Dan Gohman475871a2008-07-27 21:46:04 +00005069 SmallVector<SDValue, 32> Ops;
5070 SDValue Chain = OpCall.getOperand(0), InFlag;
Arnold Schwaighofer30e62c02008-04-30 09:16:33 +00005071 unsigned idx=0;
5072 for(SDNode::op_iterator I = OpCall.Val->op_begin(),
5073 E = OpCall.Val->op_end(); I != E; I++, idx++) {
Dan Gohman475871a2008-07-27 21:46:04 +00005074 SDValue Arg = *I;
Arnold Schwaighofer30e62c02008-04-30 09:16:33 +00005075 if (idx > 4 && (idx % 2)) {
5076 bool isByVal = cast<ARG_FLAGSSDNode>(OpCall.getOperand(idx+1))->
5077 getArgFlags().isByVal();
5078 MachineFunction &MF = DAG.getMachineFunction();
5079 MachineFrameInfo *MFI = MF.getFrameInfo();
5080 if (!isByVal &&
5081 IsPossiblyOverwrittenArgumentOfTailCall(Arg, MFI)) {
Duncan Sands83ec4b62008-06-06 12:08:01 +00005082 MVT VT = Arg.getValueType();
Arnold Schwaighofer30e62c02008-04-30 09:16:33 +00005083 unsigned VReg = MF.getRegInfo().
5084 createVirtualRegister(TLI.getRegClassFor(VT));
5085 Chain = DAG.getCopyToReg(Chain, VReg, Arg, InFlag);
5086 InFlag = Chain.getValue(1);
5087 Arg = DAG.getCopyFromReg(Chain, VReg, VT, InFlag);
5088 Chain = Arg.getValue(1);
5089 InFlag = Arg.getValue(2);
5090 }
5091 }
5092 Ops.push_back(Arg);
5093 }
5094 // Link in chain of CopyTo/CopyFromReg.
5095 Ops[0] = Chain;
5096 DAG.UpdateNodeOperands(OpCall, Ops.begin(), Ops.size());
Arnold Schwaighoferc85e1712007-10-11 19:40:01 +00005097 }
5098 }
5099 }
5100}
5101
Dan Gohmanf350b272008-08-23 02:25:05 +00005102/// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
5103/// ensure constants are generated when needed. Remember the virtual registers
5104/// that need to be added to the Machine PHI nodes as input. We cannot just
5105/// directly add them, because expansion might result in multiple MBB's for one
5106/// BB. As such, the start of the BB might correspond to a different MBB than
5107/// the end.
5108///
5109void
5110SelectionDAGISel::HandlePHINodesInSuccessorBlocks(BasicBlock *LLVMBB,
5111 FunctionLoweringInfo &FuncInfo,
5112 std::vector<std::pair<MachineInstr*, unsigned> > &PHINodesToUpdate,
5113 SelectionDAGLowering &SDL) {
Chris Lattner8c494ab2006-10-27 23:50:33 +00005114 TerminatorInst *TI = LLVMBB->getTerminator();
Chris Lattner1c08c712005-01-07 07:47:53 +00005115
5116 // Emit constants only once even if used by multiple PHI nodes.
5117 std::map<Constant*, unsigned> ConstantsOut;
Chris Lattnerd5e93c02006-09-07 01:59:34 +00005118
Dan Gohmanc53ec492008-08-20 14:58:41 +00005119 BitVector SuccsHandled;
Chris Lattner8c494ab2006-10-27 23:50:33 +00005120 if (TI->getNumSuccessors())
5121 SuccsHandled.resize(BB->getParent()->getNumBlockIDs());
5122
Dan Gohman532dc2e2007-07-09 20:59:04 +00005123 // Check successor nodes' PHI nodes that expect a constant to be available
5124 // from this block.
Chris Lattner1c08c712005-01-07 07:47:53 +00005125 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
5126 BasicBlock *SuccBB = TI->getSuccessor(succ);
Chris Lattnerd5e93c02006-09-07 01:59:34 +00005127 if (!isa<PHINode>(SuccBB->begin())) continue;
Chris Lattner8c494ab2006-10-27 23:50:33 +00005128 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
Chris Lattnerd5e93c02006-09-07 01:59:34 +00005129
Chris Lattner8c494ab2006-10-27 23:50:33 +00005130 // If this terminator has multiple identical successors (common for
5131 // switches), only handle each succ once.
5132 unsigned SuccMBBNo = SuccMBB->getNumber();
5133 if (SuccsHandled[SuccMBBNo]) continue;
5134 SuccsHandled[SuccMBBNo] = true;
5135
5136 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
Chris Lattner1c08c712005-01-07 07:47:53 +00005137 PHINode *PN;
5138
5139 // At this point we know that there is a 1-1 correspondence between LLVM PHI
5140 // nodes and Machine PHI nodes, but the incoming operands have not been
5141 // emitted yet.
5142 for (BasicBlock::iterator I = SuccBB->begin();
Chris Lattner8c494ab2006-10-27 23:50:33 +00005143 (PN = dyn_cast<PHINode>(I)); ++I) {
5144 // Ignore dead phi's.
5145 if (PN->use_empty()) continue;
5146
5147 unsigned Reg;
5148 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
Chris Lattner3f7927c2006-11-29 01:12:32 +00005149
Chris Lattner8c494ab2006-10-27 23:50:33 +00005150 if (Constant *C = dyn_cast<Constant>(PHIOp)) {
5151 unsigned &RegOut = ConstantsOut[C];
5152 if (RegOut == 0) {
5153 RegOut = FuncInfo.CreateRegForValue(C);
Dan Gohman86e1ebf2008-03-27 19:56:19 +00005154 SDL.CopyValueToVirtualRegister(C, RegOut);
Chris Lattner1c08c712005-01-07 07:47:53 +00005155 }
Chris Lattner8c494ab2006-10-27 23:50:33 +00005156 Reg = RegOut;
5157 } else {
5158 Reg = FuncInfo.ValueMap[PHIOp];
5159 if (Reg == 0) {
5160 assert(isa<AllocaInst>(PHIOp) &&
5161 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
5162 "Didn't codegen value into a register!??");
5163 Reg = FuncInfo.CreateRegForValue(PHIOp);
Dan Gohman86e1ebf2008-03-27 19:56:19 +00005164 SDL.CopyValueToVirtualRegister(PHIOp, Reg);
Chris Lattner7e021512006-03-31 02:12:18 +00005165 }
Chris Lattner1c08c712005-01-07 07:47:53 +00005166 }
Chris Lattner8c494ab2006-10-27 23:50:33 +00005167
5168 // Remember that this register needs to added to the machine PHI node as
5169 // the input for this MBB.
Dan Gohman6f498b02008-08-04 23:42:46 +00005170 SmallVector<MVT, 4> ValueVTs;
5171 ComputeValueVTs(TLI, PN->getType(), ValueVTs);
5172 for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
5173 MVT VT = ValueVTs[vti];
5174 unsigned NumRegisters = TLI.getNumRegisters(VT);
5175 for (unsigned i = 0, e = NumRegisters; i != e; ++i)
5176 PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
5177 Reg += NumRegisters;
5178 }
Chris Lattner8c494ab2006-10-27 23:50:33 +00005179 }
Chris Lattner1c08c712005-01-07 07:47:53 +00005180 }
5181 ConstantsOut.clear();
5182
5183 // Lower the terminator after the copies are emitted.
Duncan Sandsf19f6bb2007-06-13 05:51:31 +00005184 SDL.visit(*LLVMBB->getTerminator());
Chris Lattnera651cf62005-01-17 19:43:36 +00005185
Nate Begemanf15485a2006-03-27 01:32:24 +00005186 // Copy over any CaseBlock records that may now exist due to SwitchInst
Nate Begeman37efe672006-04-22 18:53:45 +00005187 // lowering, as well as any jump table information.
Nate Begemanf15485a2006-03-27 01:32:24 +00005188 SwitchCases.clear();
5189 SwitchCases = SDL.SwitchCases;
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00005190 JTCases.clear();
5191 JTCases = SDL.JTCases;
Anton Korobeynikov4198c582007-04-09 12:31:58 +00005192 BitTestCases.clear();
5193 BitTestCases = SDL.BitTestCases;
Dan Gohmanf350b272008-08-23 02:25:05 +00005194}
5195
5196void SelectionDAGISel::SelectBasicBlock(BasicBlock *LLVMBB,
5197 BasicBlock::iterator Begin,
5198 BasicBlock::iterator End,
5199 bool DoArgs,
5200 std::vector<std::pair<MachineInstr*, unsigned> > &PHINodesToUpdate,
5201 FunctionLoweringInfo &FuncInfo) {
5202 SelectionDAGLowering SDL(*CurDAG, TLI, *AA, FuncInfo, GFI);
5203
5204 // Lower any arguments needed in this block if this is the entry block.
5205 if (DoArgs)
5206 LowerArguments(LLVMBB, SDL);
5207
5208 SDL.setCurrentBasicBlock(BB);
5209
5210 MachineModuleInfo *MMI = CurDAG->getMachineModuleInfo();
5211
5212 if (MMI && BB->isLandingPad()) {
5213 // Add a label to mark the beginning of the landing pad. Deletion of the
5214 // landing pad can thus be detected via the MachineModuleInfo.
5215 unsigned LabelID = MMI->addLandingPad(BB);
5216 CurDAG->setRoot(CurDAG->getLabel(ISD::EH_LABEL,
5217 CurDAG->getEntryNode(), LabelID));
5218
5219 // Mark exception register as live in.
5220 unsigned Reg = TLI.getExceptionAddressRegister();
5221 if (Reg) BB->addLiveIn(Reg);
5222
5223 // Mark exception selector register as live in.
5224 Reg = TLI.getExceptionSelectorRegister();
5225 if (Reg) BB->addLiveIn(Reg);
5226
5227 // FIXME: Hack around an exception handling flaw (PR1508): the personality
5228 // function and list of typeids logically belong to the invoke (or, if you
5229 // like, the basic block containing the invoke), and need to be associated
5230 // with it in the dwarf exception handling tables. Currently however the
5231 // information is provided by an intrinsic (eh.selector) that can be moved
5232 // to unexpected places by the optimizers: if the unwind edge is critical,
5233 // then breaking it can result in the intrinsics being in the successor of
5234 // the landing pad, not the landing pad itself. This results in exceptions
5235 // not being caught because no typeids are associated with the invoke.
5236 // This may not be the only way things can go wrong, but it is the only way
5237 // we try to work around for the moment.
5238 BranchInst *Br = dyn_cast<BranchInst>(LLVMBB->getTerminator());
5239
5240 if (Br && Br->isUnconditional()) { // Critical edge?
5241 BasicBlock::iterator I, E;
5242 for (I = LLVMBB->begin(), E = --LLVMBB->end(); I != E; ++I)
5243 if (isSelector(I))
5244 break;
5245
5246 if (I == E)
5247 // No catch info found - try to extract some from the successor.
5248 copyCatchInfo(Br->getSuccessor(0), LLVMBB, MMI, FuncInfo);
5249 }
5250 }
5251
5252 // Lower all of the non-terminator instructions.
5253 for (BasicBlock::iterator I = Begin; I != End; ++I)
5254 if (!isa<TerminatorInst>(I))
5255 SDL.visit(*I);
5256
5257 // Ensure that all instructions which are used outside of their defining
5258 // blocks are available as virtual registers. Invoke is handled elsewhere.
5259 for (BasicBlock::iterator I = Begin; I != End; ++I)
5260 if (!I->use_empty() && !isa<PHINode>(I) && !isa<InvokeInst>(I)) {
5261 DenseMap<const Value*, unsigned>::iterator VMI =FuncInfo.ValueMap.find(I);
5262 if (VMI != FuncInfo.ValueMap.end())
5263 SDL.CopyValueToVirtualRegister(I, VMI->second);
5264 }
5265
5266 // Handle PHI nodes in successor blocks.
5267 if (Begin != End && End == LLVMBB->end())
5268 HandlePHINodesInSuccessorBlocks(LLVMBB, FuncInfo, PHINodesToUpdate, SDL);
Anton Korobeynikov4198c582007-04-09 12:31:58 +00005269
Chris Lattnera651cf62005-01-17 19:43:36 +00005270 // Make sure the root of the DAG is up-to-date.
Dan Gohmanf350b272008-08-23 02:25:05 +00005271 CurDAG->setRoot(SDL.getControlRoot());
Arnold Schwaighoferc85e1712007-10-11 19:40:01 +00005272
5273 // Check whether calls in this block are real tail calls. Fix up CALL nodes
5274 // with correct tailcall attribute so that the target can rely on the tailcall
5275 // attribute indicating whether the call is really eligible for tail call
5276 // optimization.
Dan Gohmanf350b272008-08-23 02:25:05 +00005277 CheckDAGForTailCallsAndFixThem(*CurDAG, TLI);
5278
5279 // Final step, emit the lowered DAG as machine code.
5280 CodeGenAndEmitDAG();
5281 CurDAG->reset();
Chris Lattner1c08c712005-01-07 07:47:53 +00005282}
5283
Dan Gohmanf350b272008-08-23 02:25:05 +00005284void SelectionDAGISel::ComputeLiveOutVRegInfo() {
Chris Lattneread0d882008-06-17 06:09:18 +00005285 SmallPtrSet<SDNode*, 128> VisitedNodes;
5286 SmallVector<SDNode*, 128> Worklist;
5287
Dan Gohmanf350b272008-08-23 02:25:05 +00005288 Worklist.push_back(CurDAG->getRoot().Val);
Chris Lattneread0d882008-06-17 06:09:18 +00005289
5290 APInt Mask;
5291 APInt KnownZero;
5292 APInt KnownOne;
5293
5294 while (!Worklist.empty()) {
5295 SDNode *N = Worklist.back();
5296 Worklist.pop_back();
5297
5298 // If we've already seen this node, ignore it.
5299 if (!VisitedNodes.insert(N))
5300 continue;
5301
5302 // Otherwise, add all chain operands to the worklist.
5303 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
5304 if (N->getOperand(i).getValueType() == MVT::Other)
5305 Worklist.push_back(N->getOperand(i).Val);
5306
5307 // If this is a CopyToReg with a vreg dest, process it.
5308 if (N->getOpcode() != ISD::CopyToReg)
5309 continue;
5310
5311 unsigned DestReg = cast<RegisterSDNode>(N->getOperand(1))->getReg();
5312 if (!TargetRegisterInfo::isVirtualRegister(DestReg))
5313 continue;
5314
5315 // Ignore non-scalar or non-integer values.
Dan Gohman475871a2008-07-27 21:46:04 +00005316 SDValue Src = N->getOperand(2);
Chris Lattneread0d882008-06-17 06:09:18 +00005317 MVT SrcVT = Src.getValueType();
5318 if (!SrcVT.isInteger() || SrcVT.isVector())
5319 continue;
5320
Dan Gohmanf350b272008-08-23 02:25:05 +00005321 unsigned NumSignBits = CurDAG->ComputeNumSignBits(Src);
Chris Lattneread0d882008-06-17 06:09:18 +00005322 Mask = APInt::getAllOnesValue(SrcVT.getSizeInBits());
Dan Gohmanf350b272008-08-23 02:25:05 +00005323 CurDAG->ComputeMaskedBits(Src, Mask, KnownZero, KnownOne);
Chris Lattneread0d882008-06-17 06:09:18 +00005324
5325 // Only install this information if it tells us something.
5326 if (NumSignBits != 1 || KnownZero != 0 || KnownOne != 0) {
5327 DestReg -= TargetRegisterInfo::FirstVirtualRegister;
Dan Gohmanf350b272008-08-23 02:25:05 +00005328 FunctionLoweringInfo &FLI = CurDAG->getFunctionLoweringInfo();
Chris Lattneread0d882008-06-17 06:09:18 +00005329 if (DestReg >= FLI.LiveOutRegInfo.size())
5330 FLI.LiveOutRegInfo.resize(DestReg+1);
5331 FunctionLoweringInfo::LiveOutInfo &LOI = FLI.LiveOutRegInfo[DestReg];
5332 LOI.NumSignBits = NumSignBits;
5333 LOI.KnownOne = NumSignBits;
5334 LOI.KnownZero = NumSignBits;
5335 }
5336 }
5337}
5338
Dan Gohmanf350b272008-08-23 02:25:05 +00005339void SelectionDAGISel::CodeGenAndEmitDAG() {
Dan Gohman462dc7f2008-07-21 20:00:07 +00005340 std::string GroupName;
5341 if (TimePassesIsEnabled)
5342 GroupName = "Instruction Selection and Scheduling";
5343 std::string BlockName;
5344 if (ViewDAGCombine1 || ViewLegalizeTypesDAGs || ViewLegalizeDAGs ||
5345 ViewDAGCombine2 || ViewISelDAGs || ViewSchedDAGs || ViewSUnitDAGs)
Dan Gohmanf350b272008-08-23 02:25:05 +00005346 BlockName = CurDAG->getMachineFunction().getFunction()->getName() + ':' +
Dan Gohman462dc7f2008-07-21 20:00:07 +00005347 BB->getBasicBlock()->getName();
5348
5349 DOUT << "Initial selection DAG:\n";
Dan Gohmanf350b272008-08-23 02:25:05 +00005350 DEBUG(CurDAG->dump());
Dan Gohman462dc7f2008-07-21 20:00:07 +00005351
Dan Gohmanf350b272008-08-23 02:25:05 +00005352 if (ViewDAGCombine1) CurDAG->viewGraph("dag-combine1 input for " + BlockName);
Dan Gohman417e11b2007-10-08 15:12:17 +00005353
Chris Lattneraf21d552005-10-10 16:47:10 +00005354 // Run the DAG combiner in pre-legalize mode.
Evan Chengebffb662008-07-01 17:59:20 +00005355 if (TimePassesIsEnabled) {
Dan Gohman5e843682008-07-14 18:19:29 +00005356 NamedRegionTimer T("DAG Combining 1", GroupName);
Dan Gohmanf350b272008-08-23 02:25:05 +00005357 CurDAG->Combine(false, *AA, Fast);
Evan Chengebffb662008-07-01 17:59:20 +00005358 } else {
Dan Gohmanf350b272008-08-23 02:25:05 +00005359 CurDAG->Combine(false, *AA, Fast);
Evan Chengebffb662008-07-01 17:59:20 +00005360 }
Nate Begeman2300f552005-09-07 00:15:36 +00005361
Dan Gohman417e11b2007-10-08 15:12:17 +00005362 DOUT << "Optimized lowered selection DAG:\n";
Dan Gohmanf350b272008-08-23 02:25:05 +00005363 DEBUG(CurDAG->dump());
Duncan Sandsf00e74f2008-07-17 17:06:03 +00005364
Chris Lattner1c08c712005-01-07 07:47:53 +00005365 // Second step, hack on the DAG until it only uses operations and types that
5366 // the target supports.
Duncan Sandsf00e74f2008-07-17 17:06:03 +00005367 if (EnableLegalizeTypes) {// Enable this some day.
Dan Gohmanf350b272008-08-23 02:25:05 +00005368 if (ViewLegalizeTypesDAGs) CurDAG->viewGraph("legalize-types input for " +
5369 BlockName);
Dan Gohman462dc7f2008-07-21 20:00:07 +00005370
5371 if (TimePassesIsEnabled) {
5372 NamedRegionTimer T("Type Legalization", GroupName);
Dan Gohmanf350b272008-08-23 02:25:05 +00005373 CurDAG->LegalizeTypes();
Dan Gohman462dc7f2008-07-21 20:00:07 +00005374 } else {
Dan Gohmanf350b272008-08-23 02:25:05 +00005375 CurDAG->LegalizeTypes();
Dan Gohman462dc7f2008-07-21 20:00:07 +00005376 }
5377
5378 DOUT << "Type-legalized selection DAG:\n";
Dan Gohmanf350b272008-08-23 02:25:05 +00005379 DEBUG(CurDAG->dump());
Dan Gohman462dc7f2008-07-21 20:00:07 +00005380
Chris Lattner70587ea2008-07-10 23:37:50 +00005381 // TODO: enable a dag combine pass here.
5382 }
Duncan Sandsf00e74f2008-07-17 17:06:03 +00005383
Dan Gohmanf350b272008-08-23 02:25:05 +00005384 if (ViewLegalizeDAGs) CurDAG->viewGraph("legalize input for " + BlockName);
Dan Gohman462dc7f2008-07-21 20:00:07 +00005385
Evan Chengebffb662008-07-01 17:59:20 +00005386 if (TimePassesIsEnabled) {
Dan Gohman5e843682008-07-14 18:19:29 +00005387 NamedRegionTimer T("DAG Legalization", GroupName);
Dan Gohmanf350b272008-08-23 02:25:05 +00005388 CurDAG->Legalize();
Evan Chengebffb662008-07-01 17:59:20 +00005389 } else {
Dan Gohmanf350b272008-08-23 02:25:05 +00005390 CurDAG->Legalize();
Evan Chengebffb662008-07-01 17:59:20 +00005391 }
Nate Begemanf15485a2006-03-27 01:32:24 +00005392
Bill Wendling832171c2006-12-07 20:04:42 +00005393 DOUT << "Legalized selection DAG:\n";
Dan Gohmanf350b272008-08-23 02:25:05 +00005394 DEBUG(CurDAG->dump());
Nate Begemanf15485a2006-03-27 01:32:24 +00005395
Dan Gohmanf350b272008-08-23 02:25:05 +00005396 if (ViewDAGCombine2) CurDAG->viewGraph("dag-combine2 input for " + BlockName);
Dan Gohman462dc7f2008-07-21 20:00:07 +00005397
Chris Lattneraf21d552005-10-10 16:47:10 +00005398 // Run the DAG combiner in post-legalize mode.
Evan Chengebffb662008-07-01 17:59:20 +00005399 if (TimePassesIsEnabled) {
Dan Gohman5e843682008-07-14 18:19:29 +00005400 NamedRegionTimer T("DAG Combining 2", GroupName);
Dan Gohmanf350b272008-08-23 02:25:05 +00005401 CurDAG->Combine(true, *AA, Fast);
Evan Chengebffb662008-07-01 17:59:20 +00005402 } else {
Dan Gohmanf350b272008-08-23 02:25:05 +00005403 CurDAG->Combine(true, *AA, Fast);
Evan Chengebffb662008-07-01 17:59:20 +00005404 }
Nate Begeman2300f552005-09-07 00:15:36 +00005405
Dan Gohman417e11b2007-10-08 15:12:17 +00005406 DOUT << "Optimized legalized selection DAG:\n";
Dan Gohmanf350b272008-08-23 02:25:05 +00005407 DEBUG(CurDAG->dump());
Dan Gohman417e11b2007-10-08 15:12:17 +00005408
Dan Gohmanf350b272008-08-23 02:25:05 +00005409 if (ViewISelDAGs) CurDAG->viewGraph("isel input for " + BlockName);
Chris Lattneread0d882008-06-17 06:09:18 +00005410
Dan Gohman925a7e82008-08-13 19:47:40 +00005411 if (!Fast && EnableValueProp)
Dan Gohmanf350b272008-08-23 02:25:05 +00005412 ComputeLiveOutVRegInfo();
Evan Cheng552c4a82006-04-28 02:09:19 +00005413
Chris Lattnera33ef482005-03-30 01:10:47 +00005414 // Third, instruction select all of the operations to machine code, adding the
5415 // code to the MachineBasicBlock.
Evan Chengebffb662008-07-01 17:59:20 +00005416 if (TimePassesIsEnabled) {
Dan Gohman5e843682008-07-14 18:19:29 +00005417 NamedRegionTimer T("Instruction Selection", GroupName);
Dan Gohmanf350b272008-08-23 02:25:05 +00005418 InstructionSelect();
Evan Chengebffb662008-07-01 17:59:20 +00005419 } else {
Dan Gohmanf350b272008-08-23 02:25:05 +00005420 InstructionSelect();
Evan Chengebffb662008-07-01 17:59:20 +00005421 }
Evan Chengdb8d56b2008-06-30 20:45:06 +00005422
Dan Gohman462dc7f2008-07-21 20:00:07 +00005423 DOUT << "Selected selection DAG:\n";
Dan Gohmanf350b272008-08-23 02:25:05 +00005424 DEBUG(CurDAG->dump());
Dan Gohman462dc7f2008-07-21 20:00:07 +00005425
Dan Gohmanf350b272008-08-23 02:25:05 +00005426 if (ViewSchedDAGs) CurDAG->viewGraph("scheduler input for " + BlockName);
Dan Gohman462dc7f2008-07-21 20:00:07 +00005427
Dan Gohman5e843682008-07-14 18:19:29 +00005428 // Schedule machine code.
5429 ScheduleDAG *Scheduler;
5430 if (TimePassesIsEnabled) {
5431 NamedRegionTimer T("Instruction Scheduling", GroupName);
Dan Gohmanf350b272008-08-23 02:25:05 +00005432 Scheduler = Schedule();
Dan Gohman5e843682008-07-14 18:19:29 +00005433 } else {
Dan Gohmanf350b272008-08-23 02:25:05 +00005434 Scheduler = Schedule();
Dan Gohman5e843682008-07-14 18:19:29 +00005435 }
5436
Dan Gohman462dc7f2008-07-21 20:00:07 +00005437 if (ViewSUnitDAGs) Scheduler->viewGraph();
5438
Evan Chengdb8d56b2008-06-30 20:45:06 +00005439 // Emit machine code to BB. This can change 'BB' to the last block being
5440 // inserted into.
Evan Chengebffb662008-07-01 17:59:20 +00005441 if (TimePassesIsEnabled) {
Dan Gohman5e843682008-07-14 18:19:29 +00005442 NamedRegionTimer T("Instruction Creation", GroupName);
5443 BB = Scheduler->EmitSchedule();
Evan Chengebffb662008-07-01 17:59:20 +00005444 } else {
Dan Gohman5e843682008-07-14 18:19:29 +00005445 BB = Scheduler->EmitSchedule();
5446 }
5447
5448 // Free the scheduler state.
5449 if (TimePassesIsEnabled) {
5450 NamedRegionTimer T("Instruction Scheduling Cleanup", GroupName);
5451 delete Scheduler;
5452 } else {
5453 delete Scheduler;
Evan Chengebffb662008-07-01 17:59:20 +00005454 }
Evan Chengdb8d56b2008-06-30 20:45:06 +00005455
Bill Wendling832171c2006-12-07 20:04:42 +00005456 DOUT << "Selected machine code:\n";
Chris Lattner1c08c712005-01-07 07:47:53 +00005457 DEBUG(BB->dump());
Nate Begemanf15485a2006-03-27 01:32:24 +00005458}
Chris Lattner1c08c712005-01-07 07:47:53 +00005459
Dan Gohman0e5f1302008-07-07 23:02:41 +00005460void SelectionDAGISel::SelectAllBasicBlocks(Function &Fn, MachineFunction &MF,
5461 FunctionLoweringInfo &FuncInfo) {
Dan Gohmanf350b272008-08-23 02:25:05 +00005462 // Define the SelectionDAG here so that memory allocation is reused for
Dan Gohman0e5f1302008-07-07 23:02:41 +00005463 // each basic block.
Dan Gohmanf350b272008-08-23 02:25:05 +00005464 SelectionDAG DAG(TLI, MF, FuncInfo,
5465 getAnalysisToUpdate<MachineModuleInfo>());
5466 CurDAG = &DAG;
Dan Gohman0e5f1302008-07-07 23:02:41 +00005467
Evan Cheng39fd6e82008-08-07 00:43:25 +00005468 std::vector<std::pair<MachineInstr*, unsigned> > PHINodesToUpdate;
5469 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I) {
5470 BasicBlock *LLVMBB = &*I;
Dan Gohmanf350b272008-08-23 02:25:05 +00005471 BB = FuncInfo.MBBMap[LLVMBB];
5472
5473 BasicBlock::iterator Begin = LLVMBB->begin();
5474 BasicBlock::iterator End = LLVMBB->end();
5475 bool DoArgs = LLVMBB == &Fn.getEntryBlock();
5476
5477 // Before doing SelectionDAG ISel, see if FastISel has been requested.
5478 // FastISel doesn't support EH landing pads, which require special handling.
5479 if (EnableFastISel && !BB->isLandingPad()) {
5480 if (FastISel *F = TLI.createFastISel(FuncInfo.MF)) {
5481 while (Begin != End) {
5482 Begin = F->SelectInstructions(Begin, End, FuncInfo.ValueMap,
5483 FuncInfo.MBBMap, BB);
5484
5485 if (Begin == End)
5486 // The "fast" selector selected the entire block, so we're done.
5487 break;
5488
5489 // Handle certain instructions as single-LLVM-Instruction blocks.
5490 if (isa<CallInst>(Begin) || isa<LoadInst>(Begin) ||
5491 isa<StoreInst>(Begin)) {
5492 if (Begin->getType() != Type::VoidTy) {
5493 unsigned &R = FuncInfo.ValueMap[Begin];
5494 if (!R)
5495 R = FuncInfo.CreateRegForValue(Begin);
5496 }
5497
5498 SelectBasicBlock(LLVMBB, Begin, next(Begin), DoArgs,
5499 PHINodesToUpdate, FuncInfo);
5500
5501 ++Begin;
5502 DoArgs = false;
5503 continue;
5504 }
5505
5506 if (!DisableFastISelAbort &&
5507 // For now, don't abort on non-conditional-branch terminators.
5508 (!isa<TerminatorInst>(Begin) ||
5509 (isa<BranchInst>(Begin) &&
5510 cast<BranchInst>(Begin)->isUnconditional()))) {
5511 // The "fast" selector couldn't handle something and bailed.
5512 // For the purpose of debugging, just abort.
5513#ifndef NDEBUG
5514 Begin->dump();
5515#endif
5516 assert(0 && "FastISel didn't select the entire block");
5517 }
5518 break;
5519 }
5520 delete F;
5521 }
5522 }
5523
5524 if (Begin != End || DoArgs)
5525 SelectBasicBlock(LLVMBB, Begin, End, DoArgs, PHINodesToUpdate, FuncInfo);
5526
5527 FinishBasicBlock(FuncInfo, PHINodesToUpdate);
Evan Cheng39fd6e82008-08-07 00:43:25 +00005528 PHINodesToUpdate.clear();
Evan Cheng39fd6e82008-08-07 00:43:25 +00005529 }
Dan Gohmanf350b272008-08-23 02:25:05 +00005530
5531 CurDAG = 0;
Dan Gohman0e5f1302008-07-07 23:02:41 +00005532}
5533
Dan Gohmanfed90b62008-07-28 21:51:04 +00005534void
Dan Gohmanf350b272008-08-23 02:25:05 +00005535SelectionDAGISel::FinishBasicBlock(FunctionLoweringInfo &FuncInfo,
5536 std::vector<std::pair<MachineInstr*, unsigned> > &PHINodesToUpdate) {
5537
5538 // Perform target specific isel post processing.
5539 InstructionSelectPostProcessing();
Nate Begemanf15485a2006-03-27 01:32:24 +00005540
Dan Gohmanf350b272008-08-23 02:25:05 +00005541 DOUT << "Target-post-processed machine code:\n";
5542 DEBUG(BB->dump());
Nate Begemanf15485a2006-03-27 01:32:24 +00005543
Anton Korobeynikov4198c582007-04-09 12:31:58 +00005544 DOUT << "Total amount of phi nodes to update: "
5545 << PHINodesToUpdate.size() << "\n";
5546 DEBUG(for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i)
5547 DOUT << "Node " << i << " : (" << PHINodesToUpdate[i].first
5548 << ", " << PHINodesToUpdate[i].second << ")\n";);
Nate Begemanf15485a2006-03-27 01:32:24 +00005549
Chris Lattnera33ef482005-03-30 01:10:47 +00005550 // Next, now that we know what the last MBB the LLVM BB expanded is, update
Chris Lattner1c08c712005-01-07 07:47:53 +00005551 // PHI nodes in successors.
Anton Korobeynikov4198c582007-04-09 12:31:58 +00005552 if (SwitchCases.empty() && JTCases.empty() && BitTestCases.empty()) {
Nate Begemanf15485a2006-03-27 01:32:24 +00005553 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
5554 MachineInstr *PHI = PHINodesToUpdate[i].first;
5555 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
5556 "This is not a machine PHI node that we are updating!");
Chris Lattner9ce2e9d2007-12-30 00:57:42 +00005557 PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[i].second,
5558 false));
5559 PHI->addOperand(MachineOperand::CreateMBB(BB));
Nate Begemanf15485a2006-03-27 01:32:24 +00005560 }
5561 return;
Chris Lattner1c08c712005-01-07 07:47:53 +00005562 }
Anton Korobeynikov4198c582007-04-09 12:31:58 +00005563
5564 for (unsigned i = 0, e = BitTestCases.size(); i != e; ++i) {
5565 // Lower header first, if it wasn't already lowered
5566 if (!BitTestCases[i].Emitted) {
Dan Gohmanf350b272008-08-23 02:25:05 +00005567 SelectionDAGLowering HSDL(*CurDAG, TLI, *AA, FuncInfo, GFI);
Anton Korobeynikov4198c582007-04-09 12:31:58 +00005568 // Set the current basic block to the mbb we wish to insert the code into
5569 BB = BitTestCases[i].Parent;
5570 HSDL.setCurrentBasicBlock(BB);
5571 // Emit the code
5572 HSDL.visitBitTestHeader(BitTestCases[i]);
Dan Gohmanf350b272008-08-23 02:25:05 +00005573 CurDAG->setRoot(HSDL.getRoot());
5574 CodeGenAndEmitDAG();
5575 CurDAG->reset();
Anton Korobeynikov4198c582007-04-09 12:31:58 +00005576 }
5577
5578 for (unsigned j = 0, ej = BitTestCases[i].Cases.size(); j != ej; ++j) {
Dan Gohmanf350b272008-08-23 02:25:05 +00005579 SelectionDAGLowering BSDL(*CurDAG, TLI, *AA, FuncInfo, GFI);
Anton Korobeynikov4198c582007-04-09 12:31:58 +00005580 // Set the current basic block to the mbb we wish to insert the code into
5581 BB = BitTestCases[i].Cases[j].ThisBB;
5582 BSDL.setCurrentBasicBlock(BB);
5583 // Emit the code
5584 if (j+1 != ej)
5585 BSDL.visitBitTestCase(BitTestCases[i].Cases[j+1].ThisBB,
5586 BitTestCases[i].Reg,
5587 BitTestCases[i].Cases[j]);
5588 else
5589 BSDL.visitBitTestCase(BitTestCases[i].Default,
5590 BitTestCases[i].Reg,
5591 BitTestCases[i].Cases[j]);
5592
5593
Dan Gohmanf350b272008-08-23 02:25:05 +00005594 CurDAG->setRoot(BSDL.getRoot());
5595 CodeGenAndEmitDAG();
5596 CurDAG->reset();
Anton Korobeynikov4198c582007-04-09 12:31:58 +00005597 }
5598
5599 // Update PHI Nodes
5600 for (unsigned pi = 0, pe = PHINodesToUpdate.size(); pi != pe; ++pi) {
5601 MachineInstr *PHI = PHINodesToUpdate[pi].first;
5602 MachineBasicBlock *PHIBB = PHI->getParent();
5603 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
5604 "This is not a machine PHI node that we are updating!");
5605 // This is "default" BB. We have two jumps to it. From "header" BB and
5606 // from last "case" BB.
5607 if (PHIBB == BitTestCases[i].Default) {
Chris Lattner9ce2e9d2007-12-30 00:57:42 +00005608 PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[pi].second,
5609 false));
5610 PHI->addOperand(MachineOperand::CreateMBB(BitTestCases[i].Parent));
5611 PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[pi].second,
5612 false));
5613 PHI->addOperand(MachineOperand::CreateMBB(BitTestCases[i].Cases.
5614 back().ThisBB));
Anton Korobeynikov4198c582007-04-09 12:31:58 +00005615 }
5616 // One of "cases" BB.
5617 for (unsigned j = 0, ej = BitTestCases[i].Cases.size(); j != ej; ++j) {
5618 MachineBasicBlock* cBB = BitTestCases[i].Cases[j].ThisBB;
5619 if (cBB->succ_end() !=
5620 std::find(cBB->succ_begin(),cBB->succ_end(), PHIBB)) {
Chris Lattner9ce2e9d2007-12-30 00:57:42 +00005621 PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[pi].second,
5622 false));
5623 PHI->addOperand(MachineOperand::CreateMBB(cBB));
Anton Korobeynikov4198c582007-04-09 12:31:58 +00005624 }
5625 }
5626 }
5627 }
5628
Nate Begeman9453eea2006-04-23 06:26:20 +00005629 // If the JumpTable record is filled in, then we need to emit a jump table.
5630 // Updating the PHI nodes is tricky in this case, since we need to determine
5631 // whether the PHI is a successor of the range check MBB or the jump table MBB
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00005632 for (unsigned i = 0, e = JTCases.size(); i != e; ++i) {
5633 // Lower header first, if it wasn't already lowered
5634 if (!JTCases[i].first.Emitted) {
Dan Gohmanf350b272008-08-23 02:25:05 +00005635 SelectionDAGLowering HSDL(*CurDAG, TLI, *AA, FuncInfo, GFI);
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00005636 // Set the current basic block to the mbb we wish to insert the code into
5637 BB = JTCases[i].first.HeaderBB;
5638 HSDL.setCurrentBasicBlock(BB);
5639 // Emit the code
5640 HSDL.visitJumpTableHeader(JTCases[i].second, JTCases[i].first);
Dan Gohmanf350b272008-08-23 02:25:05 +00005641 CurDAG->setRoot(HSDL.getRoot());
5642 CodeGenAndEmitDAG();
5643 CurDAG->reset();
Anton Korobeynikov4198c582007-04-09 12:31:58 +00005644 }
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00005645
Dan Gohmanf350b272008-08-23 02:25:05 +00005646 SelectionDAGLowering JSDL(*CurDAG, TLI, *AA, FuncInfo, GFI);
Nate Begeman37efe672006-04-22 18:53:45 +00005647 // Set the current basic block to the mbb we wish to insert the code into
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00005648 BB = JTCases[i].second.MBB;
5649 JSDL.setCurrentBasicBlock(BB);
Nate Begeman37efe672006-04-22 18:53:45 +00005650 // Emit the code
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00005651 JSDL.visitJumpTable(JTCases[i].second);
Dan Gohmanf350b272008-08-23 02:25:05 +00005652 CurDAG->setRoot(JSDL.getRoot());
5653 CodeGenAndEmitDAG();
5654 CurDAG->reset();
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00005655
Nate Begeman37efe672006-04-22 18:53:45 +00005656 // Update PHI Nodes
5657 for (unsigned pi = 0, pe = PHINodesToUpdate.size(); pi != pe; ++pi) {
5658 MachineInstr *PHI = PHINodesToUpdate[pi].first;
5659 MachineBasicBlock *PHIBB = PHI->getParent();
5660 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
5661 "This is not a machine PHI node that we are updating!");
Anton Korobeynikov4198c582007-04-09 12:31:58 +00005662 // "default" BB. We can go there only from header BB.
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00005663 if (PHIBB == JTCases[i].second.Default) {
Chris Lattner9ce2e9d2007-12-30 00:57:42 +00005664 PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[pi].second,
5665 false));
5666 PHI->addOperand(MachineOperand::CreateMBB(JTCases[i].first.HeaderBB));
Nate Begemanf4360a42006-05-03 03:48:02 +00005667 }
Anton Korobeynikov4198c582007-04-09 12:31:58 +00005668 // JT BB. Just iterate over successors here
Nate Begemanf4360a42006-05-03 03:48:02 +00005669 if (BB->succ_end() != std::find(BB->succ_begin(),BB->succ_end(), PHIBB)) {
Chris Lattner9ce2e9d2007-12-30 00:57:42 +00005670 PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[pi].second,
5671 false));
5672 PHI->addOperand(MachineOperand::CreateMBB(BB));
Nate Begeman37efe672006-04-22 18:53:45 +00005673 }
5674 }
Nate Begeman37efe672006-04-22 18:53:45 +00005675 }
5676
Chris Lattnerb2e806e2006-10-22 23:00:53 +00005677 // If the switch block involved a branch to one of the actual successors, we
5678 // need to update PHI nodes in that block.
5679 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
5680 MachineInstr *PHI = PHINodesToUpdate[i].first;
5681 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
5682 "This is not a machine PHI node that we are updating!");
5683 if (BB->isSuccessor(PHI->getParent())) {
Chris Lattner9ce2e9d2007-12-30 00:57:42 +00005684 PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[i].second,
5685 false));
5686 PHI->addOperand(MachineOperand::CreateMBB(BB));
Chris Lattnerb2e806e2006-10-22 23:00:53 +00005687 }
5688 }
5689
Nate Begemanf15485a2006-03-27 01:32:24 +00005690 // If we generated any switch lowering information, build and codegen any
5691 // additional DAGs necessary.
Chris Lattnerd5e93c02006-09-07 01:59:34 +00005692 for (unsigned i = 0, e = SwitchCases.size(); i != e; ++i) {
Dan Gohmanf350b272008-08-23 02:25:05 +00005693 SelectionDAGLowering SDL(*CurDAG, TLI, *AA, FuncInfo, GFI);
Chris Lattnerd5e93c02006-09-07 01:59:34 +00005694
Nate Begemanf15485a2006-03-27 01:32:24 +00005695 // Set the current basic block to the mbb we wish to insert the code into
5696 BB = SwitchCases[i].ThisBB;
5697 SDL.setCurrentBasicBlock(BB);
Chris Lattnerd5e93c02006-09-07 01:59:34 +00005698
Nate Begemanf15485a2006-03-27 01:32:24 +00005699 // Emit the code
5700 SDL.visitSwitchCase(SwitchCases[i]);
Dan Gohmanf350b272008-08-23 02:25:05 +00005701 CurDAG->setRoot(SDL.getRoot());
5702 CodeGenAndEmitDAG();
5703 CurDAG->reset();
Chris Lattnerd5e93c02006-09-07 01:59:34 +00005704
5705 // Handle any PHI nodes in successors of this chunk, as if we were coming
5706 // from the original BB before switch expansion. Note that PHI nodes can
5707 // occur multiple times in PHINodesToUpdate. We have to be very careful to
5708 // handle them the right number of times.
Chris Lattner57ab6592006-10-24 17:57:59 +00005709 while ((BB = SwitchCases[i].TrueBB)) { // Handle LHS and RHS.
Chris Lattnerd5e93c02006-09-07 01:59:34 +00005710 for (MachineBasicBlock::iterator Phi = BB->begin();
5711 Phi != BB->end() && Phi->getOpcode() == TargetInstrInfo::PHI; ++Phi){
5712 // This value for this PHI node is recorded in PHINodesToUpdate, get it.
5713 for (unsigned pn = 0; ; ++pn) {
5714 assert(pn != PHINodesToUpdate.size() && "Didn't find PHI entry!");
5715 if (PHINodesToUpdate[pn].first == Phi) {
Chris Lattner9ce2e9d2007-12-30 00:57:42 +00005716 Phi->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[pn].
5717 second, false));
5718 Phi->addOperand(MachineOperand::CreateMBB(SwitchCases[i].ThisBB));
Chris Lattnerd5e93c02006-09-07 01:59:34 +00005719 break;
5720 }
5721 }
Nate Begemanf15485a2006-03-27 01:32:24 +00005722 }
Chris Lattnerd5e93c02006-09-07 01:59:34 +00005723
5724 // Don't process RHS if same block as LHS.
Chris Lattner57ab6592006-10-24 17:57:59 +00005725 if (BB == SwitchCases[i].FalseBB)
5726 SwitchCases[i].FalseBB = 0;
Chris Lattnerd5e93c02006-09-07 01:59:34 +00005727
5728 // If we haven't handled the RHS, do so now. Otherwise, we're done.
Chris Lattner24525952006-10-24 18:07:37 +00005729 SwitchCases[i].TrueBB = SwitchCases[i].FalseBB;
Chris Lattner57ab6592006-10-24 17:57:59 +00005730 SwitchCases[i].FalseBB = 0;
Nate Begemanf15485a2006-03-27 01:32:24 +00005731 }
Chris Lattner57ab6592006-10-24 17:57:59 +00005732 assert(SwitchCases[i].TrueBB == 0 && SwitchCases[i].FalseBB == 0);
Chris Lattnera33ef482005-03-30 01:10:47 +00005733 }
Chris Lattner1c08c712005-01-07 07:47:53 +00005734}
Evan Chenga9c20912006-01-21 02:32:06 +00005735
Jim Laskey13ec7022006-08-01 14:21:23 +00005736
Dan Gohman5e843682008-07-14 18:19:29 +00005737/// Schedule - Pick a safe ordering for instructions for each
Evan Chenga9c20912006-01-21 02:32:06 +00005738/// target node in the graph.
Dan Gohman5e843682008-07-14 18:19:29 +00005739///
Dan Gohmanf350b272008-08-23 02:25:05 +00005740ScheduleDAG *SelectionDAGISel::Schedule() {
Jim Laskeyeb577ba2006-08-02 12:30:23 +00005741 RegisterScheduler::FunctionPassCtor Ctor = RegisterScheduler::getDefault();
Jim Laskey13ec7022006-08-01 14:21:23 +00005742
5743 if (!Ctor) {
Jim Laskeyeb577ba2006-08-02 12:30:23 +00005744 Ctor = ISHeuristic;
Jim Laskey9373beb2006-08-01 19:14:14 +00005745 RegisterScheduler::setDefault(Ctor);
Evan Cheng4ef10862006-01-23 07:01:07 +00005746 }
Jim Laskey13ec7022006-08-01 14:21:23 +00005747
Dan Gohmanf350b272008-08-23 02:25:05 +00005748 ScheduleDAG *Scheduler = Ctor(this, CurDAG, BB, Fast);
Dan Gohman5e843682008-07-14 18:19:29 +00005749 Scheduler->Run();
Dan Gohman3e1a7ae2007-08-28 20:32:58 +00005750
Dan Gohman5e843682008-07-14 18:19:29 +00005751 return Scheduler;
Evan Chenga9c20912006-01-21 02:32:06 +00005752}
Chris Lattner0e43f2b2006-02-24 02:13:54 +00005753
Chris Lattner03fc53c2006-03-06 00:22:00 +00005754
Jim Laskey9ff542f2006-08-01 18:29:48 +00005755HazardRecognizer *SelectionDAGISel::CreateTargetHazardRecognizer() {
5756 return new HazardRecognizer();
5757}
5758
Chris Lattner75548062006-10-11 03:58:02 +00005759//===----------------------------------------------------------------------===//
5760// Helper functions used by the generated instruction selector.
5761//===----------------------------------------------------------------------===//
5762// Calls to these methods are generated by tblgen.
5763
5764/// CheckAndMask - The isel is trying to match something like (and X, 255). If
5765/// the dag combiner simplified the 255, we still want to match. RHS is the
5766/// actual value in the DAG on the RHS of an AND, and DesiredMaskS is the value
5767/// specified in the .td file (e.g. 255).
Dan Gohman475871a2008-07-27 21:46:04 +00005768bool SelectionDAGISel::CheckAndMask(SDValue LHS, ConstantSDNode *RHS,
Dan Gohmandc9b3d02007-07-24 23:00:27 +00005769 int64_t DesiredMaskS) const {
Dan Gohman2e68b6f2008-02-25 21:11:39 +00005770 const APInt &ActualMask = RHS->getAPIntValue();
5771 const APInt &DesiredMask = APInt(LHS.getValueSizeInBits(), DesiredMaskS);
Chris Lattner75548062006-10-11 03:58:02 +00005772
5773 // If the actual mask exactly matches, success!
5774 if (ActualMask == DesiredMask)
5775 return true;
5776
5777 // If the actual AND mask is allowing unallowed bits, this doesn't match.
Dan Gohman2e68b6f2008-02-25 21:11:39 +00005778 if (ActualMask.intersects(~DesiredMask))
Chris Lattner75548062006-10-11 03:58:02 +00005779 return false;
5780
5781 // Otherwise, the DAG Combiner may have proven that the value coming in is
5782 // either already zero or is not demanded. Check for known zero input bits.
Dan Gohman2e68b6f2008-02-25 21:11:39 +00005783 APInt NeededMask = DesiredMask & ~ActualMask;
Dan Gohmanea859be2007-06-22 14:59:07 +00005784 if (CurDAG->MaskedValueIsZero(LHS, NeededMask))
Chris Lattner75548062006-10-11 03:58:02 +00005785 return true;
5786
5787 // TODO: check to see if missing bits are just not demanded.
5788
5789 // Otherwise, this pattern doesn't match.
5790 return false;
5791}
5792
5793/// CheckOrMask - The isel is trying to match something like (or X, 255). If
5794/// the dag combiner simplified the 255, we still want to match. RHS is the
5795/// actual value in the DAG on the RHS of an OR, and DesiredMaskS is the value
5796/// specified in the .td file (e.g. 255).
Dan Gohman475871a2008-07-27 21:46:04 +00005797bool SelectionDAGISel::CheckOrMask(SDValue LHS, ConstantSDNode *RHS,
Dan Gohman2e68b6f2008-02-25 21:11:39 +00005798 int64_t DesiredMaskS) const {
5799 const APInt &ActualMask = RHS->getAPIntValue();
5800 const APInt &DesiredMask = APInt(LHS.getValueSizeInBits(), DesiredMaskS);
Chris Lattner75548062006-10-11 03:58:02 +00005801
5802 // If the actual mask exactly matches, success!
5803 if (ActualMask == DesiredMask)
5804 return true;
5805
5806 // If the actual AND mask is allowing unallowed bits, this doesn't match.
Dan Gohman2e68b6f2008-02-25 21:11:39 +00005807 if (ActualMask.intersects(~DesiredMask))
Chris Lattner75548062006-10-11 03:58:02 +00005808 return false;
5809
5810 // Otherwise, the DAG Combiner may have proven that the value coming in is
5811 // either already zero or is not demanded. Check for known zero input bits.
Dan Gohman2e68b6f2008-02-25 21:11:39 +00005812 APInt NeededMask = DesiredMask & ~ActualMask;
Chris Lattner75548062006-10-11 03:58:02 +00005813
Dan Gohman2e68b6f2008-02-25 21:11:39 +00005814 APInt KnownZero, KnownOne;
Dan Gohmanea859be2007-06-22 14:59:07 +00005815 CurDAG->ComputeMaskedBits(LHS, NeededMask, KnownZero, KnownOne);
Chris Lattner75548062006-10-11 03:58:02 +00005816
5817 // If all the missing bits in the or are already known to be set, match!
5818 if ((NeededMask & KnownOne) == NeededMask)
5819 return true;
5820
5821 // TODO: check to see if missing bits are just not demanded.
5822
5823 // Otherwise, this pattern doesn't match.
5824 return false;
5825}
5826
Jim Laskey9ff542f2006-08-01 18:29:48 +00005827
Chris Lattner0e43f2b2006-02-24 02:13:54 +00005828/// SelectInlineAsmMemoryOperands - Calls to this are automatically generated
5829/// by tblgen. Others should not call it.
5830void SelectionDAGISel::
Dan Gohmanf350b272008-08-23 02:25:05 +00005831SelectInlineAsmMemoryOperands(std::vector<SDValue> &Ops) {
Dan Gohman475871a2008-07-27 21:46:04 +00005832 std::vector<SDValue> InOps;
Chris Lattner0e43f2b2006-02-24 02:13:54 +00005833 std::swap(InOps, Ops);
5834
5835 Ops.push_back(InOps[0]); // input chain.
5836 Ops.push_back(InOps[1]); // input asm string.
5837
Chris Lattner0e43f2b2006-02-24 02:13:54 +00005838 unsigned i = 2, e = InOps.size();
5839 if (InOps[e-1].getValueType() == MVT::Flag)
5840 --e; // Don't process a flag operand if it is here.
5841
5842 while (i != e) {
5843 unsigned Flags = cast<ConstantSDNode>(InOps[i])->getValue();
5844 if ((Flags & 7) != 4 /*MEM*/) {
5845 // Just skip over this operand, copying the operands verbatim.
5846 Ops.insert(Ops.end(), InOps.begin()+i, InOps.begin()+i+(Flags >> 3) + 1);
5847 i += (Flags >> 3) + 1;
5848 } else {
5849 assert((Flags >> 3) == 1 && "Memory operand with multiple values?");
5850 // Otherwise, this is a memory operand. Ask the target to select it.
Dan Gohman475871a2008-07-27 21:46:04 +00005851 std::vector<SDValue> SelOps;
Dan Gohmanf350b272008-08-23 02:25:05 +00005852 if (SelectInlineAsmMemoryOperand(InOps[i+1], 'm', SelOps)) {
Bill Wendling832171c2006-12-07 20:04:42 +00005853 cerr << "Could not match memory address. Inline asm failure!\n";
Chris Lattner0e43f2b2006-02-24 02:13:54 +00005854 exit(1);
5855 }
5856
5857 // Add this to the output node.
Dan Gohmanf350b272008-08-23 02:25:05 +00005858 MVT IntPtrTy = CurDAG->getTargetLoweringInfo().getPointerTy();
5859 Ops.push_back(CurDAG->getTargetConstant(4/*MEM*/ | (SelOps.size() << 3),
5860 IntPtrTy));
Chris Lattner0e43f2b2006-02-24 02:13:54 +00005861 Ops.insert(Ops.end(), SelOps.begin(), SelOps.end());
5862 i += 2;
5863 }
5864 }
5865
5866 // Add the flag input back if present.
5867 if (e != InOps.size())
5868 Ops.push_back(InOps.back());
5869}
Devang Patel794fd752007-05-01 21:15:47 +00005870
Devang Patel19974732007-05-03 01:11:54 +00005871char SelectionDAGISel::ID = 0;