blob: 9304c0e7a1624774ba892d1ef6067b7a7a83e4cb [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.
323 std::map<const BasicBlock*, MachineBasicBlock *> MBBMap;
324
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.
333 std::map<const AllocaInst*, int> StaticAllocaMap;
334
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) {
397 BasicBlock *Entry = A->getParent()->begin();
398 for (Value::use_iterator UI = A->use_begin(), E = A->use_end(); UI != E; ++UI)
Nate Begemanf15485a2006-03-27 01:32:24 +0000399 if (cast<Instruction>(*UI)->getParent() != Entry || isa<SwitchInst>(*UI))
Chris Lattnerbf209482005-10-30 19:42:35 +0000400 return false; // Use not in entry block.
401 return true;
402}
403
Chris Lattner1c08c712005-01-07 07:47:53 +0000404FunctionLoweringInfo::FunctionLoweringInfo(TargetLowering &tli,
Misha Brukmanedf128a2005-04-21 22:36:52 +0000405 Function &fn, MachineFunction &mf)
Chris Lattner84bc5422007-12-31 04:13:23 +0000406 : TLI(tli), Fn(fn), MF(mf), RegInfo(MF.getRegInfo()) {
Chris Lattner1c08c712005-01-07 07:47:53 +0000407
Chris Lattnerbf209482005-10-30 19:42:35 +0000408 // Create a vreg for each argument register that is not dead and is used
409 // outside of the entry block for the function.
410 for (Function::arg_iterator AI = Fn.arg_begin(), E = Fn.arg_end();
411 AI != E; ++AI)
412 if (!isOnlyUsedInEntryBlock(AI))
413 InitializeRegForValue(AI);
414
Chris Lattner1c08c712005-01-07 07:47:53 +0000415 // Initialize the mapping of values to registers. This is only set up for
416 // instruction values that are used outside of the block that defines
417 // them.
Jeff Cohen2aeaf4e2005-10-01 03:57:14 +0000418 Function::iterator BB = Fn.begin(), EB = Fn.end();
Chris Lattner1c08c712005-01-07 07:47:53 +0000419 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
420 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
Reid Spencerb83eb642006-10-20 07:07:24 +0000421 if (ConstantInt *CUI = dyn_cast<ConstantInt>(AI->getArraySize())) {
Chris Lattner1c08c712005-01-07 07:47:53 +0000422 const Type *Ty = AI->getAllocatedType();
Duncan Sands514ab342007-11-01 20:53:16 +0000423 uint64_t TySize = TLI.getTargetData()->getABITypeSize(Ty);
Nate Begemanae232e72005-11-06 09:00:38 +0000424 unsigned Align =
Chris Lattnerd2b7cec2007-02-14 05:52:17 +0000425 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
Nate Begemanae232e72005-11-06 09:00:38 +0000426 AI->getAlignment());
Chris Lattnera8217e32005-05-13 23:14:17 +0000427
Reid Spencerb83eb642006-10-20 07:07:24 +0000428 TySize *= CUI->getZExtValue(); // Get total allocated size.
Chris Lattnerd222f6a2005-10-18 22:14:06 +0000429 if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
Chris Lattner1c08c712005-01-07 07:47:53 +0000430 StaticAllocaMap[AI] =
Chris Lattner6266c182007-04-25 04:08:28 +0000431 MF.getFrameInfo()->CreateStackObject(TySize, Align);
Chris Lattner1c08c712005-01-07 07:47:53 +0000432 }
433
Jeff Cohen2aeaf4e2005-10-01 03:57:14 +0000434 for (; BB != EB; ++BB)
435 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
Chris Lattner1c08c712005-01-07 07:47:53 +0000436 if (!I->use_empty() && isUsedOutsideOfDefiningBlock(I))
437 if (!isa<AllocaInst>(I) ||
438 !StaticAllocaMap.count(cast<AllocaInst>(I)))
439 InitializeRegForValue(I);
440
441 // Create an initial MachineBasicBlock for each LLVM BasicBlock in F. This
442 // also creates the initial PHI MachineInstrs, though none of the input
443 // operands are populated.
Jeff Cohen2aeaf4e2005-10-01 03:57:14 +0000444 for (BB = Fn.begin(), EB = Fn.end(); BB != EB; ++BB) {
Dan Gohman0e5f1302008-07-07 23:02:41 +0000445 MachineBasicBlock *MBB = mf.CreateMachineBasicBlock(BB);
Chris Lattner1c08c712005-01-07 07:47:53 +0000446 MBBMap[BB] = MBB;
Dan Gohman0e5f1302008-07-07 23:02:41 +0000447 MF.push_back(MBB);
Chris Lattner1c08c712005-01-07 07:47:53 +0000448
449 // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
450 // appropriate.
451 PHINode *PN;
Chris Lattner8c494ab2006-10-27 23:50:33 +0000452 for (BasicBlock::iterator I = BB->begin();(PN = dyn_cast<PHINode>(I)); ++I){
453 if (PN->use_empty()) continue;
454
Chris Lattner8c494ab2006-10-27 23:50:33 +0000455 unsigned PHIReg = ValueMap[PN];
456 assert(PHIReg && "PHI node does not have an assigned virtual register!");
Dan Gohman6f498b02008-08-04 23:42:46 +0000457
458 SmallVector<MVT, 4> ValueVTs;
459 ComputeValueVTs(TLI, PN->getType(), ValueVTs);
460 for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
461 MVT VT = ValueVTs[vti];
462 unsigned NumRegisters = TLI.getNumRegisters(VT);
463 const TargetInstrInfo *TII = TLI.getTargetMachine().getInstrInfo();
464 for (unsigned i = 0; i != NumRegisters; ++i)
465 BuildMI(MBB, TII->get(TargetInstrInfo::PHI), PHIReg+i);
466 PHIReg += NumRegisters;
467 }
Chris Lattner8c494ab2006-10-27 23:50:33 +0000468 }
Chris Lattner1c08c712005-01-07 07:47:53 +0000469 }
470}
471
Chris Lattner3c384492006-03-16 19:51:18 +0000472/// CreateRegForValue - Allocate the appropriate number of virtual registers of
473/// the correctly promoted or expanded types. Assign these registers
474/// consecutive vreg numbers and return the first assigned number.
Dan Gohman10a6b7a2008-04-28 18:19:43 +0000475///
476/// In the case that the given value has struct or array type, this function
477/// will assign registers for each member or element.
478///
Chris Lattner3c384492006-03-16 19:51:18 +0000479unsigned FunctionLoweringInfo::CreateRegForValue(const Value *V) {
Duncan Sands83ec4b62008-06-06 12:08:01 +0000480 SmallVector<MVT, 4> ValueVTs;
Chris Lattnerb606dba2008-04-28 06:44:42 +0000481 ComputeValueVTs(TLI, V->getType(), ValueVTs);
Bill Wendling95b39552007-04-24 21:13:23 +0000482
Dan Gohman23ce5022008-04-25 18:27:55 +0000483 unsigned FirstReg = 0;
Dan Gohmanb20d4f82008-04-28 17:42:03 +0000484 for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
Duncan Sands83ec4b62008-06-06 12:08:01 +0000485 MVT ValueVT = ValueVTs[Value];
486 MVT RegisterVT = TLI.getRegisterType(ValueVT);
Dan Gohman8c8c5fc2007-06-27 14:34:07 +0000487
Chris Lattnerb606dba2008-04-28 06:44:42 +0000488 unsigned NumRegs = TLI.getNumRegisters(ValueVT);
Dan Gohman23ce5022008-04-25 18:27:55 +0000489 for (unsigned i = 0; i != NumRegs; ++i) {
490 unsigned R = MakeReg(RegisterVT);
491 if (!FirstReg) FirstReg = R;
492 }
493 }
494 return FirstReg;
Chris Lattner3c384492006-03-16 19:51:18 +0000495}
Chris Lattner1c08c712005-01-07 07:47:53 +0000496
497//===----------------------------------------------------------------------===//
498/// SelectionDAGLowering - This is the common target-independent lowering
499/// implementation that is parameterized by a TargetLowering object.
500/// Also, targets can overload any lowering method.
501///
502namespace llvm {
503class SelectionDAGLowering {
504 MachineBasicBlock *CurMBB;
505
Dan Gohman475871a2008-07-27 21:46:04 +0000506 DenseMap<const Value*, SDValue> NodeMap;
Chris Lattner1c08c712005-01-07 07:47:53 +0000507
Chris Lattnerd3948112005-01-17 22:19:26 +0000508 /// PendingLoads - Loads are not emitted to the program immediately. We bunch
509 /// them up and then emit token factor nodes when possible. This allows us to
510 /// get simple disambiguation between loads without worrying about alias
511 /// analysis.
Dan Gohman475871a2008-07-27 21:46:04 +0000512 SmallVector<SDValue, 8> PendingLoads;
Chris Lattnerd3948112005-01-17 22:19:26 +0000513
Dan Gohman86e1ebf2008-03-27 19:56:19 +0000514 /// PendingExports - CopyToReg nodes that copy values to virtual registers
515 /// for export to other blocks need to be emitted before any terminator
516 /// instruction, but they have no other ordering requirements. We bunch them
517 /// up and the emit a single tokenfactor for them just before terminator
518 /// instructions.
Dan Gohman475871a2008-07-27 21:46:04 +0000519 std::vector<SDValue> PendingExports;
Dan Gohman86e1ebf2008-03-27 19:56:19 +0000520
Anton Korobeynikov5502bf62007-04-04 21:14:49 +0000521 /// Case - A struct to record the Value for a switch case, and the
522 /// case's target basic block.
523 struct Case {
524 Constant* Low;
525 Constant* High;
526 MachineBasicBlock* BB;
527
528 Case() : Low(0), High(0), BB(0) { }
529 Case(Constant* low, Constant* high, MachineBasicBlock* bb) :
530 Low(low), High(high), BB(bb) { }
531 uint64_t size() const {
532 uint64_t rHigh = cast<ConstantInt>(High)->getSExtValue();
533 uint64_t rLow = cast<ConstantInt>(Low)->getSExtValue();
534 return (rHigh - rLow + 1ULL);
535 }
536 };
537
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000538 struct CaseBits {
539 uint64_t Mask;
540 MachineBasicBlock* BB;
541 unsigned Bits;
542
543 CaseBits(uint64_t mask, MachineBasicBlock* bb, unsigned bits):
544 Mask(mask), BB(bb), Bits(bits) { }
545 };
546
Anton Korobeynikov5502bf62007-04-04 21:14:49 +0000547 typedef std::vector<Case> CaseVector;
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000548 typedef std::vector<CaseBits> CaseBitsVector;
Anton Korobeynikov5502bf62007-04-04 21:14:49 +0000549 typedef CaseVector::iterator CaseItr;
550 typedef std::pair<CaseItr, CaseItr> CaseRange;
Nate Begemanf15485a2006-03-27 01:32:24 +0000551
552 /// CaseRec - A struct with ctor used in lowering switches to a binary tree
553 /// of conditional branches.
554 struct CaseRec {
555 CaseRec(MachineBasicBlock *bb, Constant *lt, Constant *ge, CaseRange r) :
556 CaseBB(bb), LT(lt), GE(ge), Range(r) {}
557
558 /// CaseBB - The MBB in which to emit the compare and branch
559 MachineBasicBlock *CaseBB;
560 /// LT, GE - If nonzero, we know the current case value must be less-than or
561 /// greater-than-or-equal-to these Constants.
562 Constant *LT;
563 Constant *GE;
564 /// Range - A pair of iterators representing the range of case values to be
565 /// processed at this point in the binary search tree.
566 CaseRange Range;
567 };
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +0000568
569 typedef std::vector<CaseRec> CaseRecVector;
Anton Korobeynikov5502bf62007-04-04 21:14:49 +0000570
571 /// The comparison function for sorting the switch case values in the vector.
572 /// WARNING: Case ranges should be disjoint!
Nate Begemanf15485a2006-03-27 01:32:24 +0000573 struct CaseCmp {
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000574 bool operator () (const Case& C1, const Case& C2) {
Anton Korobeynikov5502bf62007-04-04 21:14:49 +0000575 assert(isa<ConstantInt>(C1.Low) && isa<ConstantInt>(C2.High));
576 const ConstantInt* CI1 = cast<const ConstantInt>(C1.Low);
577 const ConstantInt* CI2 = cast<const ConstantInt>(C2.High);
578 return CI1->getValue().slt(CI2->getValue());
Nate Begemanf15485a2006-03-27 01:32:24 +0000579 }
580 };
Anton Korobeynikov5502bf62007-04-04 21:14:49 +0000581
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000582 struct CaseBitsCmp {
583 bool operator () (const CaseBits& C1, const CaseBits& C2) {
584 return C1.Bits > C2.Bits;
585 }
586 };
587
Anton Korobeynikov5502bf62007-04-04 21:14:49 +0000588 unsigned Clusterify(CaseVector& Cases, const SwitchInst &SI);
Nate Begemanf15485a2006-03-27 01:32:24 +0000589
Chris Lattner1c08c712005-01-07 07:47:53 +0000590public:
591 // TLI - This is information that describes the available target features we
592 // need for lowering. This indicates when operations are unavailable,
593 // implemented with a libcall, etc.
594 TargetLowering &TLI;
595 SelectionDAG &DAG;
Owen Andersona69571c2006-05-03 01:29:57 +0000596 const TargetData *TD;
Dan Gohman5f43f922007-08-27 16:26:13 +0000597 AliasAnalysis &AA;
Chris Lattner1c08c712005-01-07 07:47:53 +0000598
Nate Begemanf15485a2006-03-27 01:32:24 +0000599 /// SwitchCases - Vector of CaseBlock structures used to communicate
600 /// SwitchInst code generation information.
601 std::vector<SelectionDAGISel::CaseBlock> SwitchCases;
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +0000602 /// JTCases - Vector of JumpTable structures used to communicate
603 /// SwitchInst code generation information.
604 std::vector<SelectionDAGISel::JumpTableBlock> JTCases;
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000605 std::vector<SelectionDAGISel::BitTestBlock> BitTestCases;
Nate Begemanf15485a2006-03-27 01:32:24 +0000606
Chris Lattner1c08c712005-01-07 07:47:53 +0000607 /// FuncInfo - Information about the function as a whole.
608 ///
609 FunctionLoweringInfo &FuncInfo;
Gordon Henriksence224772008-01-07 01:30:38 +0000610
Gordon Henriksen5eca0752008-08-17 18:44:35 +0000611 /// GFI - Garbage collection metadata for the function.
612 GCFunctionInfo *GFI;
Chris Lattner1c08c712005-01-07 07:47:53 +0000613
614 SelectionDAGLowering(SelectionDAG &dag, TargetLowering &tli,
Dan Gohman5f43f922007-08-27 16:26:13 +0000615 AliasAnalysis &aa,
Gordon Henriksence224772008-01-07 01:30:38 +0000616 FunctionLoweringInfo &funcinfo,
Gordon Henriksen5eca0752008-08-17 18:44:35 +0000617 GCFunctionInfo *gfi)
Dan Gohman5f43f922007-08-27 16:26:13 +0000618 : TLI(tli), DAG(dag), TD(DAG.getTarget().getTargetData()), AA(aa),
Gordon Henriksen5eca0752008-08-17 18:44:35 +0000619 FuncInfo(funcinfo), GFI(gfi) {
Chris Lattner1c08c712005-01-07 07:47:53 +0000620 }
621
Dan Gohman86e1ebf2008-03-27 19:56:19 +0000622 /// getRoot - Return the current virtual root of the Selection DAG,
623 /// flushing any PendingLoad items. This must be done before emitting
624 /// a store or any other node that may need to be ordered after any
625 /// prior load instructions.
Chris Lattnera651cf62005-01-17 19:43:36 +0000626 ///
Dan Gohman475871a2008-07-27 21:46:04 +0000627 SDValue getRoot() {
Chris Lattnerd3948112005-01-17 22:19:26 +0000628 if (PendingLoads.empty())
629 return DAG.getRoot();
Misha Brukmanedf128a2005-04-21 22:36:52 +0000630
Chris Lattnerd3948112005-01-17 22:19:26 +0000631 if (PendingLoads.size() == 1) {
Dan Gohman475871a2008-07-27 21:46:04 +0000632 SDValue Root = PendingLoads[0];
Chris Lattnerd3948112005-01-17 22:19:26 +0000633 DAG.setRoot(Root);
634 PendingLoads.clear();
635 return Root;
636 }
637
638 // Otherwise, we have to make a token factor node.
Dan Gohman475871a2008-07-27 21:46:04 +0000639 SDValue Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
Chris Lattnerbd564bf2006-08-08 02:23:42 +0000640 &PendingLoads[0], PendingLoads.size());
Chris Lattnerd3948112005-01-17 22:19:26 +0000641 PendingLoads.clear();
642 DAG.setRoot(Root);
643 return Root;
Chris Lattnera651cf62005-01-17 19:43:36 +0000644 }
645
Dan Gohman86e1ebf2008-03-27 19:56:19 +0000646 /// getControlRoot - Similar to getRoot, but instead of flushing all the
647 /// PendingLoad items, flush all the PendingExports items. It is necessary
648 /// to do this before emitting a terminator instruction.
649 ///
Dan Gohman475871a2008-07-27 21:46:04 +0000650 SDValue getControlRoot() {
651 SDValue Root = DAG.getRoot();
Dan Gohman86e1ebf2008-03-27 19:56:19 +0000652
653 if (PendingExports.empty())
654 return Root;
655
656 // Turn all of the CopyToReg chains into one factored node.
657 if (Root.getOpcode() != ISD::EntryToken) {
658 unsigned i = 0, e = PendingExports.size();
659 for (; i != e; ++i) {
660 assert(PendingExports[i].Val->getNumOperands() > 1);
661 if (PendingExports[i].Val->getOperand(0) == Root)
662 break; // Don't add the root if we already indirectly depend on it.
663 }
664
665 if (i == e)
666 PendingExports.push_back(Root);
667 }
668
669 Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
670 &PendingExports[0],
671 PendingExports.size());
672 PendingExports.clear();
673 DAG.setRoot(Root);
674 return Root;
675 }
676
677 void CopyValueToVirtualRegister(Value *V, unsigned Reg);
Chris Lattner571e4342006-10-27 21:36:01 +0000678
Chris Lattner1c08c712005-01-07 07:47:53 +0000679 void visit(Instruction &I) { visit(I.getOpcode(), I); }
680
681 void visit(unsigned Opcode, User &I) {
Chris Lattner1e7aa5c2006-11-10 04:41:34 +0000682 // Note: this doesn't use InstVisitor, because it has to work with
683 // ConstantExpr's in addition to instructions.
Chris Lattner1c08c712005-01-07 07:47:53 +0000684 switch (Opcode) {
685 default: assert(0 && "Unknown instruction type encountered!");
686 abort();
687 // Build the switch statement using the Instruction.def file.
688#define HANDLE_INST(NUM, OPCODE, CLASS) \
689 case Instruction::OPCODE:return visit##OPCODE((CLASS&)I);
690#include "llvm/Instruction.def"
691 }
692 }
693
694 void setCurrentBasicBlock(MachineBasicBlock *MBB) { CurMBB = MBB; }
695
Dan Gohman475871a2008-07-27 21:46:04 +0000696 SDValue getValue(const Value *V);
Chris Lattner1c08c712005-01-07 07:47:53 +0000697
Dan Gohman475871a2008-07-27 21:46:04 +0000698 void setValue(const Value *V, SDValue NewN) {
699 SDValue &N = NodeMap[V];
Chris Lattner1c08c712005-01-07 07:47:53 +0000700 assert(N.Val == 0 && "Already set a value for this node!");
Chris Lattner0da331f2007-02-04 01:31:47 +0000701 N = NewN;
Chris Lattner1c08c712005-01-07 07:47:53 +0000702 }
Chris Lattner4e4b5762006-02-01 18:59:47 +0000703
Evan Cheng5c807602008-02-26 02:33:44 +0000704 void GetRegistersForValue(SDISelAsmOperandInfo &OpInfo, bool HasEarlyClobber,
Chris Lattnere7cf56a2007-04-30 21:11:17 +0000705 std::set<unsigned> &OutputRegs,
706 std::set<unsigned> &InputRegs);
Nate Begemanf15485a2006-03-27 01:32:24 +0000707
Chris Lattner571e4342006-10-27 21:36:01 +0000708 void FindMergedConditions(Value *Cond, MachineBasicBlock *TBB,
709 MachineBasicBlock *FBB, MachineBasicBlock *CurBB,
710 unsigned Opc);
Chris Lattner8c494ab2006-10-27 23:50:33 +0000711 bool isExportableFromCurrentBlock(Value *V, const BasicBlock *FromBB);
Chris Lattner571e4342006-10-27 21:36:01 +0000712 void ExportFromCurrentBlock(Value *V);
Dan Gohman475871a2008-07-27 21:46:04 +0000713 void LowerCallTo(CallSite CS, SDValue Callee, bool IsTailCall,
Anton Korobeynikov070280e2007-05-23 11:08:31 +0000714 MachineBasicBlock *LandingPad = NULL);
Duncan Sandsdc024672007-11-27 13:23:08 +0000715
Chris Lattner1c08c712005-01-07 07:47:53 +0000716 // Terminator instructions.
717 void visitRet(ReturnInst &I);
718 void visitBr(BranchInst &I);
Nate Begemanf15485a2006-03-27 01:32:24 +0000719 void visitSwitch(SwitchInst &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000720 void visitUnreachable(UnreachableInst &I) { /* noop */ }
721
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +0000722 // Helpers for visitSwitch
Anton Korobeynikovdd433212007-03-27 12:05:48 +0000723 bool handleSmallSwitchRange(CaseRec& CR,
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +0000724 CaseRecVector& WorkList,
725 Value* SV,
726 MachineBasicBlock* Default);
Anton Korobeynikovdd433212007-03-27 12:05:48 +0000727 bool handleJTSwitchCase(CaseRec& CR,
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +0000728 CaseRecVector& WorkList,
729 Value* SV,
730 MachineBasicBlock* Default);
Anton Korobeynikovdd433212007-03-27 12:05:48 +0000731 bool handleBTSplitSwitchCase(CaseRec& CR,
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +0000732 CaseRecVector& WorkList,
733 Value* SV,
734 MachineBasicBlock* Default);
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000735 bool handleBitTestsSwitchCase(CaseRec& CR,
736 CaseRecVector& WorkList,
737 Value* SV,
738 MachineBasicBlock* Default);
Nate Begemanf15485a2006-03-27 01:32:24 +0000739 void visitSwitchCase(SelectionDAGISel::CaseBlock &CB);
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000740 void visitBitTestHeader(SelectionDAGISel::BitTestBlock &B);
741 void visitBitTestCase(MachineBasicBlock* NextMBB,
742 unsigned Reg,
743 SelectionDAGISel::BitTestCase &B);
Nate Begeman37efe672006-04-22 18:53:45 +0000744 void visitJumpTable(SelectionDAGISel::JumpTable &JT);
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +0000745 void visitJumpTableHeader(SelectionDAGISel::JumpTable &JT,
746 SelectionDAGISel::JumpTableHeader &JTH);
Nate Begemanf15485a2006-03-27 01:32:24 +0000747
Chris Lattner1c08c712005-01-07 07:47:53 +0000748 // These all get lowered before this pass.
Jim Laskeyb180aa12007-02-21 22:53:45 +0000749 void visitInvoke(InvokeInst &I);
750 void visitUnwind(UnwindInst &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000751
Dan Gohman7f321562007-06-25 16:23:39 +0000752 void visitBinary(User &I, unsigned OpCode);
Nate Begemane21ea612005-11-18 07:42:56 +0000753 void visitShift(User &I, unsigned Opcode);
Nate Begeman5fbb5d22005-11-19 00:36:38 +0000754 void visitAdd(User &I) {
Dan Gohman7f321562007-06-25 16:23:39 +0000755 if (I.getType()->isFPOrFPVector())
756 visitBinary(I, ISD::FADD);
Reid Spencer1628cec2006-10-26 06:15:43 +0000757 else
Dan Gohman7f321562007-06-25 16:23:39 +0000758 visitBinary(I, ISD::ADD);
Chris Lattner01b3d732005-09-28 22:28:18 +0000759 }
Chris Lattnerb9fccc42005-04-02 05:04:50 +0000760 void visitSub(User &I);
Reid Spencer1628cec2006-10-26 06:15:43 +0000761 void visitMul(User &I) {
Dan Gohman7f321562007-06-25 16:23:39 +0000762 if (I.getType()->isFPOrFPVector())
763 visitBinary(I, ISD::FMUL);
Reid Spencer1628cec2006-10-26 06:15:43 +0000764 else
Dan Gohman7f321562007-06-25 16:23:39 +0000765 visitBinary(I, ISD::MUL);
Chris Lattner01b3d732005-09-28 22:28:18 +0000766 }
Dan Gohman7f321562007-06-25 16:23:39 +0000767 void visitURem(User &I) { visitBinary(I, ISD::UREM); }
768 void visitSRem(User &I) { visitBinary(I, ISD::SREM); }
769 void visitFRem(User &I) { visitBinary(I, ISD::FREM); }
770 void visitUDiv(User &I) { visitBinary(I, ISD::UDIV); }
771 void visitSDiv(User &I) { visitBinary(I, ISD::SDIV); }
772 void visitFDiv(User &I) { visitBinary(I, ISD::FDIV); }
773 void visitAnd (User &I) { visitBinary(I, ISD::AND); }
774 void visitOr (User &I) { visitBinary(I, ISD::OR); }
775 void visitXor (User &I) { visitBinary(I, ISD::XOR); }
Reid Spencer24d6da52007-01-21 00:29:26 +0000776 void visitShl (User &I) { visitShift(I, ISD::SHL); }
Reid Spencer3822ff52006-11-08 06:47:33 +0000777 void visitLShr(User &I) { visitShift(I, ISD::SRL); }
778 void visitAShr(User &I) { visitShift(I, ISD::SRA); }
Reid Spencer45fb3f32006-11-20 01:22:35 +0000779 void visitICmp(User &I);
780 void visitFCmp(User &I);
Nate Begemanb43e9c12008-05-12 19:40:03 +0000781 void visitVICmp(User &I);
782 void visitVFCmp(User &I);
Reid Spencer3da59db2006-11-27 01:05:10 +0000783 // Visit the conversion instructions
784 void visitTrunc(User &I);
785 void visitZExt(User &I);
786 void visitSExt(User &I);
787 void visitFPTrunc(User &I);
788 void visitFPExt(User &I);
789 void visitFPToUI(User &I);
790 void visitFPToSI(User &I);
791 void visitUIToFP(User &I);
792 void visitSIToFP(User &I);
793 void visitPtrToInt(User &I);
794 void visitIntToPtr(User &I);
795 void visitBitCast(User &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000796
Chris Lattner2bbd8102006-03-29 00:11:43 +0000797 void visitExtractElement(User &I);
798 void visitInsertElement(User &I);
Chris Lattner3e104b12006-04-08 04:15:24 +0000799 void visitShuffleVector(User &I);
Chris Lattnerc7029802006-03-18 01:44:44 +0000800
Dan Gohman1d685a42008-06-07 02:02:36 +0000801 void visitExtractValue(ExtractValueInst &I);
802 void visitInsertValue(InsertValueInst &I);
Dan Gohman041e2eb2008-05-15 19:50:34 +0000803
Chris Lattner1c08c712005-01-07 07:47:53 +0000804 void visitGetElementPtr(User &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000805 void visitSelect(User &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000806
807 void visitMalloc(MallocInst &I);
808 void visitFree(FreeInst &I);
809 void visitAlloca(AllocaInst &I);
810 void visitLoad(LoadInst &I);
811 void visitStore(StoreInst &I);
812 void visitPHI(PHINode &I) { } // PHI nodes are handled specially.
813 void visitCall(CallInst &I);
Duncan Sandsfd7b3262007-12-17 18:08:19 +0000814 void visitInlineAsm(CallSite CS);
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +0000815 const char *visitIntrinsicCall(CallInst &I, unsigned Intrinsic);
Chris Lattner0eade312006-03-24 02:22:33 +0000816 void visitTargetIntrinsic(CallInst &I, unsigned Intrinsic);
Chris Lattner1c08c712005-01-07 07:47:53 +0000817
Chris Lattner1c08c712005-01-07 07:47:53 +0000818 void visitVAStart(CallInst &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000819 void visitVAArg(VAArgInst &I);
820 void visitVAEnd(CallInst &I);
821 void visitVACopy(CallInst &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000822
Chris Lattner1c08c712005-01-07 07:47:53 +0000823 void visitUserOp1(Instruction &I) {
824 assert(0 && "UserOp1 should not exist at instruction selection time!");
825 abort();
826 }
827 void visitUserOp2(Instruction &I) {
828 assert(0 && "UserOp2 should not exist at instruction selection time!");
829 abort();
830 }
Mon P Wang63307c32008-05-05 19:05:59 +0000831
832private:
833 inline const char *implVisitBinaryAtomic(CallInst& I, ISD::NodeType Op);
834
Chris Lattner1c08c712005-01-07 07:47:53 +0000835};
836} // end namespace llvm
837
Dan Gohman6183f782007-07-05 20:12:34 +0000838
Duncan Sandsb988bac2008-02-11 20:58:28 +0000839/// getCopyFromParts - Create a value that contains the specified legal parts
840/// combined into the value they represent. If the parts combine to a type
841/// larger then ValueVT then AssertOp can be used to specify whether the extra
842/// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
Chris Lattner4468c1f2008-03-09 09:38:46 +0000843/// (ISD::AssertSext).
Dan Gohman475871a2008-07-27 21:46:04 +0000844static SDValue getCopyFromParts(SelectionDAG &DAG,
845 const SDValue *Parts,
Dan Gohman6183f782007-07-05 20:12:34 +0000846 unsigned NumParts,
Duncan Sands83ec4b62008-06-06 12:08:01 +0000847 MVT PartVT,
848 MVT ValueVT,
Chris Lattner4468c1f2008-03-09 09:38:46 +0000849 ISD::NodeType AssertOp = ISD::DELETED_NODE) {
Duncan Sands014e04a2008-02-12 20:46:31 +0000850 assert(NumParts > 0 && "No parts to assemble!");
851 TargetLowering &TLI = DAG.getTargetLoweringInfo();
Dan Gohman475871a2008-07-27 21:46:04 +0000852 SDValue Val = Parts[0];
Dan Gohman6183f782007-07-05 20:12:34 +0000853
Duncan Sands014e04a2008-02-12 20:46:31 +0000854 if (NumParts > 1) {
855 // Assemble the value from multiple parts.
Duncan Sands83ec4b62008-06-06 12:08:01 +0000856 if (!ValueVT.isVector()) {
857 unsigned PartBits = PartVT.getSizeInBits();
858 unsigned ValueBits = ValueVT.getSizeInBits();
Dan Gohman6183f782007-07-05 20:12:34 +0000859
Duncan Sands014e04a2008-02-12 20:46:31 +0000860 // Assemble the power of 2 part.
861 unsigned RoundParts = NumParts & (NumParts - 1) ?
862 1 << Log2_32(NumParts) : NumParts;
863 unsigned RoundBits = PartBits * RoundParts;
Duncan Sands83ec4b62008-06-06 12:08:01 +0000864 MVT RoundVT = RoundBits == ValueBits ?
865 ValueVT : MVT::getIntegerVT(RoundBits);
Dan Gohman475871a2008-07-27 21:46:04 +0000866 SDValue Lo, Hi;
Duncan Sands014e04a2008-02-12 20:46:31 +0000867
868 if (RoundParts > 2) {
Duncan Sands83ec4b62008-06-06 12:08:01 +0000869 MVT HalfVT = MVT::getIntegerVT(RoundBits/2);
Duncan Sands014e04a2008-02-12 20:46:31 +0000870 Lo = getCopyFromParts(DAG, Parts, RoundParts/2, PartVT, HalfVT);
871 Hi = getCopyFromParts(DAG, Parts+RoundParts/2, RoundParts/2,
872 PartVT, HalfVT);
Dan Gohman6183f782007-07-05 20:12:34 +0000873 } else {
Duncan Sands014e04a2008-02-12 20:46:31 +0000874 Lo = Parts[0];
875 Hi = Parts[1];
Dan Gohman6183f782007-07-05 20:12:34 +0000876 }
Duncan Sands014e04a2008-02-12 20:46:31 +0000877 if (TLI.isBigEndian())
878 std::swap(Lo, Hi);
879 Val = DAG.getNode(ISD::BUILD_PAIR, RoundVT, Lo, Hi);
880
881 if (RoundParts < NumParts) {
882 // Assemble the trailing non-power-of-2 part.
883 unsigned OddParts = NumParts - RoundParts;
Duncan Sands83ec4b62008-06-06 12:08:01 +0000884 MVT OddVT = MVT::getIntegerVT(OddParts * PartBits);
Duncan Sands014e04a2008-02-12 20:46:31 +0000885 Hi = getCopyFromParts(DAG, Parts+RoundParts, OddParts, PartVT, OddVT);
886
887 // Combine the round and odd parts.
888 Lo = Val;
889 if (TLI.isBigEndian())
890 std::swap(Lo, Hi);
Duncan Sands83ec4b62008-06-06 12:08:01 +0000891 MVT TotalVT = MVT::getIntegerVT(NumParts * PartBits);
Duncan Sands014e04a2008-02-12 20:46:31 +0000892 Hi = DAG.getNode(ISD::ANY_EXTEND, TotalVT, Hi);
893 Hi = DAG.getNode(ISD::SHL, TotalVT, Hi,
Duncan Sands83ec4b62008-06-06 12:08:01 +0000894 DAG.getConstant(Lo.getValueType().getSizeInBits(),
Duncan Sands014e04a2008-02-12 20:46:31 +0000895 TLI.getShiftAmountTy()));
896 Lo = DAG.getNode(ISD::ZERO_EXTEND, TotalVT, Lo);
897 Val = DAG.getNode(ISD::OR, TotalVT, Lo, Hi);
898 }
899 } else {
900 // Handle a multi-element vector.
Duncan Sands83ec4b62008-06-06 12:08:01 +0000901 MVT IntermediateVT, RegisterVT;
Duncan Sands014e04a2008-02-12 20:46:31 +0000902 unsigned NumIntermediates;
903 unsigned NumRegs =
904 TLI.getVectorTypeBreakdown(ValueVT, IntermediateVT, NumIntermediates,
905 RegisterVT);
Duncan Sands014e04a2008-02-12 20:46:31 +0000906 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
Evan Cheng35213342008-05-14 20:29:30 +0000907 NumParts = NumRegs; // Silence a compiler warning.
Duncan Sands014e04a2008-02-12 20:46:31 +0000908 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
909 assert(RegisterVT == Parts[0].getValueType() &&
910 "Part type doesn't match part!");
911
912 // Assemble the parts into intermediate operands.
Dan Gohman475871a2008-07-27 21:46:04 +0000913 SmallVector<SDValue, 8> Ops(NumIntermediates);
Duncan Sands014e04a2008-02-12 20:46:31 +0000914 if (NumIntermediates == NumParts) {
915 // If the register was not expanded, truncate or copy the value,
916 // as appropriate.
917 for (unsigned i = 0; i != NumParts; ++i)
918 Ops[i] = getCopyFromParts(DAG, &Parts[i], 1,
919 PartVT, IntermediateVT);
920 } else if (NumParts > 0) {
921 // If the intermediate type was expanded, build the intermediate operands
922 // from the parts.
923 assert(NumParts % NumIntermediates == 0 &&
924 "Must expand into a divisible number of parts!");
925 unsigned Factor = NumParts / NumIntermediates;
926 for (unsigned i = 0; i != NumIntermediates; ++i)
927 Ops[i] = getCopyFromParts(DAG, &Parts[i * Factor], Factor,
928 PartVT, IntermediateVT);
929 }
930
931 // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the intermediate
932 // operands.
Duncan Sands83ec4b62008-06-06 12:08:01 +0000933 Val = DAG.getNode(IntermediateVT.isVector() ?
Duncan Sands014e04a2008-02-12 20:46:31 +0000934 ISD::CONCAT_VECTORS : ISD::BUILD_VECTOR,
935 ValueVT, &Ops[0], NumIntermediates);
Dan Gohman6183f782007-07-05 20:12:34 +0000936 }
Dan Gohman6183f782007-07-05 20:12:34 +0000937 }
938
Duncan Sands014e04a2008-02-12 20:46:31 +0000939 // There is now one part, held in Val. Correct it to match ValueVT.
940 PartVT = Val.getValueType();
Dan Gohman6183f782007-07-05 20:12:34 +0000941
Duncan Sands014e04a2008-02-12 20:46:31 +0000942 if (PartVT == ValueVT)
943 return Val;
Dan Gohman6183f782007-07-05 20:12:34 +0000944
Duncan Sands83ec4b62008-06-06 12:08:01 +0000945 if (PartVT.isVector()) {
946 assert(ValueVT.isVector() && "Unknown vector conversion!");
Duncan Sands014e04a2008-02-12 20:46:31 +0000947 return DAG.getNode(ISD::BIT_CONVERT, ValueVT, Val);
Dan Gohman6183f782007-07-05 20:12:34 +0000948 }
Duncan Sands014e04a2008-02-12 20:46:31 +0000949
Duncan Sands83ec4b62008-06-06 12:08:01 +0000950 if (ValueVT.isVector()) {
951 assert(ValueVT.getVectorElementType() == PartVT &&
952 ValueVT.getVectorNumElements() == 1 &&
Duncan Sands014e04a2008-02-12 20:46:31 +0000953 "Only trivial scalar-to-vector conversions should get here!");
954 return DAG.getNode(ISD::BUILD_VECTOR, ValueVT, Val);
955 }
956
Duncan Sands83ec4b62008-06-06 12:08:01 +0000957 if (PartVT.isInteger() &&
958 ValueVT.isInteger()) {
Duncan Sands8e4eb092008-06-08 20:54:56 +0000959 if (ValueVT.bitsLT(PartVT)) {
Duncan Sands014e04a2008-02-12 20:46:31 +0000960 // For a truncate, see if we have any information to
961 // indicate whether the truncated bits will always be
962 // zero or sign-extension.
963 if (AssertOp != ISD::DELETED_NODE)
964 Val = DAG.getNode(AssertOp, PartVT, Val,
965 DAG.getValueType(ValueVT));
966 return DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
967 } else {
968 return DAG.getNode(ISD::ANY_EXTEND, ValueVT, Val);
969 }
970 }
971
Duncan Sands83ec4b62008-06-06 12:08:01 +0000972 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
Duncan Sands8e4eb092008-06-08 20:54:56 +0000973 if (ValueVT.bitsLT(Val.getValueType()))
Chris Lattner4468c1f2008-03-09 09:38:46 +0000974 // FP_ROUND's are always exact here.
Chris Lattnerd43d85c2008-03-09 07:47:22 +0000975 return DAG.getNode(ISD::FP_ROUND, ValueVT, Val,
Chris Lattner4468c1f2008-03-09 09:38:46 +0000976 DAG.getIntPtrConstant(1));
Chris Lattnerd43d85c2008-03-09 07:47:22 +0000977 return DAG.getNode(ISD::FP_EXTEND, ValueVT, Val);
978 }
Duncan Sands014e04a2008-02-12 20:46:31 +0000979
Duncan Sands83ec4b62008-06-06 12:08:01 +0000980 if (PartVT.getSizeInBits() == ValueVT.getSizeInBits())
Duncan Sands014e04a2008-02-12 20:46:31 +0000981 return DAG.getNode(ISD::BIT_CONVERT, ValueVT, Val);
982
983 assert(0 && "Unknown mismatch!");
Dan Gohman475871a2008-07-27 21:46:04 +0000984 return SDValue();
Dan Gohman6183f782007-07-05 20:12:34 +0000985}
986
Duncan Sandsb988bac2008-02-11 20:58:28 +0000987/// getCopyToParts - Create a series of nodes that contain the specified value
988/// split into legal parts. If the parts contain more bits than Val, then, for
989/// integers, ExtendKind can be used to specify how to generate the extra bits.
Dan Gohman6183f782007-07-05 20:12:34 +0000990static void getCopyToParts(SelectionDAG &DAG,
Dan Gohman475871a2008-07-27 21:46:04 +0000991 SDValue Val,
992 SDValue *Parts,
Dan Gohman6183f782007-07-05 20:12:34 +0000993 unsigned NumParts,
Duncan Sands83ec4b62008-06-06 12:08:01 +0000994 MVT PartVT,
Duncan Sandsb988bac2008-02-11 20:58:28 +0000995 ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
Dan Gohman25ac7e82007-08-10 14:59:38 +0000996 TargetLowering &TLI = DAG.getTargetLoweringInfo();
Duncan Sands83ec4b62008-06-06 12:08:01 +0000997 MVT PtrVT = TLI.getPointerTy();
998 MVT ValueVT = Val.getValueType();
999 unsigned PartBits = PartVT.getSizeInBits();
Duncan Sands014e04a2008-02-12 20:46:31 +00001000 assert(TLI.isTypeLegal(PartVT) && "Copying to an illegal type!");
Dan Gohman6183f782007-07-05 20:12:34 +00001001
Duncan Sands014e04a2008-02-12 20:46:31 +00001002 if (!NumParts)
1003 return;
1004
Duncan Sands83ec4b62008-06-06 12:08:01 +00001005 if (!ValueVT.isVector()) {
Duncan Sands014e04a2008-02-12 20:46:31 +00001006 if (PartVT == ValueVT) {
1007 assert(NumParts == 1 && "No-op copy with multiple parts!");
1008 Parts[0] = Val;
Dan Gohman6183f782007-07-05 20:12:34 +00001009 return;
1010 }
1011
Duncan Sands83ec4b62008-06-06 12:08:01 +00001012 if (NumParts * PartBits > ValueVT.getSizeInBits()) {
Duncan Sands014e04a2008-02-12 20:46:31 +00001013 // If the parts cover more bits than the value has, promote the value.
Duncan Sands83ec4b62008-06-06 12:08:01 +00001014 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
Duncan Sands014e04a2008-02-12 20:46:31 +00001015 assert(NumParts == 1 && "Do not know what to promote to!");
Dan Gohman6183f782007-07-05 20:12:34 +00001016 Val = DAG.getNode(ISD::FP_EXTEND, PartVT, Val);
Duncan Sands83ec4b62008-06-06 12:08:01 +00001017 } else if (PartVT.isInteger() && ValueVT.isInteger()) {
1018 ValueVT = MVT::getIntegerVT(NumParts * PartBits);
Duncan Sands014e04a2008-02-12 20:46:31 +00001019 Val = DAG.getNode(ExtendKind, ValueVT, Val);
1020 } else {
1021 assert(0 && "Unknown mismatch!");
1022 }
Duncan Sands83ec4b62008-06-06 12:08:01 +00001023 } else if (PartBits == ValueVT.getSizeInBits()) {
Duncan Sands014e04a2008-02-12 20:46:31 +00001024 // Different types of the same size.
1025 assert(NumParts == 1 && PartVT != ValueVT);
1026 Val = DAG.getNode(ISD::BIT_CONVERT, PartVT, Val);
Duncan Sands83ec4b62008-06-06 12:08:01 +00001027 } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
Duncan Sands014e04a2008-02-12 20:46:31 +00001028 // If the parts cover less bits than value has, truncate the value.
Duncan Sands83ec4b62008-06-06 12:08:01 +00001029 if (PartVT.isInteger() && ValueVT.isInteger()) {
1030 ValueVT = MVT::getIntegerVT(NumParts * PartBits);
Duncan Sands014e04a2008-02-12 20:46:31 +00001031 Val = DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
Dan Gohman6183f782007-07-05 20:12:34 +00001032 } else {
1033 assert(0 && "Unknown mismatch!");
1034 }
1035 }
Duncan Sands014e04a2008-02-12 20:46:31 +00001036
1037 // The value may have changed - recompute ValueVT.
1038 ValueVT = Val.getValueType();
Duncan Sands83ec4b62008-06-06 12:08:01 +00001039 assert(NumParts * PartBits == ValueVT.getSizeInBits() &&
Duncan Sands014e04a2008-02-12 20:46:31 +00001040 "Failed to tile the value with PartVT!");
1041
1042 if (NumParts == 1) {
1043 assert(PartVT == ValueVT && "Type conversion failed!");
1044 Parts[0] = Val;
1045 return;
1046 }
1047
1048 // Expand the value into multiple parts.
1049 if (NumParts & (NumParts - 1)) {
1050 // The number of parts is not a power of 2. Split off and copy the tail.
Duncan Sands83ec4b62008-06-06 12:08:01 +00001051 assert(PartVT.isInteger() && ValueVT.isInteger() &&
Duncan Sands014e04a2008-02-12 20:46:31 +00001052 "Do not know what to expand to!");
1053 unsigned RoundParts = 1 << Log2_32(NumParts);
1054 unsigned RoundBits = RoundParts * PartBits;
1055 unsigned OddParts = NumParts - RoundParts;
Dan Gohman475871a2008-07-27 21:46:04 +00001056 SDValue OddVal = DAG.getNode(ISD::SRL, ValueVT, Val,
Duncan Sands014e04a2008-02-12 20:46:31 +00001057 DAG.getConstant(RoundBits,
1058 TLI.getShiftAmountTy()));
1059 getCopyToParts(DAG, OddVal, Parts + RoundParts, OddParts, PartVT);
1060 if (TLI.isBigEndian())
1061 // The odd parts were reversed by getCopyToParts - unreverse them.
1062 std::reverse(Parts + RoundParts, Parts + NumParts);
1063 NumParts = RoundParts;
Duncan Sands83ec4b62008-06-06 12:08:01 +00001064 ValueVT = MVT::getIntegerVT(NumParts * PartBits);
Duncan Sands014e04a2008-02-12 20:46:31 +00001065 Val = DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
1066 }
1067
1068 // The number of parts is a power of 2. Repeatedly bisect the value using
1069 // EXTRACT_ELEMENT.
Duncan Sands25eb0432008-03-12 20:30:08 +00001070 Parts[0] = DAG.getNode(ISD::BIT_CONVERT,
Duncan Sands83ec4b62008-06-06 12:08:01 +00001071 MVT::getIntegerVT(ValueVT.getSizeInBits()),
Duncan Sands25eb0432008-03-12 20:30:08 +00001072 Val);
Duncan Sands014e04a2008-02-12 20:46:31 +00001073 for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
1074 for (unsigned i = 0; i < NumParts; i += StepSize) {
1075 unsigned ThisBits = StepSize * PartBits / 2;
Duncan Sands83ec4b62008-06-06 12:08:01 +00001076 MVT ThisVT = MVT::getIntegerVT (ThisBits);
Dan Gohman475871a2008-07-27 21:46:04 +00001077 SDValue &Part0 = Parts[i];
1078 SDValue &Part1 = Parts[i+StepSize/2];
Duncan Sands014e04a2008-02-12 20:46:31 +00001079
Duncan Sands25eb0432008-03-12 20:30:08 +00001080 Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, ThisVT, Part0,
1081 DAG.getConstant(1, PtrVT));
1082 Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, ThisVT, Part0,
1083 DAG.getConstant(0, PtrVT));
1084
1085 if (ThisBits == PartBits && ThisVT != PartVT) {
1086 Part0 = DAG.getNode(ISD::BIT_CONVERT, PartVT, Part0);
1087 Part1 = DAG.getNode(ISD::BIT_CONVERT, PartVT, Part1);
1088 }
Duncan Sands014e04a2008-02-12 20:46:31 +00001089 }
1090 }
1091
1092 if (TLI.isBigEndian())
1093 std::reverse(Parts, Parts + NumParts);
1094
1095 return;
1096 }
1097
1098 // Vector ValueVT.
1099 if (NumParts == 1) {
1100 if (PartVT != ValueVT) {
Duncan Sands83ec4b62008-06-06 12:08:01 +00001101 if (PartVT.isVector()) {
Duncan Sands014e04a2008-02-12 20:46:31 +00001102 Val = DAG.getNode(ISD::BIT_CONVERT, PartVT, Val);
1103 } else {
Duncan Sands83ec4b62008-06-06 12:08:01 +00001104 assert(ValueVT.getVectorElementType() == PartVT &&
1105 ValueVT.getVectorNumElements() == 1 &&
Duncan Sands014e04a2008-02-12 20:46:31 +00001106 "Only trivial vector-to-scalar conversions should get here!");
1107 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, PartVT, Val,
1108 DAG.getConstant(0, PtrVT));
1109 }
1110 }
1111
Dan Gohman6183f782007-07-05 20:12:34 +00001112 Parts[0] = Val;
1113 return;
1114 }
1115
1116 // Handle a multi-element vector.
Duncan Sands83ec4b62008-06-06 12:08:01 +00001117 MVT IntermediateVT, RegisterVT;
Dan Gohman6183f782007-07-05 20:12:34 +00001118 unsigned NumIntermediates;
1119 unsigned NumRegs =
1120 DAG.getTargetLoweringInfo()
1121 .getVectorTypeBreakdown(ValueVT, IntermediateVT, NumIntermediates,
1122 RegisterVT);
Duncan Sands83ec4b62008-06-06 12:08:01 +00001123 unsigned NumElements = ValueVT.getVectorNumElements();
Dan Gohman6183f782007-07-05 20:12:34 +00001124
1125 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
Evan Cheng35213342008-05-14 20:29:30 +00001126 NumParts = NumRegs; // Silence a compiler warning.
Dan Gohman6183f782007-07-05 20:12:34 +00001127 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
1128
1129 // Split the vector into intermediate operands.
Dan Gohman475871a2008-07-27 21:46:04 +00001130 SmallVector<SDValue, 8> Ops(NumIntermediates);
Dan Gohman6183f782007-07-05 20:12:34 +00001131 for (unsigned i = 0; i != NumIntermediates; ++i)
Duncan Sands83ec4b62008-06-06 12:08:01 +00001132 if (IntermediateVT.isVector())
Dan Gohman6183f782007-07-05 20:12:34 +00001133 Ops[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR,
1134 IntermediateVT, Val,
1135 DAG.getConstant(i * (NumElements / NumIntermediates),
Dan Gohman25ac7e82007-08-10 14:59:38 +00001136 PtrVT));
Dan Gohman6183f782007-07-05 20:12:34 +00001137 else
1138 Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
1139 IntermediateVT, Val,
Dan Gohman25ac7e82007-08-10 14:59:38 +00001140 DAG.getConstant(i, PtrVT));
Dan Gohman6183f782007-07-05 20:12:34 +00001141
1142 // Split the intermediate operands into legal parts.
1143 if (NumParts == NumIntermediates) {
1144 // If the register was not expanded, promote or copy the value,
1145 // as appropriate.
1146 for (unsigned i = 0; i != NumParts; ++i)
Dan Gohman532dc2e2007-07-09 20:59:04 +00001147 getCopyToParts(DAG, Ops[i], &Parts[i], 1, PartVT);
Dan Gohman6183f782007-07-05 20:12:34 +00001148 } else if (NumParts > 0) {
1149 // If the intermediate type was expanded, split each the value into
1150 // legal parts.
1151 assert(NumParts % NumIntermediates == 0 &&
1152 "Must expand into a divisible number of parts!");
1153 unsigned Factor = NumParts / NumIntermediates;
1154 for (unsigned i = 0; i != NumIntermediates; ++i)
Dan Gohman532dc2e2007-07-09 20:59:04 +00001155 getCopyToParts(DAG, Ops[i], &Parts[i * Factor], Factor, PartVT);
Dan Gohman6183f782007-07-05 20:12:34 +00001156 }
1157}
1158
1159
Dan Gohman475871a2008-07-27 21:46:04 +00001160SDValue SelectionDAGLowering::getValue(const Value *V) {
1161 SDValue &N = NodeMap[V];
Chris Lattner199862b2006-03-16 19:57:50 +00001162 if (N.Val) return N;
1163
Chris Lattner199862b2006-03-16 19:57:50 +00001164 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V))) {
Duncan Sands83ec4b62008-06-06 12:08:01 +00001165 MVT VT = TLI.getValueType(V->getType(), true);
Chris Lattnerb606dba2008-04-28 06:44:42 +00001166
1167 if (ConstantInt *CI = dyn_cast<ConstantInt>(C))
1168 return N = DAG.getConstant(CI->getValue(), VT);
1169
1170 if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
Chris Lattner199862b2006-03-16 19:57:50 +00001171 return N = DAG.getGlobalAddress(GV, VT);
Chris Lattnerb606dba2008-04-28 06:44:42 +00001172
1173 if (isa<ConstantPointerNull>(C))
Chris Lattner199862b2006-03-16 19:57:50 +00001174 return N = DAG.getConstant(0, TLI.getPointerTy());
Chris Lattnerb606dba2008-04-28 06:44:42 +00001175
1176 if (ConstantFP *CFP = dyn_cast<ConstantFP>(C))
1177 return N = DAG.getConstantFP(CFP->getValueAPF(), VT);
1178
Dan Gohman1d685a42008-06-07 02:02:36 +00001179 if (isa<UndefValue>(C) && !isa<VectorType>(V->getType()) &&
1180 !V->getType()->isAggregateType())
Chris Lattner6833b062008-04-28 07:16:35 +00001181 return N = DAG.getNode(ISD::UNDEF, VT);
Chris Lattnerb606dba2008-04-28 06:44:42 +00001182
1183 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
1184 visit(CE->getOpcode(), *CE);
Dan Gohman475871a2008-07-27 21:46:04 +00001185 SDValue N1 = NodeMap[V];
Chris Lattnerb606dba2008-04-28 06:44:42 +00001186 assert(N1.Val && "visit didn't populate the ValueMap!");
1187 return N1;
1188 }
1189
Dan Gohman1d685a42008-06-07 02:02:36 +00001190 if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
Dan Gohman475871a2008-07-27 21:46:04 +00001191 SmallVector<SDValue, 4> Constants;
Dan Gohman1d685a42008-06-07 02:02:36 +00001192 for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end();
1193 OI != OE; ++OI) {
1194 SDNode *Val = getValue(*OI).Val;
Duncan Sands4bdcb612008-07-02 17:40:58 +00001195 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
Dan Gohman475871a2008-07-27 21:46:04 +00001196 Constants.push_back(SDValue(Val, i));
Dan Gohman1d685a42008-06-07 02:02:36 +00001197 }
Duncan Sands4bdcb612008-07-02 17:40:58 +00001198 return DAG.getMergeValues(&Constants[0], Constants.size());
Dan Gohman1d685a42008-06-07 02:02:36 +00001199 }
1200
Dan Gohman1f565bc2008-08-04 23:30:41 +00001201 if (isa<StructType>(C->getType()) || isa<ArrayType>(C->getType())) {
Dan Gohman1d685a42008-06-07 02:02:36 +00001202 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
Dan Gohman1f565bc2008-08-04 23:30:41 +00001203 "Unknown struct or array constant!");
Dan Gohman1d685a42008-06-07 02:02:36 +00001204
Dan Gohman1f565bc2008-08-04 23:30:41 +00001205 SmallVector<MVT, 4> ValueVTs;
1206 ComputeValueVTs(TLI, C->getType(), ValueVTs);
1207 unsigned NumElts = ValueVTs.size();
Dan Gohman8a6ccb52008-06-09 15:21:47 +00001208 if (NumElts == 0)
Dan Gohman475871a2008-07-27 21:46:04 +00001209 return SDValue(); // empty struct
1210 SmallVector<SDValue, 4> Constants(NumElts);
Dan Gohman1f565bc2008-08-04 23:30:41 +00001211 for (unsigned i = 0; i != NumElts; ++i) {
1212 MVT EltVT = ValueVTs[i];
Dan Gohman1d685a42008-06-07 02:02:36 +00001213 if (isa<UndefValue>(C))
1214 Constants[i] = DAG.getNode(ISD::UNDEF, EltVT);
1215 else if (EltVT.isFloatingPoint())
1216 Constants[i] = DAG.getConstantFP(0, EltVT);
1217 else
1218 Constants[i] = DAG.getConstant(0, EltVT);
1219 }
Dan Gohman1f565bc2008-08-04 23:30:41 +00001220 return DAG.getMergeValues(&Constants[0], NumElts);
Dan Gohman1d685a42008-06-07 02:02:36 +00001221 }
1222
Chris Lattner6833b062008-04-28 07:16:35 +00001223 const VectorType *VecTy = cast<VectorType>(V->getType());
Chris Lattnerb606dba2008-04-28 06:44:42 +00001224 unsigned NumElements = VecTy->getNumElements();
Chris Lattnerb606dba2008-04-28 06:44:42 +00001225
Chris Lattner6833b062008-04-28 07:16:35 +00001226 // Now that we know the number and type of the elements, get that number of
1227 // elements into the Ops array based on what kind of constant it is.
Dan Gohman475871a2008-07-27 21:46:04 +00001228 SmallVector<SDValue, 16> Ops;
Chris Lattnerb606dba2008-04-28 06:44:42 +00001229 if (ConstantVector *CP = dyn_cast<ConstantVector>(C)) {
1230 for (unsigned i = 0; i != NumElements; ++i)
1231 Ops.push_back(getValue(CP->getOperand(i)));
1232 } else {
Chris Lattner6833b062008-04-28 07:16:35 +00001233 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
1234 "Unknown vector constant!");
Duncan Sands83ec4b62008-06-06 12:08:01 +00001235 MVT EltVT = TLI.getValueType(VecTy->getElementType());
Chris Lattner6833b062008-04-28 07:16:35 +00001236
Dan Gohman475871a2008-07-27 21:46:04 +00001237 SDValue Op;
Chris Lattner6833b062008-04-28 07:16:35 +00001238 if (isa<UndefValue>(C))
1239 Op = DAG.getNode(ISD::UNDEF, EltVT);
Duncan Sands83ec4b62008-06-06 12:08:01 +00001240 else if (EltVT.isFloatingPoint())
Chris Lattner6833b062008-04-28 07:16:35 +00001241 Op = DAG.getConstantFP(0, EltVT);
Chris Lattnerb606dba2008-04-28 06:44:42 +00001242 else
Chris Lattner6833b062008-04-28 07:16:35 +00001243 Op = DAG.getConstant(0, EltVT);
Chris Lattnerb606dba2008-04-28 06:44:42 +00001244 Ops.assign(NumElements, Op);
1245 }
1246
1247 // Create a BUILD_VECTOR node.
1248 return NodeMap[V] = DAG.getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
Chris Lattner199862b2006-03-16 19:57:50 +00001249 }
1250
Chris Lattnerb606dba2008-04-28 06:44:42 +00001251 // If this is a static alloca, generate it as the frameindex instead of
1252 // computation.
Chris Lattner199862b2006-03-16 19:57:50 +00001253 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1254 std::map<const AllocaInst*, int>::iterator SI =
Chris Lattnerb606dba2008-04-28 06:44:42 +00001255 FuncInfo.StaticAllocaMap.find(AI);
Chris Lattner199862b2006-03-16 19:57:50 +00001256 if (SI != FuncInfo.StaticAllocaMap.end())
1257 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
1258 }
1259
Chris Lattner251db182007-02-25 18:40:32 +00001260 unsigned InReg = FuncInfo.ValueMap[V];
1261 assert(InReg && "Value not in map!");
Chris Lattner199862b2006-03-16 19:57:50 +00001262
Chris Lattner6833b062008-04-28 07:16:35 +00001263 RegsForValue RFV(TLI, InReg, V->getType());
Dan Gohman475871a2008-07-27 21:46:04 +00001264 SDValue Chain = DAG.getEntryNode();
Dan Gohmanb6f5b002007-06-28 23:29:44 +00001265 return RFV.getCopyFromRegs(DAG, Chain, NULL);
Chris Lattner199862b2006-03-16 19:57:50 +00001266}
1267
1268
Chris Lattner1c08c712005-01-07 07:47:53 +00001269void SelectionDAGLowering::visitRet(ReturnInst &I) {
1270 if (I.getNumOperands() == 0) {
Dan Gohman86e1ebf2008-03-27 19:56:19 +00001271 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getControlRoot()));
Chris Lattner1c08c712005-01-07 07:47:53 +00001272 return;
1273 }
Chris Lattnerb606dba2008-04-28 06:44:42 +00001274
Dan Gohman475871a2008-07-27 21:46:04 +00001275 SmallVector<SDValue, 8> NewValues;
Dan Gohman86e1ebf2008-03-27 19:56:19 +00001276 NewValues.push_back(getControlRoot());
1277 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
Dan Gohman475871a2008-07-27 21:46:04 +00001278 SDValue RetOp = getValue(I.getOperand(i));
Duncan Sandsb988bac2008-02-11 20:58:28 +00001279
Dan Gohmanab8ec0a2008-06-20 01:29:26 +00001280 SmallVector<MVT, 4> ValueVTs;
1281 ComputeValueVTs(TLI, I.getOperand(i)->getType(), ValueVTs);
1282 for (unsigned j = 0, f = ValueVTs.size(); j != f; ++j) {
1283 MVT VT = ValueVTs[j];
Duncan Sandsb988bac2008-02-11 20:58:28 +00001284
Dan Gohmanab8ec0a2008-06-20 01:29:26 +00001285 // FIXME: C calling convention requires the return type to be promoted to
1286 // at least 32-bit. But this is not necessary for non-C calling conventions.
1287 if (VT.isInteger()) {
1288 MVT MinVT = TLI.getRegisterType(MVT::i32);
1289 if (VT.bitsLT(MinVT))
1290 VT = MinVT;
1291 }
Duncan Sandsb988bac2008-02-11 20:58:28 +00001292
Dan Gohmanab8ec0a2008-06-20 01:29:26 +00001293 unsigned NumParts = TLI.getNumRegisters(VT);
1294 MVT PartVT = TLI.getRegisterType(VT);
Dan Gohman475871a2008-07-27 21:46:04 +00001295 SmallVector<SDValue, 4> Parts(NumParts);
Dan Gohmanab8ec0a2008-06-20 01:29:26 +00001296 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
1297
1298 const Function *F = I.getParent()->getParent();
1299 if (F->paramHasAttr(0, ParamAttr::SExt))
1300 ExtendKind = ISD::SIGN_EXTEND;
1301 else if (F->paramHasAttr(0, ParamAttr::ZExt))
1302 ExtendKind = ISD::ZERO_EXTEND;
Duncan Sandsb988bac2008-02-11 20:58:28 +00001303
Dan Gohman475871a2008-07-27 21:46:04 +00001304 getCopyToParts(DAG, SDValue(RetOp.Val, RetOp.ResNo + j),
Dan Gohmanab8ec0a2008-06-20 01:29:26 +00001305 &Parts[0], NumParts, PartVT, ExtendKind);
Duncan Sandsb988bac2008-02-11 20:58:28 +00001306
Dan Gohmanab8ec0a2008-06-20 01:29:26 +00001307 for (unsigned i = 0; i < NumParts; ++i) {
1308 NewValues.push_back(Parts[i]);
1309 NewValues.push_back(DAG.getArgFlags(ISD::ArgFlagsTy()));
1310 }
Nate Begemanee625572006-01-27 21:09:22 +00001311 }
Chris Lattner1c08c712005-01-07 07:47:53 +00001312 }
Chris Lattnerbd564bf2006-08-08 02:23:42 +00001313 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other,
1314 &NewValues[0], NewValues.size()));
Chris Lattner1c08c712005-01-07 07:47:53 +00001315}
1316
Chris Lattner571e4342006-10-27 21:36:01 +00001317/// ExportFromCurrentBlock - If this condition isn't known to be exported from
1318/// the current basic block, add it to ValueMap now so that we'll get a
1319/// CopyTo/FromReg.
1320void SelectionDAGLowering::ExportFromCurrentBlock(Value *V) {
1321 // No need to export constants.
1322 if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
1323
1324 // Already exported?
1325 if (FuncInfo.isExportedInst(V)) return;
1326
1327 unsigned Reg = FuncInfo.InitializeRegForValue(V);
Dan Gohman86e1ebf2008-03-27 19:56:19 +00001328 CopyValueToVirtualRegister(V, Reg);
Chris Lattner571e4342006-10-27 21:36:01 +00001329}
1330
Chris Lattner8c494ab2006-10-27 23:50:33 +00001331bool SelectionDAGLowering::isExportableFromCurrentBlock(Value *V,
1332 const BasicBlock *FromBB) {
1333 // The operands of the setcc have to be in this block. We don't know
1334 // how to export them from some other block.
1335 if (Instruction *VI = dyn_cast<Instruction>(V)) {
1336 // Can export from current BB.
1337 if (VI->getParent() == FromBB)
1338 return true;
1339
1340 // Is already exported, noop.
1341 return FuncInfo.isExportedInst(V);
1342 }
1343
1344 // If this is an argument, we can export it if the BB is the entry block or
1345 // if it is already exported.
1346 if (isa<Argument>(V)) {
1347 if (FromBB == &FromBB->getParent()->getEntryBlock())
1348 return true;
1349
1350 // Otherwise, can only export this if it is already exported.
1351 return FuncInfo.isExportedInst(V);
1352 }
1353
1354 // Otherwise, constants can always be exported.
1355 return true;
1356}
1357
Chris Lattner6a586c82006-10-29 21:01:20 +00001358static bool InBlock(const Value *V, const BasicBlock *BB) {
1359 if (const Instruction *I = dyn_cast<Instruction>(V))
1360 return I->getParent() == BB;
1361 return true;
1362}
1363
Chris Lattner571e4342006-10-27 21:36:01 +00001364/// FindMergedConditions - If Cond is an expression like
1365void SelectionDAGLowering::FindMergedConditions(Value *Cond,
1366 MachineBasicBlock *TBB,
1367 MachineBasicBlock *FBB,
1368 MachineBasicBlock *CurBB,
1369 unsigned Opc) {
Chris Lattner571e4342006-10-27 21:36:01 +00001370 // If this node is not part of the or/and tree, emit it as a branch.
Reid Spencere4d87aa2006-12-23 06:05:41 +00001371 Instruction *BOp = dyn_cast<Instruction>(Cond);
Chris Lattner571e4342006-10-27 21:36:01 +00001372
Reid Spencere4d87aa2006-12-23 06:05:41 +00001373 if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
1374 (unsigned)BOp->getOpcode() != Opc || !BOp->hasOneUse() ||
Chris Lattner6a586c82006-10-29 21:01:20 +00001375 BOp->getParent() != CurBB->getBasicBlock() ||
1376 !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
1377 !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
Chris Lattner571e4342006-10-27 21:36:01 +00001378 const BasicBlock *BB = CurBB->getBasicBlock();
1379
Reid Spencere4d87aa2006-12-23 06:05:41 +00001380 // If the leaf of the tree is a comparison, merge the condition into
1381 // the caseblock.
1382 if ((isa<ICmpInst>(Cond) || isa<FCmpInst>(Cond)) &&
1383 // The operands of the cmp have to be in this block. We don't know
Chris Lattner5a145f02006-10-29 18:23:37 +00001384 // how to export them from some other block. If this is the first block
1385 // of the sequence, no exporting is needed.
1386 (CurBB == CurMBB ||
1387 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
1388 isExportableFromCurrentBlock(BOp->getOperand(1), BB)))) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00001389 BOp = cast<Instruction>(Cond);
1390 ISD::CondCode Condition;
1391 if (ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
1392 switch (IC->getPredicate()) {
1393 default: assert(0 && "Unknown icmp predicate opcode!");
1394 case ICmpInst::ICMP_EQ: Condition = ISD::SETEQ; break;
1395 case ICmpInst::ICMP_NE: Condition = ISD::SETNE; break;
1396 case ICmpInst::ICMP_SLE: Condition = ISD::SETLE; break;
1397 case ICmpInst::ICMP_ULE: Condition = ISD::SETULE; break;
1398 case ICmpInst::ICMP_SGE: Condition = ISD::SETGE; break;
1399 case ICmpInst::ICMP_UGE: Condition = ISD::SETUGE; break;
1400 case ICmpInst::ICMP_SLT: Condition = ISD::SETLT; break;
1401 case ICmpInst::ICMP_ULT: Condition = ISD::SETULT; break;
1402 case ICmpInst::ICMP_SGT: Condition = ISD::SETGT; break;
1403 case ICmpInst::ICMP_UGT: Condition = ISD::SETUGT; break;
1404 }
1405 } else if (FCmpInst *FC = dyn_cast<FCmpInst>(Cond)) {
1406 ISD::CondCode FPC, FOC;
1407 switch (FC->getPredicate()) {
1408 default: assert(0 && "Unknown fcmp predicate opcode!");
1409 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
1410 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
1411 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
1412 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
1413 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
1414 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
1415 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
Chris Lattner6bf30ab2008-05-01 07:26:11 +00001416 case FCmpInst::FCMP_ORD: FOC = FPC = ISD::SETO; break;
1417 case FCmpInst::FCMP_UNO: FOC = FPC = ISD::SETUO; break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00001418 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
1419 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
1420 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
1421 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
1422 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
1423 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
1424 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
1425 }
1426 if (FiniteOnlyFPMath())
1427 Condition = FOC;
1428 else
1429 Condition = FPC;
1430 } else {
Chris Lattner0da331f2007-02-04 01:31:47 +00001431 Condition = ISD::SETEQ; // silence warning.
Reid Spencere4d87aa2006-12-23 06:05:41 +00001432 assert(0 && "Unknown compare instruction");
Chris Lattner571e4342006-10-27 21:36:01 +00001433 }
1434
Chris Lattner571e4342006-10-27 21:36:01 +00001435 SelectionDAGISel::CaseBlock CB(Condition, BOp->getOperand(0),
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001436 BOp->getOperand(1), NULL, TBB, FBB, CurBB);
Chris Lattner571e4342006-10-27 21:36:01 +00001437 SwitchCases.push_back(CB);
1438 return;
1439 }
1440
1441 // Create a CaseBlock record representing this branch.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001442 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, Cond, ConstantInt::getTrue(),
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001443 NULL, TBB, FBB, CurBB);
Chris Lattner571e4342006-10-27 21:36:01 +00001444 SwitchCases.push_back(CB);
Chris Lattner571e4342006-10-27 21:36:01 +00001445 return;
1446 }
1447
Chris Lattnerd2f9ee92006-10-27 21:54:23 +00001448
1449 // Create TmpBB after CurBB.
Chris Lattner571e4342006-10-27 21:36:01 +00001450 MachineFunction::iterator BBI = CurBB;
Dan Gohman0e5f1302008-07-07 23:02:41 +00001451 MachineFunction &MF = DAG.getMachineFunction();
1452 MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
1453 CurBB->getParent()->insert(++BBI, TmpBB);
Chris Lattner571e4342006-10-27 21:36:01 +00001454
Chris Lattnerd2f9ee92006-10-27 21:54:23 +00001455 if (Opc == Instruction::Or) {
1456 // Codegen X | Y as:
1457 // jmp_if_X TBB
1458 // jmp TmpBB
1459 // TmpBB:
1460 // jmp_if_Y TBB
1461 // jmp FBB
1462 //
Chris Lattner571e4342006-10-27 21:36:01 +00001463
Chris Lattnerd2f9ee92006-10-27 21:54:23 +00001464 // Emit the LHS condition.
1465 FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, Opc);
1466
1467 // Emit the RHS condition into TmpBB.
1468 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
1469 } else {
1470 assert(Opc == Instruction::And && "Unknown merge op!");
1471 // Codegen X & Y as:
1472 // jmp_if_X TmpBB
1473 // jmp FBB
1474 // TmpBB:
1475 // jmp_if_Y TBB
1476 // jmp FBB
1477 //
1478 // This requires creation of TmpBB after CurBB.
1479
1480 // Emit the LHS condition.
1481 FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, Opc);
1482
1483 // Emit the RHS condition into TmpBB.
1484 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
1485 }
Chris Lattner571e4342006-10-27 21:36:01 +00001486}
1487
Chris Lattnerdf19f272006-10-31 22:37:42 +00001488/// If the set of cases should be emitted as a series of branches, return true.
1489/// If we should emit this as a bunch of and/or'd together conditions, return
1490/// false.
1491static bool
1492ShouldEmitAsBranches(const std::vector<SelectionDAGISel::CaseBlock> &Cases) {
1493 if (Cases.size() != 2) return true;
1494
Chris Lattner0ccb5002006-10-31 23:06:00 +00001495 // If this is two comparisons of the same values or'd or and'd together, they
1496 // will get folded into a single comparison, so don't emit two blocks.
1497 if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
1498 Cases[0].CmpRHS == Cases[1].CmpRHS) ||
1499 (Cases[0].CmpRHS == Cases[1].CmpLHS &&
1500 Cases[0].CmpLHS == Cases[1].CmpRHS)) {
1501 return false;
1502 }
1503
Chris Lattnerdf19f272006-10-31 22:37:42 +00001504 return true;
1505}
1506
Chris Lattner1c08c712005-01-07 07:47:53 +00001507void SelectionDAGLowering::visitBr(BranchInst &I) {
1508 // Update machine-CFG edges.
1509 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
Chris Lattner1c08c712005-01-07 07:47:53 +00001510
1511 // Figure out which block is immediately after the current one.
1512 MachineBasicBlock *NextBlock = 0;
1513 MachineFunction::iterator BBI = CurMBB;
1514 if (++BBI != CurMBB->getParent()->end())
1515 NextBlock = BBI;
1516
1517 if (I.isUnconditional()) {
Owen Anderson2d389e82008-06-07 00:00:23 +00001518 // Update machine-CFG edges.
1519 CurMBB->addSuccessor(Succ0MBB);
1520
Chris Lattner1c08c712005-01-07 07:47:53 +00001521 // If this is not a fall-through branch, emit the branch.
1522 if (Succ0MBB != NextBlock)
Dan Gohman86e1ebf2008-03-27 19:56:19 +00001523 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getControlRoot(),
Misha Brukmandedf2bd2005-04-22 04:01:18 +00001524 DAG.getBasicBlock(Succ0MBB)));
Chris Lattner57ab6592006-10-24 17:57:59 +00001525 return;
1526 }
1527
1528 // If this condition is one of the special cases we handle, do special stuff
1529 // now.
1530 Value *CondVal = I.getCondition();
Chris Lattner57ab6592006-10-24 17:57:59 +00001531 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
Chris Lattner571e4342006-10-27 21:36:01 +00001532
1533 // If this is a series of conditions that are or'd or and'd together, emit
1534 // this as a sequence of branches instead of setcc's with and/or operations.
1535 // For example, instead of something like:
1536 // cmp A, B
1537 // C = seteq
1538 // cmp D, E
1539 // F = setle
1540 // or C, F
1541 // jnz foo
1542 // Emit:
1543 // cmp A, B
1544 // je foo
1545 // cmp D, E
1546 // jle foo
1547 //
1548 if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
1549 if (BOp->hasOneUse() &&
Chris Lattnerd2f9ee92006-10-27 21:54:23 +00001550 (BOp->getOpcode() == Instruction::And ||
Chris Lattner571e4342006-10-27 21:36:01 +00001551 BOp->getOpcode() == Instruction::Or)) {
1552 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, CurMBB, BOp->getOpcode());
Chris Lattner0ccb5002006-10-31 23:06:00 +00001553 // If the compares in later blocks need to use values not currently
1554 // exported from this block, export them now. This block should always
1555 // be the first entry.
1556 assert(SwitchCases[0].ThisBB == CurMBB && "Unexpected lowering!");
1557
Chris Lattnerdf19f272006-10-31 22:37:42 +00001558 // Allow some cases to be rejected.
1559 if (ShouldEmitAsBranches(SwitchCases)) {
Chris Lattnerdf19f272006-10-31 22:37:42 +00001560 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
1561 ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
1562 ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
1563 }
1564
1565 // Emit the branch for this block.
1566 visitSwitchCase(SwitchCases[0]);
1567 SwitchCases.erase(SwitchCases.begin());
1568 return;
Chris Lattner5a145f02006-10-29 18:23:37 +00001569 }
1570
Chris Lattner0ccb5002006-10-31 23:06:00 +00001571 // Okay, we decided not to do this, remove any inserted MBB's and clear
1572 // SwitchCases.
1573 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
Dan Gohman0e5f1302008-07-07 23:02:41 +00001574 CurMBB->getParent()->erase(SwitchCases[i].ThisBB);
Chris Lattner0ccb5002006-10-31 23:06:00 +00001575
Chris Lattnerdf19f272006-10-31 22:37:42 +00001576 SwitchCases.clear();
Chris Lattner571e4342006-10-27 21:36:01 +00001577 }
1578 }
Chris Lattner24525952006-10-24 18:07:37 +00001579
1580 // Create a CaseBlock record representing this branch.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001581 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(),
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001582 NULL, Succ0MBB, Succ1MBB, CurMBB);
Chris Lattner24525952006-10-24 18:07:37 +00001583 // Use visitSwitchCase to actually insert the fast branch sequence for this
1584 // cond branch.
1585 visitSwitchCase(CB);
Chris Lattner1c08c712005-01-07 07:47:53 +00001586}
1587
Nate Begemanf15485a2006-03-27 01:32:24 +00001588/// visitSwitchCase - Emits the necessary code to represent a single node in
1589/// the binary search tree resulting from lowering a switch instruction.
1590void SelectionDAGLowering::visitSwitchCase(SelectionDAGISel::CaseBlock &CB) {
Dan Gohman475871a2008-07-27 21:46:04 +00001591 SDValue Cond;
1592 SDValue CondLHS = getValue(CB.CmpLHS);
Chris Lattner57ab6592006-10-24 17:57:59 +00001593
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001594 // Build the setcc now.
1595 if (CB.CmpMHS == NULL) {
1596 // Fold "(X == true)" to X and "(X == false)" to !X to
1597 // handle common cases produced by branch lowering.
1598 if (CB.CmpRHS == ConstantInt::getTrue() && CB.CC == ISD::SETEQ)
1599 Cond = CondLHS;
1600 else if (CB.CmpRHS == ConstantInt::getFalse() && CB.CC == ISD::SETEQ) {
Dan Gohman475871a2008-07-27 21:46:04 +00001601 SDValue True = DAG.getConstant(1, CondLHS.getValueType());
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001602 Cond = DAG.getNode(ISD::XOR, CondLHS.getValueType(), CondLHS, True);
1603 } else
1604 Cond = DAG.getSetCC(MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
1605 } else {
1606 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001607
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001608 uint64_t Low = cast<ConstantInt>(CB.CmpLHS)->getSExtValue();
1609 uint64_t High = cast<ConstantInt>(CB.CmpRHS)->getSExtValue();
1610
Dan Gohman475871a2008-07-27 21:46:04 +00001611 SDValue CmpOp = getValue(CB.CmpMHS);
Duncan Sands83ec4b62008-06-06 12:08:01 +00001612 MVT VT = CmpOp.getValueType();
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001613
1614 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
1615 Cond = DAG.getSetCC(MVT::i1, CmpOp, DAG.getConstant(High, VT), ISD::SETLE);
1616 } else {
Dan Gohman475871a2008-07-27 21:46:04 +00001617 SDValue SUB = DAG.getNode(ISD::SUB, VT, CmpOp, DAG.getConstant(Low, VT));
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001618 Cond = DAG.getSetCC(MVT::i1, SUB,
1619 DAG.getConstant(High-Low, VT), ISD::SETULE);
1620 }
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001621 }
1622
Owen Anderson2d389e82008-06-07 00:00:23 +00001623 // Update successor info
1624 CurMBB->addSuccessor(CB.TrueBB);
1625 CurMBB->addSuccessor(CB.FalseBB);
1626
Nate Begemanf15485a2006-03-27 01:32:24 +00001627 // Set NextBlock to be the MBB immediately after the current one, if any.
1628 // This is used to avoid emitting unnecessary branches to the next block.
1629 MachineBasicBlock *NextBlock = 0;
1630 MachineFunction::iterator BBI = CurMBB;
1631 if (++BBI != CurMBB->getParent()->end())
1632 NextBlock = BBI;
1633
1634 // If the lhs block is the next block, invert the condition so that we can
1635 // fall through to the lhs instead of the rhs block.
Chris Lattner57ab6592006-10-24 17:57:59 +00001636 if (CB.TrueBB == NextBlock) {
1637 std::swap(CB.TrueBB, CB.FalseBB);
Dan Gohman475871a2008-07-27 21:46:04 +00001638 SDValue True = DAG.getConstant(1, Cond.getValueType());
Nate Begemanf15485a2006-03-27 01:32:24 +00001639 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
1640 }
Dan Gohman475871a2008-07-27 21:46:04 +00001641 SDValue BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, getControlRoot(), Cond,
Chris Lattner57ab6592006-10-24 17:57:59 +00001642 DAG.getBasicBlock(CB.TrueBB));
Owen Andersonbd3ba462008-08-04 23:54:43 +00001643
1644 // If the branch was constant folded, fix up the CFG.
1645 if (BrCond.getOpcode() == ISD::BR) {
Owen Anderson3bc9c6f2008-08-05 18:27:54 +00001646 CurMBB->removeSuccessor(CB.FalseBB);
Nate Begemanf15485a2006-03-27 01:32:24 +00001647 DAG.setRoot(BrCond);
Owen Andersonbd3ba462008-08-04 23:54:43 +00001648 } else {
1649 // Otherwise, go ahead and insert the false branch.
1650 if (BrCond == getControlRoot())
Owen Anderson3bc9c6f2008-08-05 18:27:54 +00001651 CurMBB->removeSuccessor(CB.TrueBB);
Owen Andersonbd3ba462008-08-04 23:54:43 +00001652
1653 if (CB.FalseBB == NextBlock)
1654 DAG.setRoot(BrCond);
1655 else
1656 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond,
1657 DAG.getBasicBlock(CB.FalseBB)));
1658 }
Nate Begemanf15485a2006-03-27 01:32:24 +00001659}
1660
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001661/// visitJumpTable - Emit JumpTable node in the current MBB
Nate Begeman37efe672006-04-22 18:53:45 +00001662void SelectionDAGLowering::visitJumpTable(SelectionDAGISel::JumpTable &JT) {
Nate Begeman37efe672006-04-22 18:53:45 +00001663 // Emit the code for the jump table
Scott Michelf147a8d2007-04-24 01:24:20 +00001664 assert(JT.Reg != -1U && "Should lower JT Header first!");
Duncan Sands83ec4b62008-06-06 12:08:01 +00001665 MVT PTy = TLI.getPointerTy();
Dan Gohman475871a2008-07-27 21:46:04 +00001666 SDValue Index = DAG.getCopyFromReg(getControlRoot(), JT.Reg, PTy);
1667 SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
Evan Cheng3d4ce112006-10-30 08:00:44 +00001668 DAG.setRoot(DAG.getNode(ISD::BR_JT, MVT::Other, Index.getValue(1),
1669 Table, Index));
1670 return;
Nate Begeman37efe672006-04-22 18:53:45 +00001671}
1672
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001673/// visitJumpTableHeader - This function emits necessary code to produce index
1674/// in the JumpTable from switch case.
1675void SelectionDAGLowering::visitJumpTableHeader(SelectionDAGISel::JumpTable &JT,
1676 SelectionDAGISel::JumpTableHeader &JTH) {
1677 // Subtract the lowest switch case value from the value being switched on
1678 // and conditional branch to default mbb if the result is greater than the
1679 // difference between smallest and largest cases.
Dan Gohman475871a2008-07-27 21:46:04 +00001680 SDValue SwitchOp = getValue(JTH.SValue);
Duncan Sands83ec4b62008-06-06 12:08:01 +00001681 MVT VT = SwitchOp.getValueType();
Dan Gohman475871a2008-07-27 21:46:04 +00001682 SDValue SUB = DAG.getNode(ISD::SUB, VT, SwitchOp,
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001683 DAG.getConstant(JTH.First, VT));
1684
1685 // The SDNode we just created, which holds the value being switched on
1686 // minus the the smallest case value, needs to be copied to a virtual
1687 // register so it can be used as an index into the jump table in a
1688 // subsequent basic block. This value may be smaller or larger than the
1689 // target's pointer type, and therefore require extension or truncating.
Duncan Sands8e4eb092008-06-08 20:54:56 +00001690 if (VT.bitsGT(TLI.getPointerTy()))
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001691 SwitchOp = DAG.getNode(ISD::TRUNCATE, TLI.getPointerTy(), SUB);
1692 else
1693 SwitchOp = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(), SUB);
1694
1695 unsigned JumpTableReg = FuncInfo.MakeReg(TLI.getPointerTy());
Dan Gohman475871a2008-07-27 21:46:04 +00001696 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), JumpTableReg, SwitchOp);
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001697 JT.Reg = JumpTableReg;
1698
1699 // Emit the range check for the jump table, and branch to the default
1700 // block for the switch statement if the value being switched on exceeds
1701 // the largest case in the switch.
Dan Gohman475871a2008-07-27 21:46:04 +00001702 SDValue CMP = DAG.getSetCC(TLI.getSetCCResultType(SUB), SUB,
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001703 DAG.getConstant(JTH.Last-JTH.First,VT),
1704 ISD::SETUGT);
1705
1706 // Set NextBlock to be the MBB immediately after the current one, if any.
1707 // This is used to avoid emitting unnecessary branches to the next block.
1708 MachineBasicBlock *NextBlock = 0;
1709 MachineFunction::iterator BBI = CurMBB;
1710 if (++BBI != CurMBB->getParent()->end())
1711 NextBlock = BBI;
1712
Dan Gohman475871a2008-07-27 21:46:04 +00001713 SDValue BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, CopyTo, CMP,
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001714 DAG.getBasicBlock(JT.Default));
1715
1716 if (JT.MBB == NextBlock)
1717 DAG.setRoot(BrCond);
1718 else
1719 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond,
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001720 DAG.getBasicBlock(JT.MBB)));
1721
1722 return;
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001723}
1724
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001725/// visitBitTestHeader - This function emits necessary code to produce value
1726/// suitable for "bit tests"
1727void SelectionDAGLowering::visitBitTestHeader(SelectionDAGISel::BitTestBlock &B) {
1728 // Subtract the minimum value
Dan Gohman475871a2008-07-27 21:46:04 +00001729 SDValue SwitchOp = getValue(B.SValue);
Duncan Sands83ec4b62008-06-06 12:08:01 +00001730 MVT VT = SwitchOp.getValueType();
Dan Gohman475871a2008-07-27 21:46:04 +00001731 SDValue SUB = DAG.getNode(ISD::SUB, VT, SwitchOp,
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001732 DAG.getConstant(B.First, VT));
1733
1734 // Check range
Dan Gohman475871a2008-07-27 21:46:04 +00001735 SDValue RangeCmp = DAG.getSetCC(TLI.getSetCCResultType(SUB), SUB,
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001736 DAG.getConstant(B.Range, VT),
1737 ISD::SETUGT);
1738
Dan Gohman475871a2008-07-27 21:46:04 +00001739 SDValue ShiftOp;
Duncan Sands8e4eb092008-06-08 20:54:56 +00001740 if (VT.bitsGT(TLI.getShiftAmountTy()))
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001741 ShiftOp = DAG.getNode(ISD::TRUNCATE, TLI.getShiftAmountTy(), SUB);
1742 else
1743 ShiftOp = DAG.getNode(ISD::ZERO_EXTEND, TLI.getShiftAmountTy(), SUB);
1744
1745 // Make desired shift
Dan Gohman475871a2008-07-27 21:46:04 +00001746 SDValue SwitchVal = DAG.getNode(ISD::SHL, TLI.getPointerTy(),
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001747 DAG.getConstant(1, TLI.getPointerTy()),
1748 ShiftOp);
1749
1750 unsigned SwitchReg = FuncInfo.MakeReg(TLI.getPointerTy());
Dan Gohman475871a2008-07-27 21:46:04 +00001751 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), SwitchReg, SwitchVal);
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001752 B.Reg = SwitchReg;
1753
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001754 // Set NextBlock to be the MBB immediately after the current one, if any.
1755 // This is used to avoid emitting unnecessary branches to the next block.
1756 MachineBasicBlock *NextBlock = 0;
1757 MachineFunction::iterator BBI = CurMBB;
1758 if (++BBI != CurMBB->getParent()->end())
1759 NextBlock = BBI;
1760
1761 MachineBasicBlock* MBB = B.Cases[0].ThisBB;
Owen Anderson2d389e82008-06-07 00:00:23 +00001762
1763 CurMBB->addSuccessor(B.Default);
1764 CurMBB->addSuccessor(MBB);
1765
Dan Gohman475871a2008-07-27 21:46:04 +00001766 SDValue BrRange = DAG.getNode(ISD::BRCOND, MVT::Other, CopyTo, RangeCmp,
Owen Anderson2d389e82008-06-07 00:00:23 +00001767 DAG.getBasicBlock(B.Default));
1768
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001769 if (MBB == NextBlock)
1770 DAG.setRoot(BrRange);
1771 else
1772 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, CopyTo,
1773 DAG.getBasicBlock(MBB)));
1774
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001775 return;
1776}
1777
1778/// visitBitTestCase - this function produces one "bit test"
1779void SelectionDAGLowering::visitBitTestCase(MachineBasicBlock* NextMBB,
1780 unsigned Reg,
1781 SelectionDAGISel::BitTestCase &B) {
1782 // Emit bit tests and jumps
Dan Gohman475871a2008-07-27 21:46:04 +00001783 SDValue SwitchVal = DAG.getCopyFromReg(getControlRoot(), Reg,
Chris Lattneread0d882008-06-17 06:09:18 +00001784 TLI.getPointerTy());
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001785
Dan Gohman475871a2008-07-27 21:46:04 +00001786 SDValue AndOp = DAG.getNode(ISD::AND, TLI.getPointerTy(), SwitchVal,
Chris Lattneread0d882008-06-17 06:09:18 +00001787 DAG.getConstant(B.Mask, TLI.getPointerTy()));
Dan Gohman475871a2008-07-27 21:46:04 +00001788 SDValue AndCmp = DAG.getSetCC(TLI.getSetCCResultType(AndOp), AndOp,
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001789 DAG.getConstant(0, TLI.getPointerTy()),
1790 ISD::SETNE);
Owen Anderson2d389e82008-06-07 00:00:23 +00001791
1792 CurMBB->addSuccessor(B.TargetBB);
1793 CurMBB->addSuccessor(NextMBB);
1794
Dan Gohman475871a2008-07-27 21:46:04 +00001795 SDValue BrAnd = DAG.getNode(ISD::BRCOND, MVT::Other, getControlRoot(),
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001796 AndCmp, DAG.getBasicBlock(B.TargetBB));
1797
1798 // Set NextBlock to be the MBB immediately after the current one, if any.
1799 // This is used to avoid emitting unnecessary branches to the next block.
1800 MachineBasicBlock *NextBlock = 0;
1801 MachineFunction::iterator BBI = CurMBB;
1802 if (++BBI != CurMBB->getParent()->end())
1803 NextBlock = BBI;
1804
1805 if (NextMBB == NextBlock)
1806 DAG.setRoot(BrAnd);
1807 else
1808 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrAnd,
1809 DAG.getBasicBlock(NextMBB)));
1810
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001811 return;
1812}
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001813
Jim Laskeyb180aa12007-02-21 22:53:45 +00001814void SelectionDAGLowering::visitInvoke(InvokeInst &I) {
1815 // Retrieve successors.
1816 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
Duncan Sandsf19f6bb2007-06-13 05:51:31 +00001817 MachineBasicBlock *LandingPad = FuncInfo.MBBMap[I.getSuccessor(1)];
Duncan Sands9fac0b52007-06-06 10:05:18 +00001818
Duncan Sandsfd7b3262007-12-17 18:08:19 +00001819 if (isa<InlineAsm>(I.getCalledValue()))
1820 visitInlineAsm(&I);
1821 else
Duncan Sands6f74b482007-12-19 09:48:52 +00001822 LowerCallTo(&I, getValue(I.getOperand(0)), false, LandingPad);
Duncan Sands9fac0b52007-06-06 10:05:18 +00001823
Duncan Sandsf19f6bb2007-06-13 05:51:31 +00001824 // If the value of the invoke is used outside of its defining block, make it
1825 // available as a virtual register.
1826 if (!I.use_empty()) {
1827 DenseMap<const Value*, unsigned>::iterator VMI = FuncInfo.ValueMap.find(&I);
1828 if (VMI != FuncInfo.ValueMap.end())
Dan Gohman86e1ebf2008-03-27 19:56:19 +00001829 CopyValueToVirtualRegister(&I, VMI->second);
Jim Laskey183f47f2007-02-25 21:43:59 +00001830 }
Duncan Sandsf19f6bb2007-06-13 05:51:31 +00001831
Duncan Sandsf19f6bb2007-06-13 05:51:31 +00001832 // Update successor info
1833 CurMBB->addSuccessor(Return);
1834 CurMBB->addSuccessor(LandingPad);
Owen Anderson2d389e82008-06-07 00:00:23 +00001835
1836 // Drop into normal successor.
1837 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getControlRoot(),
1838 DAG.getBasicBlock(Return)));
Jim Laskeyb180aa12007-02-21 22:53:45 +00001839}
1840
1841void SelectionDAGLowering::visitUnwind(UnwindInst &I) {
1842}
1843
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001844/// handleSmallSwitchCaseRange - Emit a series of specific tests (suitable for
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001845/// small case ranges).
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001846bool SelectionDAGLowering::handleSmallSwitchRange(CaseRec& CR,
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001847 CaseRecVector& WorkList,
1848 Value* SV,
1849 MachineBasicBlock* Default) {
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001850 Case& BackCase = *(CR.Range.second-1);
1851
1852 // Size is the number of Cases represented by this range.
1853 unsigned Size = CR.Range.second - CR.Range.first;
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001854 if (Size > 3)
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001855 return false;
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001856
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001857 // Get the MachineFunction which holds the current MBB. This is used when
1858 // inserting any additional MBBs necessary to represent the switch.
1859 MachineFunction *CurMF = CurMBB->getParent();
1860
1861 // Figure out which block is immediately after the current one.
1862 MachineBasicBlock *NextBlock = 0;
1863 MachineFunction::iterator BBI = CR.CaseBB;
1864
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001865 if (++BBI != CurMBB->getParent()->end())
1866 NextBlock = BBI;
1867
1868 // TODO: If any two of the cases has the same destination, and if one value
1869 // is the same as the other, but has one bit unset that the other has set,
1870 // use bit manipulation to do two compares at once. For example:
1871 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
1872
1873 // Rearrange the case blocks so that the last one falls through if possible.
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001874 if (NextBlock && Default != NextBlock && BackCase.BB != NextBlock) {
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001875 // The last case block won't fall through into 'NextBlock' if we emit the
1876 // branches in this order. See if rearranging a case value would help.
1877 for (CaseItr I = CR.Range.first, E = CR.Range.second-1; I != E; ++I) {
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001878 if (I->BB == NextBlock) {
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001879 std::swap(*I, BackCase);
1880 break;
1881 }
1882 }
1883 }
1884
1885 // Create a CaseBlock record representing a conditional branch to
1886 // the Case's target mbb if the value being switched on SV is equal
1887 // to C.
1888 MachineBasicBlock *CurBlock = CR.CaseBB;
1889 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I) {
1890 MachineBasicBlock *FallThrough;
1891 if (I != E-1) {
Dan Gohman0e5f1302008-07-07 23:02:41 +00001892 FallThrough = CurMF->CreateMachineBasicBlock(CurBlock->getBasicBlock());
1893 CurMF->insert(BBI, FallThrough);
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001894 } else {
1895 // If the last case doesn't match, go to the default block.
1896 FallThrough = Default;
1897 }
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001898
1899 Value *RHS, *LHS, *MHS;
1900 ISD::CondCode CC;
1901 if (I->High == I->Low) {
1902 // This is just small small case range :) containing exactly 1 case
1903 CC = ISD::SETEQ;
1904 LHS = SV; RHS = I->High; MHS = NULL;
1905 } else {
1906 CC = ISD::SETLE;
1907 LHS = I->Low; MHS = SV; RHS = I->High;
1908 }
1909 SelectionDAGISel::CaseBlock CB(CC, LHS, RHS, MHS,
1910 I->BB, FallThrough, CurBlock);
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001911
1912 // If emitting the first comparison, just call visitSwitchCase to emit the
1913 // code into the current block. Otherwise, push the CaseBlock onto the
1914 // vector to be later processed by SDISel, and insert the node's MBB
1915 // before the next MBB.
1916 if (CurBlock == CurMBB)
1917 visitSwitchCase(CB);
1918 else
1919 SwitchCases.push_back(CB);
1920
1921 CurBlock = FallThrough;
1922 }
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001923
1924 return true;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001925}
1926
Anton Korobeynikov7294b582007-05-09 20:07:08 +00001927static inline bool areJTsAllowed(const TargetLowering &TLI) {
Dale Johannesen72324642008-07-31 18:13:12 +00001928 return !DisableJumpTables &&
1929 (TLI.isOperationLegal(ISD::BR_JT, MVT::Other) ||
1930 TLI.isOperationLegal(ISD::BRIND, MVT::Other));
Anton Korobeynikov7294b582007-05-09 20:07:08 +00001931}
1932
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001933/// handleJTSwitchCase - Emit jumptable for current switch case range
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001934bool SelectionDAGLowering::handleJTSwitchCase(CaseRec& CR,
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001935 CaseRecVector& WorkList,
1936 Value* SV,
1937 MachineBasicBlock* Default) {
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001938 Case& FrontCase = *CR.Range.first;
1939 Case& BackCase = *(CR.Range.second-1);
1940
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001941 int64_t First = cast<ConstantInt>(FrontCase.Low)->getSExtValue();
1942 int64_t Last = cast<ConstantInt>(BackCase.High)->getSExtValue();
1943
1944 uint64_t TSize = 0;
1945 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1946 I!=E; ++I)
1947 TSize += I->size();
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001948
Anton Korobeynikov7294b582007-05-09 20:07:08 +00001949 if (!areJTsAllowed(TLI) || TSize <= 3)
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001950 return false;
1951
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001952 double Density = (double)TSize / (double)((Last - First) + 1ULL);
1953 if (Density < 0.4)
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001954 return false;
1955
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001956 DOUT << "Lowering jump table\n"
1957 << "First entry: " << First << ". Last entry: " << Last << "\n"
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001958 << "Size: " << TSize << ". Density: " << Density << "\n\n";
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001959
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001960 // Get the MachineFunction which holds the current MBB. This is used when
1961 // inserting any additional MBBs necessary to represent the switch.
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001962 MachineFunction *CurMF = CurMBB->getParent();
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001963
1964 // Figure out which block is immediately after the current one.
1965 MachineBasicBlock *NextBlock = 0;
1966 MachineFunction::iterator BBI = CR.CaseBB;
1967
1968 if (++BBI != CurMBB->getParent()->end())
1969 NextBlock = BBI;
1970
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001971 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1972
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001973 // Create a new basic block to hold the code for loading the address
1974 // of the jump table, and jumping to it. Update successor information;
1975 // we will either branch to the default case for the switch, or the jump
1976 // table.
Dan Gohman0e5f1302008-07-07 23:02:41 +00001977 MachineBasicBlock *JumpTableBB = CurMF->CreateMachineBasicBlock(LLVMBB);
1978 CurMF->insert(BBI, JumpTableBB);
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001979 CR.CaseBB->addSuccessor(Default);
1980 CR.CaseBB->addSuccessor(JumpTableBB);
1981
1982 // Build a vector of destination BBs, corresponding to each target
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001983 // of the jump table. If the value of the jump table slot corresponds to
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001984 // a case statement, push the case's BB onto the vector, otherwise, push
1985 // the default BB.
1986 std::vector<MachineBasicBlock*> DestBBs;
1987 int64_t TEI = First;
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001988 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++TEI) {
1989 int64_t Low = cast<ConstantInt>(I->Low)->getSExtValue();
1990 int64_t High = cast<ConstantInt>(I->High)->getSExtValue();
1991
1992 if ((Low <= TEI) && (TEI <= High)) {
1993 DestBBs.push_back(I->BB);
1994 if (TEI==High)
1995 ++I;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001996 } else {
1997 DestBBs.push_back(Default);
1998 }
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001999 }
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00002000
2001 // Update successor info. Add one edge to each unique successor.
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002002 BitVector SuccsHandled(CR.CaseBB->getParent()->getNumBlockIDs());
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00002003 for (std::vector<MachineBasicBlock*>::iterator I = DestBBs.begin(),
2004 E = DestBBs.end(); I != E; ++I) {
2005 if (!SuccsHandled[(*I)->getNumber()]) {
2006 SuccsHandled[(*I)->getNumber()] = true;
2007 JumpTableBB->addSuccessor(*I);
2008 }
2009 }
2010
2011 // Create a jump table index for this jump table, or return an existing
2012 // one.
2013 unsigned JTI = CurMF->getJumpTableInfo()->getJumpTableIndex(DestBBs);
2014
2015 // Set the jump table information so that we can codegen it as a second
2016 // MachineBasicBlock
Scott Michelf147a8d2007-04-24 01:24:20 +00002017 SelectionDAGISel::JumpTable JT(-1U, JTI, JumpTableBB, Default);
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00002018 SelectionDAGISel::JumpTableHeader JTH(First, Last, SV, CR.CaseBB,
2019 (CR.CaseBB == CurMBB));
2020 if (CR.CaseBB == CurMBB)
2021 visitJumpTableHeader(JT, JTH);
2022
2023 JTCases.push_back(SelectionDAGISel::JumpTableBlock(JTH, JT));
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00002024
Anton Korobeynikovdd433212007-03-27 12:05:48 +00002025 return true;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00002026}
2027
2028/// handleBTSplitSwitchCase - emit comparison and split binary search tree into
2029/// 2 subtrees.
Anton Korobeynikovdd433212007-03-27 12:05:48 +00002030bool SelectionDAGLowering::handleBTSplitSwitchCase(CaseRec& CR,
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00002031 CaseRecVector& WorkList,
2032 Value* SV,
2033 MachineBasicBlock* Default) {
2034 // Get the MachineFunction which holds the current MBB. This is used when
2035 // inserting any additional MBBs necessary to represent the switch.
2036 MachineFunction *CurMF = CurMBB->getParent();
2037
2038 // Figure out which block is immediately after the current one.
2039 MachineBasicBlock *NextBlock = 0;
2040 MachineFunction::iterator BBI = CR.CaseBB;
2041
2042 if (++BBI != CurMBB->getParent()->end())
2043 NextBlock = BBI;
2044
2045 Case& FrontCase = *CR.Range.first;
2046 Case& BackCase = *(CR.Range.second-1);
2047 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
2048
2049 // Size is the number of Cases represented by this range.
2050 unsigned Size = CR.Range.second - CR.Range.first;
2051
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002052 int64_t First = cast<ConstantInt>(FrontCase.Low)->getSExtValue();
2053 int64_t Last = cast<ConstantInt>(BackCase.High)->getSExtValue();
Anton Korobeynikov4198c582007-04-09 12:31:58 +00002054 double FMetric = 0;
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002055 CaseItr Pivot = CR.Range.first + Size/2;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00002056
2057 // Select optimal pivot, maximizing sum density of LHS and RHS. This will
2058 // (heuristically) allow us to emit JumpTable's later.
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002059 uint64_t TSize = 0;
2060 for (CaseItr I = CR.Range.first, E = CR.Range.second;
2061 I!=E; ++I)
2062 TSize += I->size();
2063
2064 uint64_t LSize = FrontCase.size();
2065 uint64_t RSize = TSize-LSize;
Anton Korobeynikov4198c582007-04-09 12:31:58 +00002066 DOUT << "Selecting best pivot: \n"
2067 << "First: " << First << ", Last: " << Last <<"\n"
2068 << "LSize: " << LSize << ", RSize: " << RSize << "\n";
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00002069 for (CaseItr I = CR.Range.first, J=I+1, E = CR.Range.second;
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002070 J!=E; ++I, ++J) {
2071 int64_t LEnd = cast<ConstantInt>(I->High)->getSExtValue();
2072 int64_t RBegin = cast<ConstantInt>(J->Low)->getSExtValue();
Anton Korobeynikov4198c582007-04-09 12:31:58 +00002073 assert((RBegin-LEnd>=1) && "Invalid case distance");
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00002074 double LDensity = (double)LSize / (double)((LEnd - First) + 1ULL);
2075 double RDensity = (double)RSize / (double)((Last - RBegin) + 1ULL);
Anton Korobeynikov54e2b142007-04-09 21:57:03 +00002076 double Metric = Log2_64(RBegin-LEnd)*(LDensity+RDensity);
Anton Korobeynikov4198c582007-04-09 12:31:58 +00002077 // Should always split in some non-trivial place
2078 DOUT <<"=>Step\n"
2079 << "LEnd: " << LEnd << ", RBegin: " << RBegin << "\n"
2080 << "LDensity: " << LDensity << ", RDensity: " << RDensity << "\n"
2081 << "Metric: " << Metric << "\n";
2082 if (FMetric < Metric) {
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00002083 Pivot = J;
Anton Korobeynikov4198c582007-04-09 12:31:58 +00002084 FMetric = Metric;
2085 DOUT << "Current metric set to: " << FMetric << "\n";
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00002086 }
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002087
2088 LSize += J->size();
2089 RSize -= J->size();
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00002090 }
Anton Korobeynikov7294b582007-05-09 20:07:08 +00002091 if (areJTsAllowed(TLI)) {
2092 // If our case is dense we *really* should handle it earlier!
2093 assert((FMetric > 0) && "Should handle dense range earlier!");
2094 } else {
2095 Pivot = CR.Range.first + Size/2;
2096 }
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00002097
2098 CaseRange LHSR(CR.Range.first, Pivot);
2099 CaseRange RHSR(Pivot, CR.Range.second);
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002100 Constant *C = Pivot->Low;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00002101 MachineBasicBlock *FalseBB = 0, *TrueBB = 0;
2102
2103 // We know that we branch to the LHS if the Value being switched on is
2104 // less than the Pivot value, C. We use this to optimize our binary
2105 // tree a bit, by recognizing that if SV is greater than or equal to the
2106 // LHS's Case Value, and that Case Value is exactly one less than the
2107 // Pivot's Value, then we can branch directly to the LHS's Target,
2108 // rather than creating a leaf node for it.
2109 if ((LHSR.second - LHSR.first) == 1 &&
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002110 LHSR.first->High == CR.GE &&
2111 cast<ConstantInt>(C)->getSExtValue() ==
2112 (cast<ConstantInt>(CR.GE)->getSExtValue() + 1LL)) {
2113 TrueBB = LHSR.first->BB;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00002114 } else {
Dan Gohman0e5f1302008-07-07 23:02:41 +00002115 TrueBB = CurMF->CreateMachineBasicBlock(LLVMBB);
2116 CurMF->insert(BBI, TrueBB);
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00002117 WorkList.push_back(CaseRec(TrueBB, C, CR.GE, LHSR));
2118 }
2119
2120 // Similar to the optimization above, if the Value being switched on is
2121 // known to be less than the Constant CR.LT, and the current Case Value
2122 // is CR.LT - 1, then we can branch directly to the target block for
2123 // the current Case Value, rather than emitting a RHS leaf node for it.
2124 if ((RHSR.second - RHSR.first) == 1 && CR.LT &&
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002125 cast<ConstantInt>(RHSR.first->Low)->getSExtValue() ==
2126 (cast<ConstantInt>(CR.LT)->getSExtValue() - 1LL)) {
2127 FalseBB = RHSR.first->BB;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00002128 } else {
Dan Gohman0e5f1302008-07-07 23:02:41 +00002129 FalseBB = CurMF->CreateMachineBasicBlock(LLVMBB);
2130 CurMF->insert(BBI, FalseBB);
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00002131 WorkList.push_back(CaseRec(FalseBB,CR.LT,C,RHSR));
2132 }
2133
2134 // Create a CaseBlock record representing a conditional branch to
2135 // the LHS node if the value being switched on SV is less than C.
2136 // Otherwise, branch to LHS.
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002137 SelectionDAGISel::CaseBlock CB(ISD::SETLT, SV, C, NULL,
2138 TrueBB, FalseBB, CR.CaseBB);
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00002139
2140 if (CR.CaseBB == CurMBB)
2141 visitSwitchCase(CB);
2142 else
2143 SwitchCases.push_back(CB);
Anton Korobeynikovdd433212007-03-27 12:05:48 +00002144
2145 return true;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00002146}
2147
Anton Korobeynikov4198c582007-04-09 12:31:58 +00002148/// handleBitTestsSwitchCase - if current case range has few destination and
2149/// range span less, than machine word bitwidth, encode case range into series
2150/// of masks and emit bit tests with these masks.
2151bool SelectionDAGLowering::handleBitTestsSwitchCase(CaseRec& CR,
2152 CaseRecVector& WorkList,
2153 Value* SV,
Chris Lattner3ff98172007-04-14 02:26:56 +00002154 MachineBasicBlock* Default){
Duncan Sands83ec4b62008-06-06 12:08:01 +00002155 unsigned IntPtrBits = TLI.getPointerTy().getSizeInBits();
Anton Korobeynikov4198c582007-04-09 12:31:58 +00002156
2157 Case& FrontCase = *CR.Range.first;
2158 Case& BackCase = *(CR.Range.second-1);
2159
2160 // Get the MachineFunction which holds the current MBB. This is used when
2161 // inserting any additional MBBs necessary to represent the switch.
2162 MachineFunction *CurMF = CurMBB->getParent();
2163
2164 unsigned numCmps = 0;
2165 for (CaseItr I = CR.Range.first, E = CR.Range.second;
2166 I!=E; ++I) {
2167 // Single case counts one, case range - two.
2168 if (I->Low == I->High)
2169 numCmps +=1;
2170 else
2171 numCmps +=2;
2172 }
2173
2174 // Count unique destinations
2175 SmallSet<MachineBasicBlock*, 4> Dests;
2176 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
2177 Dests.insert(I->BB);
2178 if (Dests.size() > 3)
2179 // Don't bother the code below, if there are too much unique destinations
2180 return false;
2181 }
2182 DOUT << "Total number of unique destinations: " << Dests.size() << "\n"
2183 << "Total number of comparisons: " << numCmps << "\n";
2184
2185 // Compute span of values.
2186 Constant* minValue = FrontCase.Low;
2187 Constant* maxValue = BackCase.High;
2188 uint64_t range = cast<ConstantInt>(maxValue)->getSExtValue() -
2189 cast<ConstantInt>(minValue)->getSExtValue();
2190 DOUT << "Compare range: " << range << "\n"
2191 << "Low bound: " << cast<ConstantInt>(minValue)->getSExtValue() << "\n"
2192 << "High bound: " << cast<ConstantInt>(maxValue)->getSExtValue() << "\n";
2193
Anton Korobeynikovab8fd402007-04-26 20:44:04 +00002194 if (range>=IntPtrBits ||
Anton Korobeynikov4198c582007-04-09 12:31:58 +00002195 (!(Dests.size() == 1 && numCmps >= 3) &&
2196 !(Dests.size() == 2 && numCmps >= 5) &&
2197 !(Dests.size() >= 3 && numCmps >= 6)))
2198 return false;
2199
2200 DOUT << "Emitting bit tests\n";
2201 int64_t lowBound = 0;
2202
2203 // Optimize the case where all the case values fit in a
2204 // word without having to subtract minValue. In this case,
2205 // we can optimize away the subtraction.
2206 if (cast<ConstantInt>(minValue)->getSExtValue() >= 0 &&
Anton Korobeynikove01017b2007-04-14 13:25:55 +00002207 cast<ConstantInt>(maxValue)->getSExtValue() < IntPtrBits) {
Anton Korobeynikov4198c582007-04-09 12:31:58 +00002208 range = cast<ConstantInt>(maxValue)->getSExtValue();
2209 } else {
2210 lowBound = cast<ConstantInt>(minValue)->getSExtValue();
2211 }
2212
2213 CaseBitsVector CasesBits;
2214 unsigned i, count = 0;
2215
2216 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
2217 MachineBasicBlock* Dest = I->BB;
2218 for (i = 0; i < count; ++i)
2219 if (Dest == CasesBits[i].BB)
2220 break;
2221
2222 if (i == count) {
2223 assert((count < 3) && "Too much destinations to test!");
2224 CasesBits.push_back(CaseBits(0, Dest, 0));
2225 count++;
2226 }
2227
2228 uint64_t lo = cast<ConstantInt>(I->Low)->getSExtValue() - lowBound;
2229 uint64_t hi = cast<ConstantInt>(I->High)->getSExtValue() - lowBound;
2230
2231 for (uint64_t j = lo; j <= hi; j++) {
Anton Korobeynikove01017b2007-04-14 13:25:55 +00002232 CasesBits[i].Mask |= 1ULL << j;
Anton Korobeynikov4198c582007-04-09 12:31:58 +00002233 CasesBits[i].Bits++;
2234 }
2235
2236 }
2237 std::sort(CasesBits.begin(), CasesBits.end(), CaseBitsCmp());
2238
2239 SelectionDAGISel::BitTestInfo BTC;
2240
2241 // Figure out which block is immediately after the current one.
2242 MachineFunction::iterator BBI = CR.CaseBB;
2243 ++BBI;
2244
2245 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
2246
2247 DOUT << "Cases:\n";
2248 for (unsigned i = 0, e = CasesBits.size(); i!=e; ++i) {
2249 DOUT << "Mask: " << CasesBits[i].Mask << ", Bits: " << CasesBits[i].Bits
2250 << ", BB: " << CasesBits[i].BB << "\n";
2251
Dan Gohman0e5f1302008-07-07 23:02:41 +00002252 MachineBasicBlock *CaseBB = CurMF->CreateMachineBasicBlock(LLVMBB);
2253 CurMF->insert(BBI, CaseBB);
Anton Korobeynikov4198c582007-04-09 12:31:58 +00002254 BTC.push_back(SelectionDAGISel::BitTestCase(CasesBits[i].Mask,
2255 CaseBB,
2256 CasesBits[i].BB));
2257 }
2258
2259 SelectionDAGISel::BitTestBlock BTB(lowBound, range, SV,
Jeff Cohenefc36622007-04-09 14:32:59 +00002260 -1U, (CR.CaseBB == CurMBB),
Anton Korobeynikov4198c582007-04-09 12:31:58 +00002261 CR.CaseBB, Default, BTC);
2262
2263 if (CR.CaseBB == CurMBB)
2264 visitBitTestHeader(BTB);
2265
2266 BitTestCases.push_back(BTB);
2267
2268 return true;
2269}
2270
2271
Dan Gohman86e1ebf2008-03-27 19:56:19 +00002272/// Clusterify - Transform simple list of Cases into list of CaseRange's
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002273unsigned SelectionDAGLowering::Clusterify(CaseVector& Cases,
2274 const SwitchInst& SI) {
2275 unsigned numCmps = 0;
2276
2277 // Start with "simple" cases
2278 for (unsigned i = 1; i < SI.getNumSuccessors(); ++i) {
2279 MachineBasicBlock *SMBB = FuncInfo.MBBMap[SI.getSuccessor(i)];
2280 Cases.push_back(Case(SI.getSuccessorValue(i),
2281 SI.getSuccessorValue(i),
2282 SMBB));
2283 }
Chris Lattnerb3d9cdb2007-11-27 06:14:32 +00002284 std::sort(Cases.begin(), Cases.end(), CaseCmp());
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002285
2286 // Merge case into clusters
2287 if (Cases.size()>=2)
David Greenea2a48852007-06-29 03:42:23 +00002288 // Must recompute end() each iteration because it may be
2289 // invalidated by erase if we hold on to it
Chris Lattner27a6c732007-11-24 07:07:01 +00002290 for (CaseItr I=Cases.begin(), J=++(Cases.begin()); J!=Cases.end(); ) {
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002291 int64_t nextValue = cast<ConstantInt>(J->Low)->getSExtValue();
2292 int64_t currentValue = cast<ConstantInt>(I->High)->getSExtValue();
2293 MachineBasicBlock* nextBB = J->BB;
2294 MachineBasicBlock* currentBB = I->BB;
2295
2296 // If the two neighboring cases go to the same destination, merge them
2297 // into a single case.
2298 if ((nextValue-currentValue==1) && (currentBB == nextBB)) {
2299 I->High = J->High;
2300 J = Cases.erase(J);
2301 } else {
2302 I = J++;
2303 }
2304 }
2305
2306 for (CaseItr I=Cases.begin(), E=Cases.end(); I!=E; ++I, ++numCmps) {
2307 if (I->Low != I->High)
2308 // A range counts double, since it requires two compares.
2309 ++numCmps;
2310 }
2311
2312 return numCmps;
2313}
2314
2315void SelectionDAGLowering::visitSwitch(SwitchInst &SI) {
Nate Begemanf15485a2006-03-27 01:32:24 +00002316 // Figure out which block is immediately after the current one.
2317 MachineBasicBlock *NextBlock = 0;
2318 MachineFunction::iterator BBI = CurMBB;
Bill Wendlingc70ddad2006-10-19 21:46:38 +00002319
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002320 MachineBasicBlock *Default = FuncInfo.MBBMap[SI.getDefaultDest()];
Chris Lattnerd2c1d222006-10-22 21:36:53 +00002321
Nate Begemanf15485a2006-03-27 01:32:24 +00002322 // If there is only the default destination, branch to it if it is not the
2323 // next basic block. Otherwise, just fall through.
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002324 if (SI.getNumOperands() == 2) {
Nate Begemanf15485a2006-03-27 01:32:24 +00002325 // Update machine-CFG edges.
Bill Wendlingc70ddad2006-10-19 21:46:38 +00002326
Nate Begemanf15485a2006-03-27 01:32:24 +00002327 // If this is not a fall-through branch, emit the branch.
Owen Anderson2d389e82008-06-07 00:00:23 +00002328 CurMBB->addSuccessor(Default);
Chris Lattnerd2c1d222006-10-22 21:36:53 +00002329 if (Default != NextBlock)
Dan Gohman86e1ebf2008-03-27 19:56:19 +00002330 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getControlRoot(),
Chris Lattnerd2c1d222006-10-22 21:36:53 +00002331 DAG.getBasicBlock(Default)));
Owen Anderson2d389e82008-06-07 00:00:23 +00002332
Nate Begemanf15485a2006-03-27 01:32:24 +00002333 return;
2334 }
2335
2336 // If there are any non-default case statements, create a vector of Cases
2337 // representing each one, and sort the vector so that we can efficiently
2338 // create a binary search tree from them.
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002339 CaseVector Cases;
2340 unsigned numCmps = Clusterify(Cases, SI);
2341 DOUT << "Clusterify finished. Total clusters: " << Cases.size()
2342 << ". Total compares: " << numCmps << "\n";
Bill Wendlingc70ddad2006-10-19 21:46:38 +00002343
Nate Begemanf15485a2006-03-27 01:32:24 +00002344 // Get the Value to be switched on and default basic blocks, which will be
2345 // inserted into CaseBlock records, representing basic blocks in the binary
2346 // search tree.
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002347 Value *SV = SI.getOperand(0);
Nate Begeman37efe672006-04-22 18:53:45 +00002348
Nate Begemanf15485a2006-03-27 01:32:24 +00002349 // Push the initial CaseRec onto the worklist
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00002350 CaseRecVector WorkList;
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00002351 WorkList.push_back(CaseRec(CurMBB,0,0,CaseRange(Cases.begin(),Cases.end())));
2352
2353 while (!WorkList.empty()) {
Nate Begemanf15485a2006-03-27 01:32:24 +00002354 // Grab a record representing a case range to process off the worklist
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00002355 CaseRec CR = WorkList.back();
2356 WorkList.pop_back();
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00002357
Anton Korobeynikov4198c582007-04-09 12:31:58 +00002358 if (handleBitTestsSwitchCase(CR, WorkList, SV, Default))
2359 continue;
2360
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00002361 // If the range has few cases (two or less) emit a series of specific
2362 // tests.
Anton Korobeynikovdd433212007-03-27 12:05:48 +00002363 if (handleSmallSwitchRange(CR, WorkList, SV, Default))
2364 continue;
2365
Anton Korobeynikov4198c582007-04-09 12:31:58 +00002366 // If the switch has more than 5 blocks, and at least 40% dense, and the
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00002367 // target supports indirect branches, then emit a jump table rather than
2368 // lowering the switch to a binary tree of conditional branches.
Anton Korobeynikovdd433212007-03-27 12:05:48 +00002369 if (handleJTSwitchCase(CR, WorkList, SV, Default))
2370 continue;
2371
2372 // Emit binary tree. We need to pick a pivot, and push left and right ranges
2373 // onto the worklist. Leafs are handled via handleSmallSwitchRange() call.
2374 handleBTSplitSwitchCase(CR, WorkList, SV, Default);
Nate Begemanf15485a2006-03-27 01:32:24 +00002375 }
2376}
2377
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00002378
Chris Lattnerb9fccc42005-04-02 05:04:50 +00002379void SelectionDAGLowering::visitSub(User &I) {
2380 // -0.0 - X --> fneg
Reid Spencer24d6da52007-01-21 00:29:26 +00002381 const Type *Ty = I.getType();
Reid Spencer9d6565a2007-02-15 02:26:10 +00002382 if (isa<VectorType>(Ty)) {
Dan Gohman7f321562007-06-25 16:23:39 +00002383 if (ConstantVector *CV = dyn_cast<ConstantVector>(I.getOperand(0))) {
2384 const VectorType *DestTy = cast<VectorType>(I.getType());
2385 const Type *ElTy = DestTy->getElementType();
Evan Chengc45453f2007-06-29 21:44:35 +00002386 if (ElTy->isFloatingPoint()) {
2387 unsigned VL = DestTy->getNumElements();
Dale Johannesen9e3d3ab2007-09-14 22:26:36 +00002388 std::vector<Constant*> NZ(VL, ConstantFP::getNegativeZero(ElTy));
Evan Chengc45453f2007-06-29 21:44:35 +00002389 Constant *CNZ = ConstantVector::get(&NZ[0], NZ.size());
2390 if (CV == CNZ) {
Dan Gohman475871a2008-07-27 21:46:04 +00002391 SDValue Op2 = getValue(I.getOperand(1));
Evan Chengc45453f2007-06-29 21:44:35 +00002392 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
2393 return;
2394 }
Dan Gohman7f321562007-06-25 16:23:39 +00002395 }
2396 }
2397 }
2398 if (Ty->isFloatingPoint()) {
Chris Lattner01b3d732005-09-28 22:28:18 +00002399 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
Dale Johannesen9e3d3ab2007-09-14 22:26:36 +00002400 if (CFP->isExactlyValue(ConstantFP::getNegativeZero(Ty)->getValueAPF())) {
Dan Gohman475871a2008-07-27 21:46:04 +00002401 SDValue Op2 = getValue(I.getOperand(1));
Chris Lattner01b3d732005-09-28 22:28:18 +00002402 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
2403 return;
2404 }
Dan Gohman7f321562007-06-25 16:23:39 +00002405 }
2406
2407 visitBinary(I, Ty->isFPOrFPVector() ? ISD::FSUB : ISD::SUB);
Chris Lattnerb9fccc42005-04-02 05:04:50 +00002408}
2409
Dan Gohman7f321562007-06-25 16:23:39 +00002410void SelectionDAGLowering::visitBinary(User &I, unsigned OpCode) {
Dan Gohman475871a2008-07-27 21:46:04 +00002411 SDValue Op1 = getValue(I.getOperand(0));
2412 SDValue Op2 = getValue(I.getOperand(1));
Reid Spencer24d6da52007-01-21 00:29:26 +00002413
2414 setValue(&I, DAG.getNode(OpCode, Op1.getValueType(), Op1, Op2));
Reid Spencer1628cec2006-10-26 06:15:43 +00002415}
2416
Nate Begemane21ea612005-11-18 07:42:56 +00002417void SelectionDAGLowering::visitShift(User &I, unsigned Opcode) {
Dan Gohman475871a2008-07-27 21:46:04 +00002418 SDValue Op1 = getValue(I.getOperand(0));
2419 SDValue Op2 = getValue(I.getOperand(1));
Nate Begeman5bc1ea02008-07-29 15:49:41 +00002420 if (!isa<VectorType>(I.getType())) {
2421 if (TLI.getShiftAmountTy().bitsLT(Op2.getValueType()))
2422 Op2 = DAG.getNode(ISD::TRUNCATE, TLI.getShiftAmountTy(), Op2);
2423 else if (TLI.getShiftAmountTy().bitsGT(Op2.getValueType()))
2424 Op2 = DAG.getNode(ISD::ANY_EXTEND, TLI.getShiftAmountTy(), Op2);
2425 }
Nate Begemane21ea612005-11-18 07:42:56 +00002426
Chris Lattner1c08c712005-01-07 07:47:53 +00002427 setValue(&I, DAG.getNode(Opcode, Op1.getValueType(), Op1, Op2));
2428}
2429
Reid Spencer45fb3f32006-11-20 01:22:35 +00002430void SelectionDAGLowering::visitICmp(User &I) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002431 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
2432 if (ICmpInst *IC = dyn_cast<ICmpInst>(&I))
2433 predicate = IC->getPredicate();
2434 else if (ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
2435 predicate = ICmpInst::Predicate(IC->getPredicate());
Dan Gohman475871a2008-07-27 21:46:04 +00002436 SDValue Op1 = getValue(I.getOperand(0));
2437 SDValue Op2 = getValue(I.getOperand(1));
Reid Spencer45fb3f32006-11-20 01:22:35 +00002438 ISD::CondCode Opcode;
Reid Spencere4d87aa2006-12-23 06:05:41 +00002439 switch (predicate) {
Reid Spencer45fb3f32006-11-20 01:22:35 +00002440 case ICmpInst::ICMP_EQ : Opcode = ISD::SETEQ; break;
2441 case ICmpInst::ICMP_NE : Opcode = ISD::SETNE; break;
2442 case ICmpInst::ICMP_UGT : Opcode = ISD::SETUGT; break;
2443 case ICmpInst::ICMP_UGE : Opcode = ISD::SETUGE; break;
2444 case ICmpInst::ICMP_ULT : Opcode = ISD::SETULT; break;
2445 case ICmpInst::ICMP_ULE : Opcode = ISD::SETULE; break;
2446 case ICmpInst::ICMP_SGT : Opcode = ISD::SETGT; break;
2447 case ICmpInst::ICMP_SGE : Opcode = ISD::SETGE; break;
2448 case ICmpInst::ICMP_SLT : Opcode = ISD::SETLT; break;
2449 case ICmpInst::ICMP_SLE : Opcode = ISD::SETLE; break;
2450 default:
2451 assert(!"Invalid ICmp predicate value");
2452 Opcode = ISD::SETEQ;
2453 break;
2454 }
2455 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Opcode));
2456}
2457
2458void SelectionDAGLowering::visitFCmp(User &I) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002459 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
2460 if (FCmpInst *FC = dyn_cast<FCmpInst>(&I))
2461 predicate = FC->getPredicate();
2462 else if (ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
2463 predicate = FCmpInst::Predicate(FC->getPredicate());
Dan Gohman475871a2008-07-27 21:46:04 +00002464 SDValue Op1 = getValue(I.getOperand(0));
2465 SDValue Op2 = getValue(I.getOperand(1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00002466 ISD::CondCode Condition, FOC, FPC;
2467 switch (predicate) {
2468 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
2469 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
2470 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
2471 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
2472 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
2473 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
2474 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
Dan Gohmancba3b442008-05-01 23:40:44 +00002475 case FCmpInst::FCMP_ORD: FOC = FPC = ISD::SETO; break;
2476 case FCmpInst::FCMP_UNO: FOC = FPC = ISD::SETUO; break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00002477 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
2478 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
2479 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
2480 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
2481 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
2482 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
2483 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
2484 default:
2485 assert(!"Invalid FCmp predicate value");
2486 FOC = FPC = ISD::SETFALSE;
2487 break;
2488 }
2489 if (FiniteOnlyFPMath())
2490 Condition = FOC;
2491 else
2492 Condition = FPC;
2493 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Condition));
Chris Lattner1c08c712005-01-07 07:47:53 +00002494}
2495
Nate Begemanb43e9c12008-05-12 19:40:03 +00002496void SelectionDAGLowering::visitVICmp(User &I) {
2497 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
2498 if (VICmpInst *IC = dyn_cast<VICmpInst>(&I))
2499 predicate = IC->getPredicate();
2500 else if (ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
2501 predicate = ICmpInst::Predicate(IC->getPredicate());
Dan Gohman475871a2008-07-27 21:46:04 +00002502 SDValue Op1 = getValue(I.getOperand(0));
2503 SDValue Op2 = getValue(I.getOperand(1));
Nate Begemanb43e9c12008-05-12 19:40:03 +00002504 ISD::CondCode Opcode;
2505 switch (predicate) {
2506 case ICmpInst::ICMP_EQ : Opcode = ISD::SETEQ; break;
2507 case ICmpInst::ICMP_NE : Opcode = ISD::SETNE; break;
2508 case ICmpInst::ICMP_UGT : Opcode = ISD::SETUGT; break;
2509 case ICmpInst::ICMP_UGE : Opcode = ISD::SETUGE; break;
2510 case ICmpInst::ICMP_ULT : Opcode = ISD::SETULT; break;
2511 case ICmpInst::ICMP_ULE : Opcode = ISD::SETULE; break;
2512 case ICmpInst::ICMP_SGT : Opcode = ISD::SETGT; break;
2513 case ICmpInst::ICMP_SGE : Opcode = ISD::SETGE; break;
2514 case ICmpInst::ICMP_SLT : Opcode = ISD::SETLT; break;
2515 case ICmpInst::ICMP_SLE : Opcode = ISD::SETLE; break;
2516 default:
2517 assert(!"Invalid ICmp predicate value");
2518 Opcode = ISD::SETEQ;
2519 break;
2520 }
2521 setValue(&I, DAG.getVSetCC(Op1.getValueType(), Op1, Op2, Opcode));
2522}
2523
2524void SelectionDAGLowering::visitVFCmp(User &I) {
2525 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
2526 if (VFCmpInst *FC = dyn_cast<VFCmpInst>(&I))
2527 predicate = FC->getPredicate();
2528 else if (ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
2529 predicate = FCmpInst::Predicate(FC->getPredicate());
Dan Gohman475871a2008-07-27 21:46:04 +00002530 SDValue Op1 = getValue(I.getOperand(0));
2531 SDValue Op2 = getValue(I.getOperand(1));
Nate Begemanb43e9c12008-05-12 19:40:03 +00002532 ISD::CondCode Condition, FOC, FPC;
2533 switch (predicate) {
2534 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
2535 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
2536 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
2537 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
2538 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
2539 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
2540 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
2541 case FCmpInst::FCMP_ORD: FOC = FPC = ISD::SETO; break;
2542 case FCmpInst::FCMP_UNO: FOC = FPC = ISD::SETUO; break;
2543 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
2544 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
2545 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
2546 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
2547 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
2548 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
2549 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
2550 default:
2551 assert(!"Invalid VFCmp predicate value");
2552 FOC = FPC = ISD::SETFALSE;
2553 break;
2554 }
2555 if (FiniteOnlyFPMath())
2556 Condition = FOC;
2557 else
2558 Condition = FPC;
2559
Duncan Sands83ec4b62008-06-06 12:08:01 +00002560 MVT DestVT = TLI.getValueType(I.getType());
Nate Begemanb43e9c12008-05-12 19:40:03 +00002561
2562 setValue(&I, DAG.getVSetCC(DestVT, Op1, Op2, Condition));
2563}
2564
Chris Lattner1c08c712005-01-07 07:47:53 +00002565void SelectionDAGLowering::visitSelect(User &I) {
Dan Gohman475871a2008-07-27 21:46:04 +00002566 SDValue Cond = getValue(I.getOperand(0));
2567 SDValue TrueVal = getValue(I.getOperand(1));
2568 SDValue FalseVal = getValue(I.getOperand(2));
Dan Gohman7f321562007-06-25 16:23:39 +00002569 setValue(&I, DAG.getNode(ISD::SELECT, TrueVal.getValueType(), Cond,
2570 TrueVal, FalseVal));
Chris Lattner1c08c712005-01-07 07:47:53 +00002571}
2572
Reid Spencer3da59db2006-11-27 01:05:10 +00002573
2574void SelectionDAGLowering::visitTrunc(User &I) {
2575 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
Dan Gohman475871a2008-07-27 21:46:04 +00002576 SDValue N = getValue(I.getOperand(0));
Duncan Sands83ec4b62008-06-06 12:08:01 +00002577 MVT DestVT = TLI.getValueType(I.getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00002578 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
2579}
2580
2581void SelectionDAGLowering::visitZExt(User &I) {
2582 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2583 // ZExt also can't be a cast to bool for same reason. So, nothing much to do
Dan Gohman475871a2008-07-27 21:46:04 +00002584 SDValue N = getValue(I.getOperand(0));
Duncan Sands83ec4b62008-06-06 12:08:01 +00002585 MVT DestVT = TLI.getValueType(I.getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00002586 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
2587}
2588
2589void SelectionDAGLowering::visitSExt(User &I) {
2590 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2591 // SExt also can't be a cast to bool for same reason. So, nothing much to do
Dan Gohman475871a2008-07-27 21:46:04 +00002592 SDValue N = getValue(I.getOperand(0));
Duncan Sands83ec4b62008-06-06 12:08:01 +00002593 MVT DestVT = TLI.getValueType(I.getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00002594 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, DestVT, N));
2595}
2596
2597void SelectionDAGLowering::visitFPTrunc(User &I) {
2598 // FPTrunc is never a no-op cast, no need to check
Dan Gohman475871a2008-07-27 21:46:04 +00002599 SDValue N = getValue(I.getOperand(0));
Duncan Sands83ec4b62008-06-06 12:08:01 +00002600 MVT DestVT = TLI.getValueType(I.getType());
Chris Lattner0bd48932008-01-17 07:00:52 +00002601 setValue(&I, DAG.getNode(ISD::FP_ROUND, DestVT, N, DAG.getIntPtrConstant(0)));
Reid Spencer3da59db2006-11-27 01:05:10 +00002602}
2603
2604void SelectionDAGLowering::visitFPExt(User &I){
2605 // FPTrunc is never a no-op cast, no need to check
Dan Gohman475871a2008-07-27 21:46:04 +00002606 SDValue N = getValue(I.getOperand(0));
Duncan Sands83ec4b62008-06-06 12:08:01 +00002607 MVT DestVT = TLI.getValueType(I.getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00002608 setValue(&I, DAG.getNode(ISD::FP_EXTEND, DestVT, N));
2609}
2610
2611void SelectionDAGLowering::visitFPToUI(User &I) {
2612 // FPToUI is never a no-op cast, no need to check
Dan Gohman475871a2008-07-27 21:46:04 +00002613 SDValue N = getValue(I.getOperand(0));
Duncan Sands83ec4b62008-06-06 12:08:01 +00002614 MVT DestVT = TLI.getValueType(I.getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00002615 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, DestVT, N));
2616}
2617
2618void SelectionDAGLowering::visitFPToSI(User &I) {
2619 // FPToSI is never a no-op cast, no need to check
Dan Gohman475871a2008-07-27 21:46:04 +00002620 SDValue N = getValue(I.getOperand(0));
Duncan Sands83ec4b62008-06-06 12:08:01 +00002621 MVT DestVT = TLI.getValueType(I.getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00002622 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, DestVT, N));
2623}
2624
2625void SelectionDAGLowering::visitUIToFP(User &I) {
2626 // UIToFP is never a no-op cast, no need to check
Dan Gohman475871a2008-07-27 21:46:04 +00002627 SDValue N = getValue(I.getOperand(0));
Duncan Sands83ec4b62008-06-06 12:08:01 +00002628 MVT DestVT = TLI.getValueType(I.getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00002629 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, DestVT, N));
2630}
2631
2632void SelectionDAGLowering::visitSIToFP(User &I){
2633 // UIToFP is never a no-op cast, no need to check
Dan Gohman475871a2008-07-27 21:46:04 +00002634 SDValue N = getValue(I.getOperand(0));
Duncan Sands83ec4b62008-06-06 12:08:01 +00002635 MVT DestVT = TLI.getValueType(I.getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00002636 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, DestVT, N));
2637}
2638
2639void SelectionDAGLowering::visitPtrToInt(User &I) {
2640 // What to do depends on the size of the integer and the size of the pointer.
2641 // We can either truncate, zero extend, or no-op, accordingly.
Dan Gohman475871a2008-07-27 21:46:04 +00002642 SDValue N = getValue(I.getOperand(0));
Duncan Sands83ec4b62008-06-06 12:08:01 +00002643 MVT SrcVT = N.getValueType();
2644 MVT DestVT = TLI.getValueType(I.getType());
Dan Gohman475871a2008-07-27 21:46:04 +00002645 SDValue Result;
Duncan Sands8e4eb092008-06-08 20:54:56 +00002646 if (DestVT.bitsLT(SrcVT))
Reid Spencer3da59db2006-11-27 01:05:10 +00002647 Result = DAG.getNode(ISD::TRUNCATE, DestVT, N);
2648 else
2649 // Note: ZERO_EXTEND can handle cases where the sizes are equal too
2650 Result = DAG.getNode(ISD::ZERO_EXTEND, DestVT, N);
2651 setValue(&I, Result);
2652}
Chris Lattner1c08c712005-01-07 07:47:53 +00002653
Reid Spencer3da59db2006-11-27 01:05:10 +00002654void SelectionDAGLowering::visitIntToPtr(User &I) {
2655 // What to do depends on the size of the integer and the size of the pointer.
2656 // We can either truncate, zero extend, or no-op, accordingly.
Dan Gohman475871a2008-07-27 21:46:04 +00002657 SDValue N = getValue(I.getOperand(0));
Duncan Sands83ec4b62008-06-06 12:08:01 +00002658 MVT SrcVT = N.getValueType();
2659 MVT DestVT = TLI.getValueType(I.getType());
Duncan Sands8e4eb092008-06-08 20:54:56 +00002660 if (DestVT.bitsLT(SrcVT))
Reid Spencer3da59db2006-11-27 01:05:10 +00002661 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
2662 else
2663 // Note: ZERO_EXTEND can handle cases where the sizes are equal too
2664 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
2665}
2666
2667void SelectionDAGLowering::visitBitCast(User &I) {
Dan Gohman475871a2008-07-27 21:46:04 +00002668 SDValue N = getValue(I.getOperand(0));
Duncan Sands83ec4b62008-06-06 12:08:01 +00002669 MVT DestVT = TLI.getValueType(I.getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00002670
2671 // BitCast assures us that source and destination are the same size so this
2672 // is either a BIT_CONVERT or a no-op.
2673 if (DestVT != N.getValueType())
2674 setValue(&I, DAG.getNode(ISD::BIT_CONVERT, DestVT, N)); // convert types
2675 else
2676 setValue(&I, N); // noop cast.
Chris Lattner1c08c712005-01-07 07:47:53 +00002677}
2678
Chris Lattner2bbd8102006-03-29 00:11:43 +00002679void SelectionDAGLowering::visitInsertElement(User &I) {
Dan Gohman475871a2008-07-27 21:46:04 +00002680 SDValue InVec = getValue(I.getOperand(0));
2681 SDValue InVal = getValue(I.getOperand(1));
2682 SDValue InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
Chris Lattnerc7029802006-03-18 01:44:44 +00002683 getValue(I.getOperand(2)));
2684
Dan Gohman7f321562007-06-25 16:23:39 +00002685 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT,
2686 TLI.getValueType(I.getType()),
2687 InVec, InVal, InIdx));
Chris Lattnerc7029802006-03-18 01:44:44 +00002688}
2689
Chris Lattner2bbd8102006-03-29 00:11:43 +00002690void SelectionDAGLowering::visitExtractElement(User &I) {
Dan Gohman475871a2008-07-27 21:46:04 +00002691 SDValue InVec = getValue(I.getOperand(0));
2692 SDValue InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
Chris Lattner384504c2006-03-21 20:44:12 +00002693 getValue(I.getOperand(1)));
Dan Gohman7f321562007-06-25 16:23:39 +00002694 setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
Chris Lattner384504c2006-03-21 20:44:12 +00002695 TLI.getValueType(I.getType()), InVec, InIdx));
2696}
Chris Lattnerc7029802006-03-18 01:44:44 +00002697
Chris Lattner3e104b12006-04-08 04:15:24 +00002698void SelectionDAGLowering::visitShuffleVector(User &I) {
Dan Gohman475871a2008-07-27 21:46:04 +00002699 SDValue V1 = getValue(I.getOperand(0));
2700 SDValue V2 = getValue(I.getOperand(1));
2701 SDValue Mask = getValue(I.getOperand(2));
Chris Lattner3e104b12006-04-08 04:15:24 +00002702
Dan Gohman7f321562007-06-25 16:23:39 +00002703 setValue(&I, DAG.getNode(ISD::VECTOR_SHUFFLE,
2704 TLI.getValueType(I.getType()),
2705 V1, V2, Mask));
Chris Lattner3e104b12006-04-08 04:15:24 +00002706}
2707
Dan Gohman1d685a42008-06-07 02:02:36 +00002708void SelectionDAGLowering::visitInsertValue(InsertValueInst &I) {
2709 const Value *Op0 = I.getOperand(0);
2710 const Value *Op1 = I.getOperand(1);
2711 const Type *AggTy = I.getType();
2712 const Type *ValTy = Op1->getType();
2713 bool IntoUndef = isa<UndefValue>(Op0);
2714 bool FromUndef = isa<UndefValue>(Op1);
2715
2716 unsigned LinearIndex = ComputeLinearIndex(TLI, AggTy,
2717 I.idx_begin(), I.idx_end());
2718
2719 SmallVector<MVT, 4> AggValueVTs;
2720 ComputeValueVTs(TLI, AggTy, AggValueVTs);
2721 SmallVector<MVT, 4> ValValueVTs;
2722 ComputeValueVTs(TLI, ValTy, ValValueVTs);
2723
2724 unsigned NumAggValues = AggValueVTs.size();
2725 unsigned NumValValues = ValValueVTs.size();
Dan Gohman475871a2008-07-27 21:46:04 +00002726 SmallVector<SDValue, 4> Values(NumAggValues);
Dan Gohman1d685a42008-06-07 02:02:36 +00002727
Dan Gohman475871a2008-07-27 21:46:04 +00002728 SDValue Agg = getValue(Op0);
2729 SDValue Val = getValue(Op1);
Dan Gohman1d685a42008-06-07 02:02:36 +00002730 unsigned i = 0;
2731 // Copy the beginning value(s) from the original aggregate.
2732 for (; i != LinearIndex; ++i)
2733 Values[i] = IntoUndef ? DAG.getNode(ISD::UNDEF, AggValueVTs[i]) :
Dan Gohman475871a2008-07-27 21:46:04 +00002734 SDValue(Agg.Val, Agg.ResNo + i);
Dan Gohman1d685a42008-06-07 02:02:36 +00002735 // Copy values from the inserted value(s).
2736 for (; i != LinearIndex + NumValValues; ++i)
2737 Values[i] = FromUndef ? DAG.getNode(ISD::UNDEF, AggValueVTs[i]) :
Dan Gohman475871a2008-07-27 21:46:04 +00002738 SDValue(Val.Val, Val.ResNo + i - LinearIndex);
Dan Gohman1d685a42008-06-07 02:02:36 +00002739 // Copy remaining value(s) from the original aggregate.
2740 for (; i != NumAggValues; ++i)
2741 Values[i] = IntoUndef ? DAG.getNode(ISD::UNDEF, AggValueVTs[i]) :
Dan Gohman475871a2008-07-27 21:46:04 +00002742 SDValue(Agg.Val, Agg.ResNo + i);
Dan Gohman1d685a42008-06-07 02:02:36 +00002743
Duncan Sandsf9516202008-06-30 10:19:09 +00002744 setValue(&I, DAG.getMergeValues(DAG.getVTList(&AggValueVTs[0], NumAggValues),
2745 &Values[0], NumAggValues));
Dan Gohman041e2eb2008-05-15 19:50:34 +00002746}
2747
Dan Gohman1d685a42008-06-07 02:02:36 +00002748void SelectionDAGLowering::visitExtractValue(ExtractValueInst &I) {
2749 const Value *Op0 = I.getOperand(0);
2750 const Type *AggTy = Op0->getType();
2751 const Type *ValTy = I.getType();
2752 bool OutOfUndef = isa<UndefValue>(Op0);
2753
2754 unsigned LinearIndex = ComputeLinearIndex(TLI, AggTy,
2755 I.idx_begin(), I.idx_end());
2756
2757 SmallVector<MVT, 4> ValValueVTs;
2758 ComputeValueVTs(TLI, ValTy, ValValueVTs);
2759
2760 unsigned NumValValues = ValValueVTs.size();
Dan Gohman475871a2008-07-27 21:46:04 +00002761 SmallVector<SDValue, 4> Values(NumValValues);
Dan Gohman1d685a42008-06-07 02:02:36 +00002762
Dan Gohman475871a2008-07-27 21:46:04 +00002763 SDValue Agg = getValue(Op0);
Dan Gohman1d685a42008-06-07 02:02:36 +00002764 // Copy out the selected value(s).
2765 for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
2766 Values[i - LinearIndex] =
Dan Gohmandded0fd2008-06-20 00:54:19 +00002767 OutOfUndef ? DAG.getNode(ISD::UNDEF, Agg.Val->getValueType(Agg.ResNo + i)) :
Dan Gohman475871a2008-07-27 21:46:04 +00002768 SDValue(Agg.Val, Agg.ResNo + i);
Dan Gohman1d685a42008-06-07 02:02:36 +00002769
Duncan Sandsf9516202008-06-30 10:19:09 +00002770 setValue(&I, DAG.getMergeValues(DAG.getVTList(&ValValueVTs[0], NumValValues),
2771 &Values[0], NumValValues));
Dan Gohman041e2eb2008-05-15 19:50:34 +00002772}
2773
Chris Lattner3e104b12006-04-08 04:15:24 +00002774
Chris Lattner1c08c712005-01-07 07:47:53 +00002775void SelectionDAGLowering::visitGetElementPtr(User &I) {
Dan Gohman475871a2008-07-27 21:46:04 +00002776 SDValue N = getValue(I.getOperand(0));
Chris Lattner1c08c712005-01-07 07:47:53 +00002777 const Type *Ty = I.getOperand(0)->getType();
Chris Lattner1c08c712005-01-07 07:47:53 +00002778
2779 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
2780 OI != E; ++OI) {
2781 Value *Idx = *OI;
Chris Lattnerc88d8e92005-12-05 07:10:48 +00002782 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002783 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
Chris Lattner1c08c712005-01-07 07:47:53 +00002784 if (Field) {
2785 // N = N + Offset
Chris Lattnerb1919e22007-02-10 19:55:17 +00002786 uint64_t Offset = TD->getStructLayout(StTy)->getElementOffset(Field);
Chris Lattner1c08c712005-01-07 07:47:53 +00002787 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
Chris Lattner0bd48932008-01-17 07:00:52 +00002788 DAG.getIntPtrConstant(Offset));
Chris Lattner1c08c712005-01-07 07:47:53 +00002789 }
2790 Ty = StTy->getElementType(Field);
2791 } else {
2792 Ty = cast<SequentialType>(Ty)->getElementType();
Chris Lattner7cc47772005-01-07 21:56:57 +00002793
Chris Lattner7c0104b2005-11-09 04:45:33 +00002794 // If this is a constant subscript, handle it quickly.
2795 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002796 if (CI->getZExtValue() == 0) continue;
Reid Spencer47857812006-12-31 05:55:36 +00002797 uint64_t Offs =
Dale Johannesena7ac2bd2007-10-01 23:08:35 +00002798 TD->getABITypeSize(Ty)*cast<ConstantInt>(CI)->getSExtValue();
Chris Lattner0bd48932008-01-17 07:00:52 +00002799 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
2800 DAG.getIntPtrConstant(Offs));
Chris Lattner7c0104b2005-11-09 04:45:33 +00002801 continue;
Chris Lattner1c08c712005-01-07 07:47:53 +00002802 }
Chris Lattner7c0104b2005-11-09 04:45:33 +00002803
2804 // N = N + Idx * ElementSize;
Dale Johannesena7ac2bd2007-10-01 23:08:35 +00002805 uint64_t ElementSize = TD->getABITypeSize(Ty);
Dan Gohman475871a2008-07-27 21:46:04 +00002806 SDValue IdxN = getValue(Idx);
Chris Lattner7c0104b2005-11-09 04:45:33 +00002807
2808 // If the index is smaller or larger than intptr_t, truncate or extend
2809 // it.
Evan Cheng83785c82008-08-20 22:45:34 +00002810 if (IdxN.getValueType().bitsLT(N.getValueType()))
Reid Spencer47857812006-12-31 05:55:36 +00002811 IdxN = DAG.getNode(ISD::SIGN_EXTEND, N.getValueType(), IdxN);
Evan Cheng83785c82008-08-20 22:45:34 +00002812 else if (IdxN.getValueType().bitsGT(N.getValueType()))
Chris Lattner7c0104b2005-11-09 04:45:33 +00002813 IdxN = DAG.getNode(ISD::TRUNCATE, N.getValueType(), IdxN);
2814
2815 // If this is a multiply by a power of two, turn it into a shl
2816 // immediately. This is a very common case.
2817 if (isPowerOf2_64(ElementSize)) {
2818 unsigned Amt = Log2_64(ElementSize);
2819 IdxN = DAG.getNode(ISD::SHL, N.getValueType(), IdxN,
Chris Lattner6b2d6962005-11-09 16:50:40 +00002820 DAG.getConstant(Amt, TLI.getShiftAmountTy()));
Chris Lattner7c0104b2005-11-09 04:45:33 +00002821 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
2822 continue;
2823 }
2824
Dan Gohman475871a2008-07-27 21:46:04 +00002825 SDValue Scale = DAG.getIntPtrConstant(ElementSize);
Chris Lattner7c0104b2005-11-09 04:45:33 +00002826 IdxN = DAG.getNode(ISD::MUL, N.getValueType(), IdxN, Scale);
2827 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
Chris Lattner1c08c712005-01-07 07:47:53 +00002828 }
2829 }
2830 setValue(&I, N);
2831}
2832
2833void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
2834 // If this is a fixed sized alloca in the entry block of the function,
2835 // allocate it statically on the stack.
2836 if (FuncInfo.StaticAllocaMap.count(&I))
2837 return; // getValue will auto-populate this.
2838
2839 const Type *Ty = I.getAllocatedType();
Duncan Sands514ab342007-11-01 20:53:16 +00002840 uint64_t TySize = TLI.getTargetData()->getABITypeSize(Ty);
Chris Lattner58092e32007-01-20 22:35:55 +00002841 unsigned Align =
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00002842 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
Chris Lattner58092e32007-01-20 22:35:55 +00002843 I.getAlignment());
Chris Lattner1c08c712005-01-07 07:47:53 +00002844
Dan Gohman475871a2008-07-27 21:46:04 +00002845 SDValue AllocSize = getValue(I.getArraySize());
Duncan Sands83ec4b62008-06-06 12:08:01 +00002846 MVT IntPtr = TLI.getPointerTy();
Duncan Sands8e4eb092008-06-08 20:54:56 +00002847 if (IntPtr.bitsLT(AllocSize.getValueType()))
Chris Lattner68cd65e2005-01-22 23:04:37 +00002848 AllocSize = DAG.getNode(ISD::TRUNCATE, IntPtr, AllocSize);
Duncan Sands8e4eb092008-06-08 20:54:56 +00002849 else if (IntPtr.bitsGT(AllocSize.getValueType()))
Chris Lattner68cd65e2005-01-22 23:04:37 +00002850 AllocSize = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, AllocSize);
Chris Lattner1c08c712005-01-07 07:47:53 +00002851
Chris Lattner68cd65e2005-01-22 23:04:37 +00002852 AllocSize = DAG.getNode(ISD::MUL, IntPtr, AllocSize,
Chris Lattner0bd48932008-01-17 07:00:52 +00002853 DAG.getIntPtrConstant(TySize));
Chris Lattner1c08c712005-01-07 07:47:53 +00002854
Evan Cheng45157792007-08-16 23:46:29 +00002855 // Handle alignment. If the requested alignment is less than or equal to
2856 // the stack alignment, ignore it. If the size is greater than or equal to
2857 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
Chris Lattner1c08c712005-01-07 07:47:53 +00002858 unsigned StackAlign =
2859 TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
Evan Cheng45157792007-08-16 23:46:29 +00002860 if (Align <= StackAlign)
Chris Lattner1c08c712005-01-07 07:47:53 +00002861 Align = 0;
Evan Cheng45157792007-08-16 23:46:29 +00002862
2863 // Round the size of the allocation up to the stack alignment size
2864 // by add SA-1 to the size.
2865 AllocSize = DAG.getNode(ISD::ADD, AllocSize.getValueType(), AllocSize,
Chris Lattner0bd48932008-01-17 07:00:52 +00002866 DAG.getIntPtrConstant(StackAlign-1));
Evan Cheng45157792007-08-16 23:46:29 +00002867 // Mask out the low bits for alignment purposes.
2868 AllocSize = DAG.getNode(ISD::AND, AllocSize.getValueType(), AllocSize,
Chris Lattner0bd48932008-01-17 07:00:52 +00002869 DAG.getIntPtrConstant(~(uint64_t)(StackAlign-1)));
Chris Lattner1c08c712005-01-07 07:47:53 +00002870
Dan Gohman475871a2008-07-27 21:46:04 +00002871 SDValue Ops[] = { getRoot(), AllocSize, DAG.getIntPtrConstant(Align) };
Duncan Sands83ec4b62008-06-06 12:08:01 +00002872 const MVT *VTs = DAG.getNodeValueTypes(AllocSize.getValueType(),
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00002873 MVT::Other);
Dan Gohman475871a2008-07-27 21:46:04 +00002874 SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, VTs, 2, Ops, 3);
Chris Lattner0da331f2007-02-04 01:31:47 +00002875 setValue(&I, DSA);
2876 DAG.setRoot(DSA.getValue(1));
Chris Lattner1c08c712005-01-07 07:47:53 +00002877
2878 // Inform the Frame Information that we have just allocated a variable-sized
2879 // object.
2880 CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
2881}
2882
Chris Lattner1c08c712005-01-07 07:47:53 +00002883void SelectionDAGLowering::visitLoad(LoadInst &I) {
Dan Gohman8a6ccb52008-06-09 15:21:47 +00002884 const Value *SV = I.getOperand(0);
Dan Gohman475871a2008-07-27 21:46:04 +00002885 SDValue Ptr = getValue(SV);
Dan Gohman8a6ccb52008-06-09 15:21:47 +00002886
2887 const Type *Ty = I.getType();
2888 bool isVolatile = I.isVolatile();
2889 unsigned Alignment = I.getAlignment();
2890
2891 SmallVector<MVT, 4> ValueVTs;
2892 SmallVector<uint64_t, 4> Offsets;
2893 ComputeValueVTs(TLI, Ty, ValueVTs, &Offsets);
2894 unsigned NumValues = ValueVTs.size();
2895 if (NumValues == 0)
2896 return;
Misha Brukmanedf128a2005-04-21 22:36:52 +00002897
Dan Gohman475871a2008-07-27 21:46:04 +00002898 SDValue Root;
Dan Gohman8b4588f2008-07-25 00:04:14 +00002899 bool ConstantMemory = false;
Chris Lattnerd3948112005-01-17 22:19:26 +00002900 if (I.isVolatile())
Dan Gohman8b4588f2008-07-25 00:04:14 +00002901 // Serialize volatile loads with other side effects.
Chris Lattnerd3948112005-01-17 22:19:26 +00002902 Root = getRoot();
Dan Gohman8b4588f2008-07-25 00:04:14 +00002903 else if (AA.pointsToConstantMemory(SV)) {
2904 // Do not serialize (non-volatile) loads of constant memory with anything.
2905 Root = DAG.getEntryNode();
2906 ConstantMemory = true;
2907 } else {
Chris Lattnerd3948112005-01-17 22:19:26 +00002908 // Do not serialize non-volatile loads against each other.
2909 Root = DAG.getRoot();
2910 }
Chris Lattner28b5b1c2006-03-15 22:19:46 +00002911
Dan Gohman475871a2008-07-27 21:46:04 +00002912 SmallVector<SDValue, 4> Values(NumValues);
2913 SmallVector<SDValue, 4> Chains(NumValues);
Dan Gohman1d685a42008-06-07 02:02:36 +00002914 MVT PtrVT = Ptr.getValueType();
2915 for (unsigned i = 0; i != NumValues; ++i) {
Dan Gohman475871a2008-07-27 21:46:04 +00002916 SDValue L = DAG.getLoad(ValueVTs[i], Root,
Dan Gohman1d685a42008-06-07 02:02:36 +00002917 DAG.getNode(ISD::ADD, PtrVT, Ptr,
2918 DAG.getConstant(Offsets[i], PtrVT)),
2919 SV, Offsets[i],
2920 isVolatile, Alignment);
2921 Values[i] = L;
2922 Chains[i] = L.getValue(1);
2923 }
Chris Lattner28b5b1c2006-03-15 22:19:46 +00002924
Dan Gohman8b4588f2008-07-25 00:04:14 +00002925 if (!ConstantMemory) {
Dan Gohman475871a2008-07-27 21:46:04 +00002926 SDValue Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
Dan Gohman8b4588f2008-07-25 00:04:14 +00002927 &Chains[0], NumValues);
2928 if (isVolatile)
2929 DAG.setRoot(Chain);
2930 else
2931 PendingLoads.push_back(Chain);
2932 }
Dan Gohman1d685a42008-06-07 02:02:36 +00002933
Duncan Sandsf9516202008-06-30 10:19:09 +00002934 setValue(&I, DAG.getMergeValues(DAG.getVTList(&ValueVTs[0], NumValues),
2935 &Values[0], NumValues));
Chris Lattner1c08c712005-01-07 07:47:53 +00002936}
2937
2938
2939void SelectionDAGLowering::visitStore(StoreInst &I) {
2940 Value *SrcV = I.getOperand(0);
Dan Gohman1d685a42008-06-07 02:02:36 +00002941 Value *PtrV = I.getOperand(1);
Dan Gohman1d685a42008-06-07 02:02:36 +00002942
2943 SmallVector<MVT, 4> ValueVTs;
2944 SmallVector<uint64_t, 4> Offsets;
2945 ComputeValueVTs(TLI, SrcV->getType(), ValueVTs, &Offsets);
2946 unsigned NumValues = ValueVTs.size();
Dan Gohman8a6ccb52008-06-09 15:21:47 +00002947 if (NumValues == 0)
2948 return;
Dan Gohman1d685a42008-06-07 02:02:36 +00002949
Dan Gohman90d33ee2008-07-30 18:36:51 +00002950 // Get the lowered operands. Note that we do this after
2951 // checking if NumResults is zero, because with zero results
2952 // the operands won't have values in the map.
2953 SDValue Src = getValue(SrcV);
2954 SDValue Ptr = getValue(PtrV);
2955
Dan Gohman475871a2008-07-27 21:46:04 +00002956 SDValue Root = getRoot();
2957 SmallVector<SDValue, 4> Chains(NumValues);
Dan Gohman1d685a42008-06-07 02:02:36 +00002958 MVT PtrVT = Ptr.getValueType();
2959 bool isVolatile = I.isVolatile();
2960 unsigned Alignment = I.getAlignment();
2961 for (unsigned i = 0; i != NumValues; ++i)
Dan Gohman475871a2008-07-27 21:46:04 +00002962 Chains[i] = DAG.getStore(Root, SDValue(Src.Val, Src.ResNo + i),
Dan Gohman1d685a42008-06-07 02:02:36 +00002963 DAG.getNode(ISD::ADD, PtrVT, Ptr,
2964 DAG.getConstant(Offsets[i], PtrVT)),
2965 PtrV, Offsets[i],
2966 isVolatile, Alignment);
2967
2968 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other, &Chains[0], NumValues));
Chris Lattner1c08c712005-01-07 07:47:53 +00002969}
2970
Chris Lattner0eade312006-03-24 02:22:33 +00002971/// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
2972/// node.
2973void SelectionDAGLowering::visitTargetIntrinsic(CallInst &I,
2974 unsigned Intrinsic) {
Duncan Sandsa3355ff2007-12-03 20:06:50 +00002975 bool HasChain = !I.doesNotAccessMemory();
2976 bool OnlyLoad = HasChain && I.onlyReadsMemory();
2977
Chris Lattner0eade312006-03-24 02:22:33 +00002978 // Build the operand list.
Dan Gohman475871a2008-07-27 21:46:04 +00002979 SmallVector<SDValue, 8> Ops;
Chris Lattnere58a7802006-04-02 03:41:14 +00002980 if (HasChain) { // If this intrinsic has side-effects, chainify it.
2981 if (OnlyLoad) {
2982 // We don't need to serialize loads against other loads.
2983 Ops.push_back(DAG.getRoot());
2984 } else {
2985 Ops.push_back(getRoot());
2986 }
2987 }
Chris Lattner0eade312006-03-24 02:22:33 +00002988
2989 // Add the intrinsic ID as an integer operand.
2990 Ops.push_back(DAG.getConstant(Intrinsic, TLI.getPointerTy()));
2991
2992 // Add all operands of the call to the operand list.
2993 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
Dan Gohman475871a2008-07-27 21:46:04 +00002994 SDValue Op = getValue(I.getOperand(i));
Chris Lattner0eade312006-03-24 02:22:33 +00002995 assert(TLI.isTypeLegal(Op.getValueType()) &&
2996 "Intrinsic uses a non-legal type?");
2997 Ops.push_back(Op);
2998 }
2999
Duncan Sands83ec4b62008-06-06 12:08:01 +00003000 std::vector<MVT> VTs;
Chris Lattner0eade312006-03-24 02:22:33 +00003001 if (I.getType() != Type::VoidTy) {
Duncan Sands83ec4b62008-06-06 12:08:01 +00003002 MVT VT = TLI.getValueType(I.getType());
3003 if (VT.isVector()) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00003004 const VectorType *DestTy = cast<VectorType>(I.getType());
Duncan Sands83ec4b62008-06-06 12:08:01 +00003005 MVT EltVT = TLI.getValueType(DestTy->getElementType());
Chris Lattner0eade312006-03-24 02:22:33 +00003006
Duncan Sands83ec4b62008-06-06 12:08:01 +00003007 VT = MVT::getVectorVT(EltVT, DestTy->getNumElements());
Chris Lattner0eade312006-03-24 02:22:33 +00003008 assert(VT != MVT::Other && "Intrinsic uses a non-legal type?");
3009 }
3010
3011 assert(TLI.isTypeLegal(VT) && "Intrinsic uses a non-legal type?");
3012 VTs.push_back(VT);
3013 }
3014 if (HasChain)
3015 VTs.push_back(MVT::Other);
3016
Duncan Sands83ec4b62008-06-06 12:08:01 +00003017 const MVT *VTList = DAG.getNodeValueTypes(VTs);
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00003018
Chris Lattner0eade312006-03-24 02:22:33 +00003019 // Create the node.
Dan Gohman475871a2008-07-27 21:46:04 +00003020 SDValue Result;
Chris Lattner48b61a72006-03-28 00:40:33 +00003021 if (!HasChain)
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00003022 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VTList, VTs.size(),
3023 &Ops[0], Ops.size());
Chris Lattner48b61a72006-03-28 00:40:33 +00003024 else if (I.getType() != Type::VoidTy)
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00003025 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, VTList, VTs.size(),
3026 &Ops[0], Ops.size());
Chris Lattner48b61a72006-03-28 00:40:33 +00003027 else
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00003028 Result = DAG.getNode(ISD::INTRINSIC_VOID, VTList, VTs.size(),
3029 &Ops[0], Ops.size());
Chris Lattner48b61a72006-03-28 00:40:33 +00003030
Chris Lattnere58a7802006-04-02 03:41:14 +00003031 if (HasChain) {
Dan Gohman475871a2008-07-27 21:46:04 +00003032 SDValue Chain = Result.getValue(Result.Val->getNumValues()-1);
Chris Lattnere58a7802006-04-02 03:41:14 +00003033 if (OnlyLoad)
3034 PendingLoads.push_back(Chain);
3035 else
3036 DAG.setRoot(Chain);
3037 }
Chris Lattner0eade312006-03-24 02:22:33 +00003038 if (I.getType() != Type::VoidTy) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00003039 if (const VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
Duncan Sands83ec4b62008-06-06 12:08:01 +00003040 MVT VT = TLI.getValueType(PTy);
Dan Gohman7f321562007-06-25 16:23:39 +00003041 Result = DAG.getNode(ISD::BIT_CONVERT, VT, Result);
Chris Lattner0eade312006-03-24 02:22:33 +00003042 }
3043 setValue(&I, Result);
3044 }
3045}
3046
Duncan Sandsb4fd45e2007-07-06 09:10:03 +00003047/// ExtractTypeInfo - Returns the type info, possibly bitcast, encoded in V.
Duncan Sandscf26d7c2007-07-04 20:52:51 +00003048static GlobalVariable *ExtractTypeInfo (Value *V) {
Anton Korobeynikov0b12ecf2008-05-07 22:54:15 +00003049 V = V->stripPointerCasts();
Duncan Sandsb4fd45e2007-07-06 09:10:03 +00003050 GlobalVariable *GV = dyn_cast<GlobalVariable>(V);
Anton Korobeynikov4c71dfe2008-02-20 11:10:28 +00003051 assert ((GV || isa<ConstantPointerNull>(V)) &&
Duncan Sandscf26d7c2007-07-04 20:52:51 +00003052 "TypeInfo must be a global variable or NULL");
3053 return GV;
3054}
3055
Duncan Sandsf4070822007-06-15 19:04:19 +00003056/// addCatchInfo - Extract the personality and type infos from an eh.selector
Duncan Sandscf26d7c2007-07-04 20:52:51 +00003057/// call, and add them to the specified machine basic block.
Duncan Sandsf4070822007-06-15 19:04:19 +00003058static void addCatchInfo(CallInst &I, MachineModuleInfo *MMI,
3059 MachineBasicBlock *MBB) {
3060 // Inform the MachineModuleInfo of the personality for this landing pad.
3061 ConstantExpr *CE = cast<ConstantExpr>(I.getOperand(2));
3062 assert(CE->getOpcode() == Instruction::BitCast &&
3063 isa<Function>(CE->getOperand(0)) &&
3064 "Personality should be a function");
3065 MMI->addPersonality(MBB, cast<Function>(CE->getOperand(0)));
3066
3067 // Gather all the type infos for this landing pad and pass them along to
3068 // MachineModuleInfo.
3069 std::vector<GlobalVariable *> TyInfo;
Duncan Sandscf26d7c2007-07-04 20:52:51 +00003070 unsigned N = I.getNumOperands();
3071
3072 for (unsigned i = N - 1; i > 2; --i) {
3073 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(i))) {
3074 unsigned FilterLength = CI->getZExtValue();
Duncan Sands6590b042007-08-27 15:47:50 +00003075 unsigned FirstCatch = i + FilterLength + !FilterLength;
Duncan Sandscf26d7c2007-07-04 20:52:51 +00003076 assert (FirstCatch <= N && "Invalid filter length");
3077
3078 if (FirstCatch < N) {
3079 TyInfo.reserve(N - FirstCatch);
3080 for (unsigned j = FirstCatch; j < N; ++j)
3081 TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
3082 MMI->addCatchTypeInfo(MBB, TyInfo);
3083 TyInfo.clear();
3084 }
3085
Duncan Sands6590b042007-08-27 15:47:50 +00003086 if (!FilterLength) {
3087 // Cleanup.
3088 MMI->addCleanup(MBB);
3089 } else {
3090 // Filter.
3091 TyInfo.reserve(FilterLength - 1);
3092 for (unsigned j = i + 1; j < FirstCatch; ++j)
3093 TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
3094 MMI->addFilterTypeInfo(MBB, TyInfo);
3095 TyInfo.clear();
3096 }
Duncan Sandscf26d7c2007-07-04 20:52:51 +00003097
3098 N = i;
3099 }
Duncan Sandsf4070822007-06-15 19:04:19 +00003100 }
Duncan Sandscf26d7c2007-07-04 20:52:51 +00003101
3102 if (N > 3) {
3103 TyInfo.reserve(N - 3);
3104 for (unsigned j = 3; j < N; ++j)
3105 TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
Duncan Sandsf4070822007-06-15 19:04:19 +00003106 MMI->addCatchTypeInfo(MBB, TyInfo);
Duncan Sandscf26d7c2007-07-04 20:52:51 +00003107 }
Duncan Sandsf4070822007-06-15 19:04:19 +00003108}
3109
Mon P Wang63307c32008-05-05 19:05:59 +00003110
3111/// Inlined utility function to implement binary input atomic intrinsics for
3112// visitIntrinsicCall: I is a call instruction
3113// Op is the associated NodeType for I
3114const char *
3115SelectionDAGLowering::implVisitBinaryAtomic(CallInst& I, ISD::NodeType Op) {
Dan Gohman475871a2008-07-27 21:46:04 +00003116 SDValue Root = getRoot();
3117 SDValue L = DAG.getAtomic(Op, Root,
Mon P Wang63307c32008-05-05 19:05:59 +00003118 getValue(I.getOperand(1)),
Dan Gohmanfd4418f2008-06-25 16:07:49 +00003119 getValue(I.getOperand(2)),
Mon P Wang28873102008-06-25 08:15:39 +00003120 I.getOperand(1));
Mon P Wang63307c32008-05-05 19:05:59 +00003121 setValue(&I, L);
3122 DAG.setRoot(L.getValue(1));
3123 return 0;
3124}
3125
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003126/// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
3127/// we want to emit this as a call to a named external function, return the name
3128/// otherwise lower it and return null.
3129const char *
3130SelectionDAGLowering::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
3131 switch (Intrinsic) {
Chris Lattner0eade312006-03-24 02:22:33 +00003132 default:
3133 // By default, turn this into a target intrinsic node.
3134 visitTargetIntrinsic(I, Intrinsic);
3135 return 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003136 case Intrinsic::vastart: visitVAStart(I); return 0;
3137 case Intrinsic::vaend: visitVAEnd(I); return 0;
3138 case Intrinsic::vacopy: visitVACopy(I); return 0;
Nate Begemanbcc5f362007-01-29 22:58:52 +00003139 case Intrinsic::returnaddress:
3140 setValue(&I, DAG.getNode(ISD::RETURNADDR, TLI.getPointerTy(),
3141 getValue(I.getOperand(1))));
3142 return 0;
3143 case Intrinsic::frameaddress:
3144 setValue(&I, DAG.getNode(ISD::FRAMEADDR, TLI.getPointerTy(),
3145 getValue(I.getOperand(1))));
3146 return 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003147 case Intrinsic::setjmp:
Anton Korobeynikovd27a2582006-12-10 23:12:42 +00003148 return "_setjmp"+!TLI.usesUnderscoreSetJmp();
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003149 break;
3150 case Intrinsic::longjmp:
Anton Korobeynikovd27a2582006-12-10 23:12:42 +00003151 return "_longjmp"+!TLI.usesUnderscoreLongJmp();
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003152 break;
Chris Lattner03dd4652006-03-03 00:00:25 +00003153 case Intrinsic::memcpy_i32:
Dan Gohman707e0182008-04-12 04:36:06 +00003154 case Intrinsic::memcpy_i64: {
Dan Gohman475871a2008-07-27 21:46:04 +00003155 SDValue Op1 = getValue(I.getOperand(1));
3156 SDValue Op2 = getValue(I.getOperand(2));
3157 SDValue Op3 = getValue(I.getOperand(3));
Dan Gohman707e0182008-04-12 04:36:06 +00003158 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
3159 DAG.setRoot(DAG.getMemcpy(getRoot(), Op1, Op2, Op3, Align, false,
3160 I.getOperand(1), 0, I.getOperand(2), 0));
Chris Lattner03dd4652006-03-03 00:00:25 +00003161 return 0;
Dan Gohman707e0182008-04-12 04:36:06 +00003162 }
Chris Lattner03dd4652006-03-03 00:00:25 +00003163 case Intrinsic::memset_i32:
Dan Gohman707e0182008-04-12 04:36:06 +00003164 case Intrinsic::memset_i64: {
Dan Gohman475871a2008-07-27 21:46:04 +00003165 SDValue Op1 = getValue(I.getOperand(1));
3166 SDValue Op2 = getValue(I.getOperand(2));
3167 SDValue Op3 = getValue(I.getOperand(3));
Dan Gohman707e0182008-04-12 04:36:06 +00003168 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
3169 DAG.setRoot(DAG.getMemset(getRoot(), Op1, Op2, Op3, Align,
3170 I.getOperand(1), 0));
Chris Lattner03dd4652006-03-03 00:00:25 +00003171 return 0;
Dan Gohman707e0182008-04-12 04:36:06 +00003172 }
Chris Lattner03dd4652006-03-03 00:00:25 +00003173 case Intrinsic::memmove_i32:
Dan Gohman707e0182008-04-12 04:36:06 +00003174 case Intrinsic::memmove_i64: {
Dan Gohman475871a2008-07-27 21:46:04 +00003175 SDValue Op1 = getValue(I.getOperand(1));
3176 SDValue Op2 = getValue(I.getOperand(2));
3177 SDValue Op3 = getValue(I.getOperand(3));
Dan Gohman707e0182008-04-12 04:36:06 +00003178 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
3179
3180 // If the source and destination are known to not be aliases, we can
3181 // lower memmove as memcpy.
3182 uint64_t Size = -1ULL;
3183 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op3))
3184 Size = C->getValue();
3185 if (AA.alias(I.getOperand(1), Size, I.getOperand(2), Size) ==
3186 AliasAnalysis::NoAlias) {
3187 DAG.setRoot(DAG.getMemcpy(getRoot(), Op1, Op2, Op3, Align, false,
3188 I.getOperand(1), 0, I.getOperand(2), 0));
3189 return 0;
3190 }
3191
3192 DAG.setRoot(DAG.getMemmove(getRoot(), Op1, Op2, Op3, Align,
3193 I.getOperand(1), 0, I.getOperand(2), 0));
Chris Lattner03dd4652006-03-03 00:00:25 +00003194 return 0;
Dan Gohman707e0182008-04-12 04:36:06 +00003195 }
Chris Lattner86cb6432005-12-13 17:40:33 +00003196 case Intrinsic::dbg_stoppoint: {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00003197 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskey43970fe2006-03-23 18:06:46 +00003198 DbgStopPointInst &SPI = cast<DbgStopPointInst>(I);
Jim Laskey44c3b9f2007-01-26 21:22:28 +00003199 if (MMI && SPI.getContext() && MMI->Verify(SPI.getContext())) {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00003200 DebugInfoDesc *DD = MMI->getDescFor(SPI.getContext());
Jim Laskeyce72b172006-02-11 01:01:30 +00003201 assert(DD && "Not a debug information descriptor");
Dan Gohman7f460202008-06-30 20:59:49 +00003202 DAG.setRoot(DAG.getDbgStopPoint(getRoot(),
3203 SPI.getLine(),
3204 SPI.getColumn(),
3205 cast<CompileUnitDesc>(DD)));
Chris Lattner86cb6432005-12-13 17:40:33 +00003206 }
Jim Laskey43970fe2006-03-23 18:06:46 +00003207
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +00003208 return 0;
Chris Lattner36ce6912005-11-29 06:21:05 +00003209 }
Jim Laskey43970fe2006-03-23 18:06:46 +00003210 case Intrinsic::dbg_region_start: {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00003211 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskey43970fe2006-03-23 18:06:46 +00003212 DbgRegionStartInst &RSI = cast<DbgRegionStartInst>(I);
Jim Laskey44c3b9f2007-01-26 21:22:28 +00003213 if (MMI && RSI.getContext() && MMI->Verify(RSI.getContext())) {
3214 unsigned LabelID = MMI->RecordRegionStart(RSI.getContext());
Dan Gohman44066042008-07-01 00:05:16 +00003215 DAG.setRoot(DAG.getLabel(ISD::DBG_LABEL, getRoot(), LabelID));
Jim Laskey43970fe2006-03-23 18:06:46 +00003216 }
3217
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +00003218 return 0;
Jim Laskey43970fe2006-03-23 18:06:46 +00003219 }
3220 case Intrinsic::dbg_region_end: {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00003221 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskey43970fe2006-03-23 18:06:46 +00003222 DbgRegionEndInst &REI = cast<DbgRegionEndInst>(I);
Jim Laskey44c3b9f2007-01-26 21:22:28 +00003223 if (MMI && REI.getContext() && MMI->Verify(REI.getContext())) {
3224 unsigned LabelID = MMI->RecordRegionEnd(REI.getContext());
Dan Gohman44066042008-07-01 00:05:16 +00003225 DAG.setRoot(DAG.getLabel(ISD::DBG_LABEL, getRoot(), LabelID));
Jim Laskey43970fe2006-03-23 18:06:46 +00003226 }
3227
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +00003228 return 0;
Jim Laskey43970fe2006-03-23 18:06:46 +00003229 }
3230 case Intrinsic::dbg_func_start: {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00003231 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Evan Cheng1b08bbc2008-02-01 09:10:45 +00003232 if (!MMI) return 0;
Jim Laskey43970fe2006-03-23 18:06:46 +00003233 DbgFuncStartInst &FSI = cast<DbgFuncStartInst>(I);
Evan Cheng1b08bbc2008-02-01 09:10:45 +00003234 Value *SP = FSI.getSubprogram();
3235 if (SP && MMI->Verify(SP)) {
3236 // llvm.dbg.func.start implicitly defines a dbg_stoppoint which is
3237 // what (most?) gdb expects.
3238 DebugInfoDesc *DD = MMI->getDescFor(SP);
3239 assert(DD && "Not a debug information descriptor");
3240 SubprogramDesc *Subprogram = cast<SubprogramDesc>(DD);
3241 const CompileUnitDesc *CompileUnit = Subprogram->getFile();
Dan Gohman99fe47b2008-06-30 22:21:03 +00003242 unsigned SrcFile = MMI->RecordSource(CompileUnit);
Evan Cheng1b08bbc2008-02-01 09:10:45 +00003243 // Record the source line but does create a label. It will be emitted
3244 // at asm emission time.
3245 MMI->RecordSourceLine(Subprogram->getLine(), 0, SrcFile);
Jim Laskey43970fe2006-03-23 18:06:46 +00003246 }
3247
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +00003248 return 0;
Jim Laskey43970fe2006-03-23 18:06:46 +00003249 }
3250 case Intrinsic::dbg_declare: {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00003251 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskey43970fe2006-03-23 18:06:46 +00003252 DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
Evan Chenga844bde2008-02-02 04:07:54 +00003253 Value *Variable = DI.getVariable();
3254 if (MMI && Variable && MMI->Verify(Variable))
3255 DAG.setRoot(DAG.getNode(ISD::DECLARE, MVT::Other, getRoot(),
3256 getValue(DI.getAddress()), getValue(Variable)));
Jim Laskey43970fe2006-03-23 18:06:46 +00003257 return 0;
3258 }
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003259
Jim Laskeyb180aa12007-02-21 22:53:45 +00003260 case Intrinsic::eh_exception: {
Dale Johannesen1532f3d2008-04-02 00:25:04 +00003261 if (!CurMBB->isLandingPad()) {
3262 // FIXME: Mark exception register as live in. Hack for PR1508.
3263 unsigned Reg = TLI.getExceptionAddressRegister();
3264 if (Reg) CurMBB->addLiveIn(Reg);
Jim Laskey735b6f82007-02-22 15:38:06 +00003265 }
Dale Johannesen1532f3d2008-04-02 00:25:04 +00003266 // Insert the EXCEPTIONADDR instruction.
3267 SDVTList VTs = DAG.getVTList(TLI.getPointerTy(), MVT::Other);
Dan Gohman475871a2008-07-27 21:46:04 +00003268 SDValue Ops[1];
Dale Johannesen1532f3d2008-04-02 00:25:04 +00003269 Ops[0] = DAG.getRoot();
Dan Gohman475871a2008-07-27 21:46:04 +00003270 SDValue Op = DAG.getNode(ISD::EXCEPTIONADDR, VTs, Ops, 1);
Dale Johannesen1532f3d2008-04-02 00:25:04 +00003271 setValue(&I, Op);
3272 DAG.setRoot(Op.getValue(1));
Jim Laskeyb180aa12007-02-21 22:53:45 +00003273 return 0;
3274 }
3275
Anton Korobeynikov8806c7b2007-09-07 11:39:35 +00003276 case Intrinsic::eh_selector_i32:
3277 case Intrinsic::eh_selector_i64: {
Jim Laskeyb180aa12007-02-21 22:53:45 +00003278 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Duncan Sands83ec4b62008-06-06 12:08:01 +00003279 MVT VT = (Intrinsic == Intrinsic::eh_selector_i32 ?
Anton Korobeynikov8806c7b2007-09-07 11:39:35 +00003280 MVT::i32 : MVT::i64);
3281
Dale Johannesen1532f3d2008-04-02 00:25:04 +00003282 if (MMI) {
Duncan Sandsf4070822007-06-15 19:04:19 +00003283 if (CurMBB->isLandingPad())
3284 addCatchInfo(I, MMI, CurMBB);
Evan Chenge47c3332007-06-27 18:45:32 +00003285 else {
Duncan Sandsf4070822007-06-15 19:04:19 +00003286#ifndef NDEBUG
Duncan Sandsf4070822007-06-15 19:04:19 +00003287 FuncInfo.CatchInfoLost.insert(&I);
3288#endif
Duncan Sands90291952007-07-06 09:18:59 +00003289 // FIXME: Mark exception selector register as live in. Hack for PR1508.
3290 unsigned Reg = TLI.getExceptionSelectorRegister();
3291 if (Reg) CurMBB->addLiveIn(Reg);
Evan Chenge47c3332007-06-27 18:45:32 +00003292 }
Jim Laskey735b6f82007-02-22 15:38:06 +00003293
3294 // Insert the EHSELECTION instruction.
Anton Korobeynikov8806c7b2007-09-07 11:39:35 +00003295 SDVTList VTs = DAG.getVTList(VT, MVT::Other);
Dan Gohman475871a2008-07-27 21:46:04 +00003296 SDValue Ops[2];
Jim Laskey735b6f82007-02-22 15:38:06 +00003297 Ops[0] = getValue(I.getOperand(1));
3298 Ops[1] = getRoot();
Dan Gohman475871a2008-07-27 21:46:04 +00003299 SDValue Op = DAG.getNode(ISD::EHSELECTION, VTs, Ops, 2);
Jim Laskey735b6f82007-02-22 15:38:06 +00003300 setValue(&I, Op);
3301 DAG.setRoot(Op.getValue(1));
Jim Laskey7a1de982007-02-24 09:45:44 +00003302 } else {
Anton Korobeynikov8806c7b2007-09-07 11:39:35 +00003303 setValue(&I, DAG.getConstant(0, VT));
Jim Laskey735b6f82007-02-22 15:38:06 +00003304 }
Jim Laskeyb180aa12007-02-21 22:53:45 +00003305
3306 return 0;
3307 }
Anton Korobeynikov8806c7b2007-09-07 11:39:35 +00003308
3309 case Intrinsic::eh_typeid_for_i32:
3310 case Intrinsic::eh_typeid_for_i64: {
Jim Laskeyb180aa12007-02-21 22:53:45 +00003311 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Duncan Sands83ec4b62008-06-06 12:08:01 +00003312 MVT VT = (Intrinsic == Intrinsic::eh_typeid_for_i32 ?
Anton Korobeynikov8806c7b2007-09-07 11:39:35 +00003313 MVT::i32 : MVT::i64);
Jim Laskeyb180aa12007-02-21 22:53:45 +00003314
Jim Laskey735b6f82007-02-22 15:38:06 +00003315 if (MMI) {
3316 // Find the type id for the given typeinfo.
Duncan Sandscf26d7c2007-07-04 20:52:51 +00003317 GlobalVariable *GV = ExtractTypeInfo(I.getOperand(1));
Duncan Sands3b346362007-05-04 17:12:26 +00003318
Jim Laskey735b6f82007-02-22 15:38:06 +00003319 unsigned TypeID = MMI->getTypeIDFor(GV);
Anton Korobeynikov8806c7b2007-09-07 11:39:35 +00003320 setValue(&I, DAG.getConstant(TypeID, VT));
Jim Laskey7a1de982007-02-24 09:45:44 +00003321 } else {
Duncan Sandsf664e412007-07-06 14:46:23 +00003322 // Return something different to eh_selector.
Anton Korobeynikov8806c7b2007-09-07 11:39:35 +00003323 setValue(&I, DAG.getConstant(1, VT));
Jim Laskey735b6f82007-02-22 15:38:06 +00003324 }
Jim Laskeyb180aa12007-02-21 22:53:45 +00003325
3326 return 0;
3327 }
3328
Anton Korobeynikov2365f512007-07-14 14:06:15 +00003329 case Intrinsic::eh_return: {
3330 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3331
Dale Johannesen1532f3d2008-04-02 00:25:04 +00003332 if (MMI) {
Anton Korobeynikov2365f512007-07-14 14:06:15 +00003333 MMI->setCallsEHReturn(true);
3334 DAG.setRoot(DAG.getNode(ISD::EH_RETURN,
3335 MVT::Other,
Dan Gohman86e1ebf2008-03-27 19:56:19 +00003336 getControlRoot(),
Anton Korobeynikov2365f512007-07-14 14:06:15 +00003337 getValue(I.getOperand(1)),
3338 getValue(I.getOperand(2))));
3339 } else {
3340 setValue(&I, DAG.getConstant(0, TLI.getPointerTy()));
3341 }
3342
3343 return 0;
3344 }
3345
3346 case Intrinsic::eh_unwind_init: {
3347 if (MachineModuleInfo *MMI = DAG.getMachineModuleInfo()) {
3348 MMI->setCallsUnwindInit(true);
3349 }
3350
3351 return 0;
3352 }
3353
3354 case Intrinsic::eh_dwarf_cfa: {
Duncan Sands83ec4b62008-06-06 12:08:01 +00003355 MVT VT = getValue(I.getOperand(1)).getValueType();
Dan Gohman475871a2008-07-27 21:46:04 +00003356 SDValue CfaArg;
Duncan Sands8e4eb092008-06-08 20:54:56 +00003357 if (VT.bitsGT(TLI.getPointerTy()))
Dale Johannesen1532f3d2008-04-02 00:25:04 +00003358 CfaArg = DAG.getNode(ISD::TRUNCATE,
3359 TLI.getPointerTy(), getValue(I.getOperand(1)));
3360 else
3361 CfaArg = DAG.getNode(ISD::SIGN_EXTEND,
3362 TLI.getPointerTy(), getValue(I.getOperand(1)));
Anton Korobeynikov2365f512007-07-14 14:06:15 +00003363
Dan Gohman475871a2008-07-27 21:46:04 +00003364 SDValue Offset = DAG.getNode(ISD::ADD,
Dale Johannesen1532f3d2008-04-02 00:25:04 +00003365 TLI.getPointerTy(),
3366 DAG.getNode(ISD::FRAME_TO_ARGS_OFFSET,
3367 TLI.getPointerTy()),
3368 CfaArg);
3369 setValue(&I, DAG.getNode(ISD::ADD,
3370 TLI.getPointerTy(),
3371 DAG.getNode(ISD::FRAMEADDR,
3372 TLI.getPointerTy(),
3373 DAG.getConstant(0,
3374 TLI.getPointerTy())),
3375 Offset));
Anton Korobeynikov2365f512007-07-14 14:06:15 +00003376 return 0;
3377 }
3378
Dale Johannesen9ab7fb32007-10-02 17:43:59 +00003379 case Intrinsic::sqrt:
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003380 setValue(&I, DAG.getNode(ISD::FSQRT,
3381 getValue(I.getOperand(1)).getValueType(),
3382 getValue(I.getOperand(1))));
3383 return 0;
Dale Johannesen9ab7fb32007-10-02 17:43:59 +00003384 case Intrinsic::powi:
Chris Lattner6ddf8ed2006-09-09 06:03:30 +00003385 setValue(&I, DAG.getNode(ISD::FPOWI,
3386 getValue(I.getOperand(1)).getValueType(),
3387 getValue(I.getOperand(1)),
3388 getValue(I.getOperand(2))));
3389 return 0;
Dan Gohmanac9385a2007-10-12 00:01:22 +00003390 case Intrinsic::sin:
3391 setValue(&I, DAG.getNode(ISD::FSIN,
3392 getValue(I.getOperand(1)).getValueType(),
3393 getValue(I.getOperand(1))));
3394 return 0;
3395 case Intrinsic::cos:
3396 setValue(&I, DAG.getNode(ISD::FCOS,
3397 getValue(I.getOperand(1)).getValueType(),
3398 getValue(I.getOperand(1))));
3399 return 0;
3400 case Intrinsic::pow:
3401 setValue(&I, DAG.getNode(ISD::FPOW,
3402 getValue(I.getOperand(1)).getValueType(),
3403 getValue(I.getOperand(1)),
3404 getValue(I.getOperand(2))));
3405 return 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003406 case Intrinsic::pcmarker: {
Dan Gohman475871a2008-07-27 21:46:04 +00003407 SDValue Tmp = getValue(I.getOperand(1));
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003408 DAG.setRoot(DAG.getNode(ISD::PCMARKER, MVT::Other, getRoot(), Tmp));
3409 return 0;
3410 }
Andrew Lenharth8b91c772005-11-11 22:48:54 +00003411 case Intrinsic::readcyclecounter: {
Dan Gohman475871a2008-07-27 21:46:04 +00003412 SDValue Op = getRoot();
3413 SDValue Tmp = DAG.getNode(ISD::READCYCLECOUNTER,
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00003414 DAG.getNodeValueTypes(MVT::i64, MVT::Other), 2,
3415 &Op, 1);
Andrew Lenharth8b91c772005-11-11 22:48:54 +00003416 setValue(&I, Tmp);
3417 DAG.setRoot(Tmp.getValue(1));
Andrew Lenharth51b8d542005-11-11 16:47:30 +00003418 return 0;
Andrew Lenharth8b91c772005-11-11 22:48:54 +00003419 }
Chris Lattnerc6eb6d72007-04-10 03:20:39 +00003420 case Intrinsic::part_select: {
Reid Spencer3f108cb2007-04-05 01:20:18 +00003421 // Currently not implemented: just abort
Reid Spencerf75b8742007-04-12 02:48:46 +00003422 assert(0 && "part_select intrinsic not implemented");
3423 abort();
3424 }
3425 case Intrinsic::part_set: {
3426 // Currently not implemented: just abort
3427 assert(0 && "part_set intrinsic not implemented");
Reid Spencer3f108cb2007-04-05 01:20:18 +00003428 abort();
Reid Spenceraddd11d2007-04-04 23:48:25 +00003429 }
Reid Spencera4f9c4d2007-04-01 07:34:11 +00003430 case Intrinsic::bswap:
Nate Begemand88fc032006-01-14 03:14:10 +00003431 setValue(&I, DAG.getNode(ISD::BSWAP,
3432 getValue(I.getOperand(1)).getValueType(),
3433 getValue(I.getOperand(1))));
3434 return 0;
Reid Spencera4f9c4d2007-04-01 07:34:11 +00003435 case Intrinsic::cttz: {
Dan Gohman475871a2008-07-27 21:46:04 +00003436 SDValue Arg = getValue(I.getOperand(1));
Duncan Sands83ec4b62008-06-06 12:08:01 +00003437 MVT Ty = Arg.getValueType();
Dan Gohman475871a2008-07-27 21:46:04 +00003438 SDValue result = DAG.getNode(ISD::CTTZ, Ty, Arg);
Reid Spencera4f9c4d2007-04-01 07:34:11 +00003439 setValue(&I, result);
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003440 return 0;
Reid Spencera4f9c4d2007-04-01 07:34:11 +00003441 }
3442 case Intrinsic::ctlz: {
Dan Gohman475871a2008-07-27 21:46:04 +00003443 SDValue Arg = getValue(I.getOperand(1));
Duncan Sands83ec4b62008-06-06 12:08:01 +00003444 MVT Ty = Arg.getValueType();
Dan Gohman475871a2008-07-27 21:46:04 +00003445 SDValue result = DAG.getNode(ISD::CTLZ, Ty, Arg);
Reid Spencera4f9c4d2007-04-01 07:34:11 +00003446 setValue(&I, result);
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003447 return 0;
Reid Spencera4f9c4d2007-04-01 07:34:11 +00003448 }
3449 case Intrinsic::ctpop: {
Dan Gohman475871a2008-07-27 21:46:04 +00003450 SDValue Arg = getValue(I.getOperand(1));
Duncan Sands83ec4b62008-06-06 12:08:01 +00003451 MVT Ty = Arg.getValueType();
Dan Gohman475871a2008-07-27 21:46:04 +00003452 SDValue result = DAG.getNode(ISD::CTPOP, Ty, Arg);
Reid Spencera4f9c4d2007-04-01 07:34:11 +00003453 setValue(&I, result);
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003454 return 0;
Reid Spencera4f9c4d2007-04-01 07:34:11 +00003455 }
Chris Lattner140d53c2006-01-13 02:50:02 +00003456 case Intrinsic::stacksave: {
Dan Gohman475871a2008-07-27 21:46:04 +00003457 SDValue Op = getRoot();
3458 SDValue Tmp = DAG.getNode(ISD::STACKSAVE,
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00003459 DAG.getNodeValueTypes(TLI.getPointerTy(), MVT::Other), 2, &Op, 1);
Chris Lattner140d53c2006-01-13 02:50:02 +00003460 setValue(&I, Tmp);
3461 DAG.setRoot(Tmp.getValue(1));
3462 return 0;
3463 }
Chris Lattner39a17dd2006-01-23 05:22:07 +00003464 case Intrinsic::stackrestore: {
Dan Gohman475871a2008-07-27 21:46:04 +00003465 SDValue Tmp = getValue(I.getOperand(1));
Chris Lattner39a17dd2006-01-23 05:22:07 +00003466 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, MVT::Other, getRoot(), Tmp));
Chris Lattner140d53c2006-01-13 02:50:02 +00003467 return 0;
Chris Lattner39a17dd2006-01-23 05:22:07 +00003468 }
Tanya Lattner24e5aad2007-06-15 22:26:58 +00003469 case Intrinsic::var_annotation:
3470 // Discard annotate attributes
3471 return 0;
Duncan Sands36397f52007-07-27 12:58:54 +00003472
Duncan Sands36397f52007-07-27 12:58:54 +00003473 case Intrinsic::init_trampoline: {
Anton Korobeynikov0b12ecf2008-05-07 22:54:15 +00003474 const Function *F = cast<Function>(I.getOperand(2)->stripPointerCasts());
Duncan Sands36397f52007-07-27 12:58:54 +00003475
Dan Gohman475871a2008-07-27 21:46:04 +00003476 SDValue Ops[6];
Duncan Sands36397f52007-07-27 12:58:54 +00003477 Ops[0] = getRoot();
3478 Ops[1] = getValue(I.getOperand(1));
3479 Ops[2] = getValue(I.getOperand(2));
3480 Ops[3] = getValue(I.getOperand(3));
3481 Ops[4] = DAG.getSrcValue(I.getOperand(1));
3482 Ops[5] = DAG.getSrcValue(F);
3483
Dan Gohman475871a2008-07-27 21:46:04 +00003484 SDValue Tmp = DAG.getNode(ISD::TRAMPOLINE,
Duncan Sandsf7331b32007-09-11 14:10:23 +00003485 DAG.getNodeValueTypes(TLI.getPointerTy(),
3486 MVT::Other), 2,
3487 Ops, 6);
3488
3489 setValue(&I, Tmp);
3490 DAG.setRoot(Tmp.getValue(1));
Duncan Sands36397f52007-07-27 12:58:54 +00003491 return 0;
3492 }
Gordon Henriksence224772008-01-07 01:30:38 +00003493
3494 case Intrinsic::gcroot:
Gordon Henriksen5eca0752008-08-17 18:44:35 +00003495 if (GFI) {
Gordon Henriksence224772008-01-07 01:30:38 +00003496 Value *Alloca = I.getOperand(1);
3497 Constant *TypeMap = cast<Constant>(I.getOperand(2));
3498
3499 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).Val);
Gordon Henriksen5eca0752008-08-17 18:44:35 +00003500 GFI->addStackRoot(FI->getIndex(), TypeMap);
Gordon Henriksence224772008-01-07 01:30:38 +00003501 }
3502 return 0;
3503
3504 case Intrinsic::gcread:
3505 case Intrinsic::gcwrite:
Gordon Henriksen5eca0752008-08-17 18:44:35 +00003506 assert(0 && "GC failed to lower gcread/gcwrite intrinsics!");
Gordon Henriksence224772008-01-07 01:30:38 +00003507 return 0;
3508
Anton Korobeynikov917c2a62007-11-15 23:25:33 +00003509 case Intrinsic::flt_rounds: {
Dan Gohman1a024862008-01-31 00:41:03 +00003510 setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, MVT::i32));
Anton Korobeynikov917c2a62007-11-15 23:25:33 +00003511 return 0;
3512 }
Anton Korobeynikov66fac792008-01-15 07:02:33 +00003513
3514 case Intrinsic::trap: {
3515 DAG.setRoot(DAG.getNode(ISD::TRAP, MVT::Other, getRoot()));
3516 return 0;
3517 }
Evan Cheng27b7db52008-03-08 00:58:38 +00003518 case Intrinsic::prefetch: {
Dan Gohman475871a2008-07-27 21:46:04 +00003519 SDValue Ops[4];
Evan Cheng27b7db52008-03-08 00:58:38 +00003520 Ops[0] = getRoot();
3521 Ops[1] = getValue(I.getOperand(1));
3522 Ops[2] = getValue(I.getOperand(2));
3523 Ops[3] = getValue(I.getOperand(3));
3524 DAG.setRoot(DAG.getNode(ISD::PREFETCH, MVT::Other, &Ops[0], 4));
3525 return 0;
3526 }
3527
Andrew Lenharth22c5c1b2008-02-16 01:24:58 +00003528 case Intrinsic::memory_barrier: {
Dan Gohman475871a2008-07-27 21:46:04 +00003529 SDValue Ops[6];
Andrew Lenharth22c5c1b2008-02-16 01:24:58 +00003530 Ops[0] = getRoot();
3531 for (int x = 1; x < 6; ++x)
3532 Ops[x] = getValue(I.getOperand(x));
3533
3534 DAG.setRoot(DAG.getNode(ISD::MEMBARRIER, MVT::Other, &Ops[0], 6));
3535 return 0;
3536 }
Mon P Wang28873102008-06-25 08:15:39 +00003537 case Intrinsic::atomic_cmp_swap: {
Dan Gohman475871a2008-07-27 21:46:04 +00003538 SDValue Root = getRoot();
3539 SDValue L = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, Root,
Andrew Lenharthab0b9492008-02-21 06:45:13 +00003540 getValue(I.getOperand(1)),
3541 getValue(I.getOperand(2)),
Dan Gohmanfd4418f2008-06-25 16:07:49 +00003542 getValue(I.getOperand(3)),
Mon P Wang28873102008-06-25 08:15:39 +00003543 I.getOperand(1));
Andrew Lenharthab0b9492008-02-21 06:45:13 +00003544 setValue(&I, L);
3545 DAG.setRoot(L.getValue(1));
3546 return 0;
3547 }
Mon P Wang28873102008-06-25 08:15:39 +00003548 case Intrinsic::atomic_load_add:
3549 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_ADD);
3550 case Intrinsic::atomic_load_sub:
3551 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_SUB);
Mon P Wang63307c32008-05-05 19:05:59 +00003552 case Intrinsic::atomic_load_and:
3553 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_AND);
3554 case Intrinsic::atomic_load_or:
3555 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_OR);
3556 case Intrinsic::atomic_load_xor:
3557 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_XOR);
Andrew Lenharth507a58a2008-06-14 05:48:15 +00003558 case Intrinsic::atomic_load_nand:
3559 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_NAND);
Mon P Wang63307c32008-05-05 19:05:59 +00003560 case Intrinsic::atomic_load_min:
3561 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MIN);
3562 case Intrinsic::atomic_load_max:
3563 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MAX);
3564 case Intrinsic::atomic_load_umin:
3565 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMIN);
3566 case Intrinsic::atomic_load_umax:
3567 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMAX);
3568 case Intrinsic::atomic_swap:
3569 return implVisitBinaryAtomic(I, ISD::ATOMIC_SWAP);
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003570 }
3571}
3572
3573
Dan Gohman475871a2008-07-27 21:46:04 +00003574void SelectionDAGLowering::LowerCallTo(CallSite CS, SDValue Callee,
Jim Laskey1da20a72007-02-23 21:45:01 +00003575 bool IsTailCall,
Anton Korobeynikov070280e2007-05-23 11:08:31 +00003576 MachineBasicBlock *LandingPad) {
Duncan Sands6f74b482007-12-19 09:48:52 +00003577 const PointerType *PT = cast<PointerType>(CS.getCalledValue()->getType());
Jim Laskey735b6f82007-02-22 15:38:06 +00003578 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
Anton Korobeynikov070280e2007-05-23 11:08:31 +00003579 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3580 unsigned BeginLabel = 0, EndLabel = 0;
Duncan Sands6f74b482007-12-19 09:48:52 +00003581
Jim Laskey735b6f82007-02-22 15:38:06 +00003582 TargetLowering::ArgListTy Args;
3583 TargetLowering::ArgListEntry Entry;
Duncan Sands6f74b482007-12-19 09:48:52 +00003584 Args.reserve(CS.arg_size());
3585 for (CallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
3586 i != e; ++i) {
Dan Gohman475871a2008-07-27 21:46:04 +00003587 SDValue ArgNode = getValue(*i);
Duncan Sands6f74b482007-12-19 09:48:52 +00003588 Entry.Node = ArgNode; Entry.Ty = (*i)->getType();
Duncan Sands4fee7032007-05-07 20:49:28 +00003589
Duncan Sands6f74b482007-12-19 09:48:52 +00003590 unsigned attrInd = i - CS.arg_begin() + 1;
3591 Entry.isSExt = CS.paramHasAttr(attrInd, ParamAttr::SExt);
3592 Entry.isZExt = CS.paramHasAttr(attrInd, ParamAttr::ZExt);
3593 Entry.isInReg = CS.paramHasAttr(attrInd, ParamAttr::InReg);
3594 Entry.isSRet = CS.paramHasAttr(attrInd, ParamAttr::StructRet);
3595 Entry.isNest = CS.paramHasAttr(attrInd, ParamAttr::Nest);
3596 Entry.isByVal = CS.paramHasAttr(attrInd, ParamAttr::ByVal);
Dale Johannesen08e78b12008-02-22 17:49:45 +00003597 Entry.Alignment = CS.getParamAlignment(attrInd);
Jim Laskey735b6f82007-02-22 15:38:06 +00003598 Args.push_back(Entry);
3599 }
3600
Dale Johannesen1532f3d2008-04-02 00:25:04 +00003601 if (LandingPad && MMI) {
Anton Korobeynikov070280e2007-05-23 11:08:31 +00003602 // Insert a label before the invoke call to mark the try range. This can be
3603 // used to detect deletion of the invoke via the MachineModuleInfo.
3604 BeginLabel = MMI->NextLabelID();
Dale Johannesena4091d32008-04-04 23:48:31 +00003605 // Both PendingLoads and PendingExports must be flushed here;
3606 // this call might not return.
3607 (void)getRoot();
Dan Gohman44066042008-07-01 00:05:16 +00003608 DAG.setRoot(DAG.getLabel(ISD::EH_LABEL, getControlRoot(), BeginLabel));
Anton Korobeynikov070280e2007-05-23 11:08:31 +00003609 }
Duncan Sands6f74b482007-12-19 09:48:52 +00003610
Dan Gohman475871a2008-07-27 21:46:04 +00003611 std::pair<SDValue,SDValue> Result =
Duncan Sands6f74b482007-12-19 09:48:52 +00003612 TLI.LowerCallTo(getRoot(), CS.getType(),
3613 CS.paramHasAttr(0, ParamAttr::SExt),
Duncan Sands00fee652008-02-14 17:28:50 +00003614 CS.paramHasAttr(0, ParamAttr::ZExt),
Duncan Sands6f74b482007-12-19 09:48:52 +00003615 FTy->isVarArg(), CS.getCallingConv(), IsTailCall,
Jim Laskey735b6f82007-02-22 15:38:06 +00003616 Callee, Args, DAG);
Duncan Sands6f74b482007-12-19 09:48:52 +00003617 if (CS.getType() != Type::VoidTy)
3618 setValue(CS.getInstruction(), Result.first);
Jim Laskey735b6f82007-02-22 15:38:06 +00003619 DAG.setRoot(Result.second);
Anton Korobeynikov070280e2007-05-23 11:08:31 +00003620
Dale Johannesen1532f3d2008-04-02 00:25:04 +00003621 if (LandingPad && MMI) {
Anton Korobeynikov070280e2007-05-23 11:08:31 +00003622 // Insert a label at the end of the invoke call to mark the try range. This
3623 // can be used to detect deletion of the invoke via the MachineModuleInfo.
3624 EndLabel = MMI->NextLabelID();
Dan Gohman44066042008-07-01 00:05:16 +00003625 DAG.setRoot(DAG.getLabel(ISD::EH_LABEL, getRoot(), EndLabel));
Anton Korobeynikov070280e2007-05-23 11:08:31 +00003626
Duncan Sands6f74b482007-12-19 09:48:52 +00003627 // Inform MachineModuleInfo of range.
Anton Korobeynikov070280e2007-05-23 11:08:31 +00003628 MMI->addInvoke(LandingPad, BeginLabel, EndLabel);
3629 }
Jim Laskey735b6f82007-02-22 15:38:06 +00003630}
3631
3632
Chris Lattner1c08c712005-01-07 07:47:53 +00003633void SelectionDAGLowering::visitCall(CallInst &I) {
Chris Lattner64e14b12005-01-08 22:48:57 +00003634 const char *RenameFn = 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003635 if (Function *F = I.getCalledFunction()) {
Chris Lattner87b51bc2007-09-10 21:15:22 +00003636 if (F->isDeclaration()) {
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003637 if (unsigned IID = F->getIntrinsicID()) {
3638 RenameFn = visitIntrinsicCall(I, IID);
3639 if (!RenameFn)
3640 return;
Chris Lattner87b51bc2007-09-10 21:15:22 +00003641 }
3642 }
3643
3644 // Check for well-known libc/libm calls. If the function is internal, it
3645 // can't be a library call.
3646 unsigned NameLen = F->getNameLen();
3647 if (!F->hasInternalLinkage() && NameLen) {
3648 const char *NameStr = F->getNameStart();
3649 if (NameStr[0] == 'c' &&
3650 ((NameLen == 8 && !strcmp(NameStr, "copysign")) ||
3651 (NameLen == 9 && !strcmp(NameStr, "copysignf")))) {
3652 if (I.getNumOperands() == 3 && // Basic sanity checks.
3653 I.getOperand(1)->getType()->isFloatingPoint() &&
3654 I.getType() == I.getOperand(1)->getType() &&
3655 I.getType() == I.getOperand(2)->getType()) {
Dan Gohman475871a2008-07-27 21:46:04 +00003656 SDValue LHS = getValue(I.getOperand(1));
3657 SDValue RHS = getValue(I.getOperand(2));
Chris Lattner87b51bc2007-09-10 21:15:22 +00003658 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, LHS.getValueType(),
3659 LHS, RHS));
3660 return;
3661 }
3662 } else if (NameStr[0] == 'f' &&
3663 ((NameLen == 4 && !strcmp(NameStr, "fabs")) ||
Dale Johannesen2f429012007-09-26 21:10:55 +00003664 (NameLen == 5 && !strcmp(NameStr, "fabsf")) ||
3665 (NameLen == 5 && !strcmp(NameStr, "fabsl")))) {
Chris Lattner87b51bc2007-09-10 21:15:22 +00003666 if (I.getNumOperands() == 2 && // Basic sanity checks.
3667 I.getOperand(1)->getType()->isFloatingPoint() &&
3668 I.getType() == I.getOperand(1)->getType()) {
Dan Gohman475871a2008-07-27 21:46:04 +00003669 SDValue Tmp = getValue(I.getOperand(1));
Chris Lattner87b51bc2007-09-10 21:15:22 +00003670 setValue(&I, DAG.getNode(ISD::FABS, Tmp.getValueType(), Tmp));
3671 return;
3672 }
3673 } else if (NameStr[0] == 's' &&
3674 ((NameLen == 3 && !strcmp(NameStr, "sin")) ||
Dale Johannesen2f429012007-09-26 21:10:55 +00003675 (NameLen == 4 && !strcmp(NameStr, "sinf")) ||
3676 (NameLen == 4 && !strcmp(NameStr, "sinl")))) {
Chris Lattner87b51bc2007-09-10 21:15:22 +00003677 if (I.getNumOperands() == 2 && // Basic sanity checks.
3678 I.getOperand(1)->getType()->isFloatingPoint() &&
3679 I.getType() == I.getOperand(1)->getType()) {
Dan Gohman475871a2008-07-27 21:46:04 +00003680 SDValue Tmp = getValue(I.getOperand(1));
Chris Lattner87b51bc2007-09-10 21:15:22 +00003681 setValue(&I, DAG.getNode(ISD::FSIN, Tmp.getValueType(), Tmp));
3682 return;
3683 }
3684 } else if (NameStr[0] == 'c' &&
3685 ((NameLen == 3 && !strcmp(NameStr, "cos")) ||
Dale Johannesen2f429012007-09-26 21:10:55 +00003686 (NameLen == 4 && !strcmp(NameStr, "cosf")) ||
3687 (NameLen == 4 && !strcmp(NameStr, "cosl")))) {
Chris Lattner87b51bc2007-09-10 21:15:22 +00003688 if (I.getNumOperands() == 2 && // Basic sanity checks.
3689 I.getOperand(1)->getType()->isFloatingPoint() &&
3690 I.getType() == I.getOperand(1)->getType()) {
Dan Gohman475871a2008-07-27 21:46:04 +00003691 SDValue Tmp = getValue(I.getOperand(1));
Chris Lattner87b51bc2007-09-10 21:15:22 +00003692 setValue(&I, DAG.getNode(ISD::FCOS, Tmp.getValueType(), Tmp));
3693 return;
Chris Lattnerf76e7dc2005-04-30 04:43:14 +00003694 }
Chris Lattner1ca85d52005-05-14 13:56:55 +00003695 }
Chris Lattner87b51bc2007-09-10 21:15:22 +00003696 }
Chris Lattnerce7518c2006-01-26 22:24:51 +00003697 } else if (isa<InlineAsm>(I.getOperand(0))) {
Duncan Sandsfd7b3262007-12-17 18:08:19 +00003698 visitInlineAsm(&I);
Chris Lattnerce7518c2006-01-26 22:24:51 +00003699 return;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003700 }
Misha Brukmanedf128a2005-04-21 22:36:52 +00003701
Dan Gohman475871a2008-07-27 21:46:04 +00003702 SDValue Callee;
Chris Lattner64e14b12005-01-08 22:48:57 +00003703 if (!RenameFn)
3704 Callee = getValue(I.getOperand(0));
3705 else
3706 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
Anton Korobeynikov070280e2007-05-23 11:08:31 +00003707
Duncan Sands6f74b482007-12-19 09:48:52 +00003708 LowerCallTo(&I, Callee, I.isTailCall());
Chris Lattner1c08c712005-01-07 07:47:53 +00003709}
3710
Jim Laskey735b6f82007-02-22 15:38:06 +00003711
Dan Gohmanb6f5b002007-06-28 23:29:44 +00003712/// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
3713/// this value and returns the result as a ValueVT value. This uses
3714/// Chain/Flag as the input and updates them for the output Chain/Flag.
3715/// If the Flag pointer is NULL, no flag is used.
Dan Gohman475871a2008-07-27 21:46:04 +00003716SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
3717 SDValue &Chain,
3718 SDValue *Flag) const {
Dan Gohman23ce5022008-04-25 18:27:55 +00003719 // Assemble the legal parts into the final values.
Dan Gohman475871a2008-07-27 21:46:04 +00003720 SmallVector<SDValue, 4> Values(ValueVTs.size());
3721 SmallVector<SDValue, 8> Parts;
Chris Lattner6833b062008-04-28 07:16:35 +00003722 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
Dan Gohman23ce5022008-04-25 18:27:55 +00003723 // Copy the legal parts from the registers.
Duncan Sands83ec4b62008-06-06 12:08:01 +00003724 MVT ValueVT = ValueVTs[Value];
Dan Gohman23ce5022008-04-25 18:27:55 +00003725 unsigned NumRegs = TLI->getNumRegisters(ValueVT);
Duncan Sands83ec4b62008-06-06 12:08:01 +00003726 MVT RegisterVT = RegVTs[Value];
Dan Gohman23ce5022008-04-25 18:27:55 +00003727
Chris Lattner6833b062008-04-28 07:16:35 +00003728 Parts.resize(NumRegs);
Dan Gohman23ce5022008-04-25 18:27:55 +00003729 for (unsigned i = 0; i != NumRegs; ++i) {
Dan Gohman475871a2008-07-27 21:46:04 +00003730 SDValue P;
Chris Lattner6833b062008-04-28 07:16:35 +00003731 if (Flag == 0)
3732 P = DAG.getCopyFromReg(Chain, Regs[Part+i], RegisterVT);
3733 else {
3734 P = DAG.getCopyFromReg(Chain, Regs[Part+i], RegisterVT, *Flag);
Dan Gohman23ce5022008-04-25 18:27:55 +00003735 *Flag = P.getValue(2);
Chris Lattner6833b062008-04-28 07:16:35 +00003736 }
3737 Chain = P.getValue(1);
Chris Lattneread0d882008-06-17 06:09:18 +00003738
3739 // If the source register was virtual and if we know something about it,
3740 // add an assert node.
3741 if (TargetRegisterInfo::isVirtualRegister(Regs[Part+i]) &&
3742 RegisterVT.isInteger() && !RegisterVT.isVector()) {
3743 unsigned SlotNo = Regs[Part+i]-TargetRegisterInfo::FirstVirtualRegister;
3744 FunctionLoweringInfo &FLI = DAG.getFunctionLoweringInfo();
3745 if (FLI.LiveOutRegInfo.size() > SlotNo) {
3746 FunctionLoweringInfo::LiveOutInfo &LOI = FLI.LiveOutRegInfo[SlotNo];
3747
3748 unsigned RegSize = RegisterVT.getSizeInBits();
3749 unsigned NumSignBits = LOI.NumSignBits;
3750 unsigned NumZeroBits = LOI.KnownZero.countLeadingOnes();
3751
3752 // FIXME: We capture more information than the dag can represent. For
3753 // now, just use the tightest assertzext/assertsext possible.
3754 bool isSExt = true;
3755 MVT FromVT(MVT::Other);
3756 if (NumSignBits == RegSize)
3757 isSExt = true, FromVT = MVT::i1; // ASSERT SEXT 1
3758 else if (NumZeroBits >= RegSize-1)
3759 isSExt = false, FromVT = MVT::i1; // ASSERT ZEXT 1
3760 else if (NumSignBits > RegSize-8)
3761 isSExt = true, FromVT = MVT::i8; // ASSERT SEXT 8
3762 else if (NumZeroBits >= RegSize-9)
3763 isSExt = false, FromVT = MVT::i8; // ASSERT ZEXT 8
3764 else if (NumSignBits > RegSize-16)
3765 isSExt = true, FromVT = MVT::i16; // ASSERT SEXT 16
3766 else if (NumZeroBits >= RegSize-17)
3767 isSExt = false, FromVT = MVT::i16; // ASSERT ZEXT 16
3768 else if (NumSignBits > RegSize-32)
3769 isSExt = true, FromVT = MVT::i32; // ASSERT SEXT 32
3770 else if (NumZeroBits >= RegSize-33)
3771 isSExt = false, FromVT = MVT::i32; // ASSERT ZEXT 32
3772
3773 if (FromVT != MVT::Other) {
3774 P = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext,
3775 RegisterVT, P, DAG.getValueType(FromVT));
3776
3777 }
3778 }
3779 }
3780
Dan Gohman23ce5022008-04-25 18:27:55 +00003781 Parts[Part+i] = P;
3782 }
Chris Lattner5df99b32007-03-25 05:00:54 +00003783
Dan Gohman23ce5022008-04-25 18:27:55 +00003784 Values[Value] = getCopyFromParts(DAG, &Parts[Part], NumRegs, RegisterVT,
3785 ValueVT);
3786 Part += NumRegs;
3787 }
Duncan Sands4bdcb612008-07-02 17:40:58 +00003788
Duncan Sandsf9516202008-06-30 10:19:09 +00003789 return DAG.getMergeValues(DAG.getVTList(&ValueVTs[0], ValueVTs.size()),
3790 &Values[0], ValueVTs.size());
Chris Lattner864635a2006-02-22 22:37:12 +00003791}
3792
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00003793/// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
3794/// specified value into the registers specified by this object. This uses
3795/// Chain/Flag as the input and updates them for the output Chain/Flag.
Dan Gohmanb6f5b002007-06-28 23:29:44 +00003796/// If the Flag pointer is NULL, no flag is used.
Dan Gohman475871a2008-07-27 21:46:04 +00003797void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG,
3798 SDValue &Chain, SDValue *Flag) const {
Dan Gohmanb6f5b002007-06-28 23:29:44 +00003799 // Get the list of the values's legal parts.
Dan Gohman23ce5022008-04-25 18:27:55 +00003800 unsigned NumRegs = Regs.size();
Dan Gohman475871a2008-07-27 21:46:04 +00003801 SmallVector<SDValue, 8> Parts(NumRegs);
Chris Lattner6833b062008-04-28 07:16:35 +00003802 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
Duncan Sands83ec4b62008-06-06 12:08:01 +00003803 MVT ValueVT = ValueVTs[Value];
Dan Gohman23ce5022008-04-25 18:27:55 +00003804 unsigned NumParts = TLI->getNumRegisters(ValueVT);
Duncan Sands83ec4b62008-06-06 12:08:01 +00003805 MVT RegisterVT = RegVTs[Value];
Dan Gohman23ce5022008-04-25 18:27:55 +00003806
3807 getCopyToParts(DAG, Val.getValue(Val.ResNo + Value),
3808 &Parts[Part], NumParts, RegisterVT);
3809 Part += NumParts;
3810 }
Dan Gohmanb6f5b002007-06-28 23:29:44 +00003811
3812 // Copy the parts into the registers.
Dan Gohman475871a2008-07-27 21:46:04 +00003813 SmallVector<SDValue, 8> Chains(NumRegs);
Dan Gohman23ce5022008-04-25 18:27:55 +00003814 for (unsigned i = 0; i != NumRegs; ++i) {
Dan Gohman475871a2008-07-27 21:46:04 +00003815 SDValue Part;
Chris Lattner6833b062008-04-28 07:16:35 +00003816 if (Flag == 0)
3817 Part = DAG.getCopyToReg(Chain, Regs[i], Parts[i]);
3818 else {
3819 Part = DAG.getCopyToReg(Chain, Regs[i], Parts[i], *Flag);
Dan Gohmanb6f5b002007-06-28 23:29:44 +00003820 *Flag = Part.getValue(1);
Chris Lattner6833b062008-04-28 07:16:35 +00003821 }
3822 Chains[i] = Part.getValue(0);
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00003823 }
Chris Lattner6833b062008-04-28 07:16:35 +00003824
Evan Cheng33bf38a2008-04-28 22:07:13 +00003825 if (NumRegs == 1 || Flag)
3826 // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is
3827 // flagged to it. That is the CopyToReg nodes and the user are considered
3828 // a single scheduling unit. If we create a TokenFactor and return it as
3829 // chain, then the TokenFactor is both a predecessor (operand) of the
3830 // user as well as a successor (the TF operands are flagged to the user).
3831 // c1, f1 = CopyToReg
3832 // c2, f2 = CopyToReg
3833 // c3 = TokenFactor c1, c2
3834 // ...
3835 // = op c3, ..., f2
3836 Chain = Chains[NumRegs-1];
Chris Lattner6833b062008-04-28 07:16:35 +00003837 else
3838 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other, &Chains[0], NumRegs);
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00003839}
Chris Lattner864635a2006-02-22 22:37:12 +00003840
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00003841/// AddInlineAsmOperands - Add this value to the specified inlineasm node
3842/// operand list. This adds the code marker and includes the number of
3843/// values added into it.
3844void RegsForValue::AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
Dan Gohman475871a2008-07-27 21:46:04 +00003845 std::vector<SDValue> &Ops) const {
Duncan Sands83ec4b62008-06-06 12:08:01 +00003846 MVT IntPtrTy = DAG.getTargetLoweringInfo().getPointerTy();
Chris Lattner4b993b12007-04-09 00:33:58 +00003847 Ops.push_back(DAG.getTargetConstant(Code | (Regs.size() << 3), IntPtrTy));
Chris Lattner6833b062008-04-28 07:16:35 +00003848 for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
3849 unsigned NumRegs = TLI->getNumRegisters(ValueVTs[Value]);
Duncan Sands83ec4b62008-06-06 12:08:01 +00003850 MVT RegisterVT = RegVTs[Value];
Chris Lattner6833b062008-04-28 07:16:35 +00003851 for (unsigned i = 0; i != NumRegs; ++i)
3852 Ops.push_back(DAG.getRegister(Regs[Reg++], RegisterVT));
Dan Gohman23ce5022008-04-25 18:27:55 +00003853 }
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00003854}
Chris Lattner864635a2006-02-22 22:37:12 +00003855
3856/// isAllocatableRegister - If the specified register is safe to allocate,
3857/// i.e. it isn't a stack pointer or some other special register, return the
3858/// register class for the register. Otherwise, return null.
3859static const TargetRegisterClass *
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00003860isAllocatableRegister(unsigned Reg, MachineFunction &MF,
Dan Gohman6f0d0242008-02-10 18:45:23 +00003861 const TargetLowering &TLI,
3862 const TargetRegisterInfo *TRI) {
Duncan Sands83ec4b62008-06-06 12:08:01 +00003863 MVT FoundVT = MVT::Other;
Chris Lattnerf8814cf2006-04-02 00:24:45 +00003864 const TargetRegisterClass *FoundRC = 0;
Dan Gohman6f0d0242008-02-10 18:45:23 +00003865 for (TargetRegisterInfo::regclass_iterator RCI = TRI->regclass_begin(),
3866 E = TRI->regclass_end(); RCI != E; ++RCI) {
Duncan Sands83ec4b62008-06-06 12:08:01 +00003867 MVT ThisVT = MVT::Other;
Chris Lattnerf8814cf2006-04-02 00:24:45 +00003868
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00003869 const TargetRegisterClass *RC = *RCI;
3870 // If none of the the value types for this register class are valid, we
3871 // can't use it. For example, 64-bit reg classes on 32-bit targets.
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00003872 for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
3873 I != E; ++I) {
3874 if (TLI.isTypeLegal(*I)) {
Chris Lattnerf8814cf2006-04-02 00:24:45 +00003875 // If we have already found this register in a different register class,
3876 // choose the one with the largest VT specified. For example, on
3877 // PowerPC, we favor f64 register classes over f32.
Duncan Sands8e4eb092008-06-08 20:54:56 +00003878 if (FoundVT == MVT::Other || FoundVT.bitsLT(*I)) {
Chris Lattnerf8814cf2006-04-02 00:24:45 +00003879 ThisVT = *I;
3880 break;
3881 }
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00003882 }
3883 }
3884
Chris Lattnerf8814cf2006-04-02 00:24:45 +00003885 if (ThisVT == MVT::Other) continue;
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00003886
Chris Lattner864635a2006-02-22 22:37:12 +00003887 // NOTE: This isn't ideal. In particular, this might allocate the
3888 // frame pointer in functions that need it (due to them not being taken
3889 // out of allocation, because a variable sized allocation hasn't been seen
3890 // yet). This is a slight code pessimization, but should still work.
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00003891 for (TargetRegisterClass::iterator I = RC->allocation_order_begin(MF),
3892 E = RC->allocation_order_end(MF); I != E; ++I)
Chris Lattnerf8814cf2006-04-02 00:24:45 +00003893 if (*I == Reg) {
3894 // We found a matching register class. Keep looking at others in case
3895 // we find one with larger registers that this physreg is also in.
3896 FoundRC = RC;
3897 FoundVT = ThisVT;
3898 break;
3899 }
Chris Lattner4e4b5762006-02-01 18:59:47 +00003900 }
Chris Lattnerf8814cf2006-04-02 00:24:45 +00003901 return FoundRC;
Chris Lattner864635a2006-02-22 22:37:12 +00003902}
3903
Chris Lattner4e4b5762006-02-01 18:59:47 +00003904
Chris Lattner0c583402007-04-28 20:49:53 +00003905namespace {
3906/// AsmOperandInfo - This contains information for each constraint that we are
3907/// lowering.
Evan Cheng5c807602008-02-26 02:33:44 +00003908struct SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo {
3909 /// CallOperand - If this is the result output operand or a clobber
3910 /// this is null, otherwise it is the incoming operand to the CallInst.
3911 /// This gets modified as the asm is processed.
Dan Gohman475871a2008-07-27 21:46:04 +00003912 SDValue CallOperand;
Evan Cheng5c807602008-02-26 02:33:44 +00003913
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003914 /// AssignedRegs - If this is a register or register class operand, this
3915 /// contains the set of register corresponding to the operand.
3916 RegsForValue AssignedRegs;
3917
Dan Gohman23ce5022008-04-25 18:27:55 +00003918 explicit SDISelAsmOperandInfo(const InlineAsm::ConstraintInfo &info)
Evan Cheng5c807602008-02-26 02:33:44 +00003919 : TargetLowering::AsmOperandInfo(info), CallOperand(0,0) {
Chris Lattner0c583402007-04-28 20:49:53 +00003920 }
Chris Lattner3ff90dc2007-04-30 17:16:27 +00003921
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003922 /// MarkAllocatedRegs - Once AssignedRegs is set, mark the assigned registers
3923 /// busy in OutputRegs/InputRegs.
3924 void MarkAllocatedRegs(bool isOutReg, bool isInReg,
3925 std::set<unsigned> &OutputRegs,
Chris Lattner7cbeb242008-02-21 04:55:52 +00003926 std::set<unsigned> &InputRegs,
3927 const TargetRegisterInfo &TRI) const {
3928 if (isOutReg) {
3929 for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i)
3930 MarkRegAndAliases(AssignedRegs.Regs[i], OutputRegs, TRI);
3931 }
3932 if (isInReg) {
3933 for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i)
3934 MarkRegAndAliases(AssignedRegs.Regs[i], InputRegs, TRI);
3935 }
3936 }
3937
3938private:
3939 /// MarkRegAndAliases - Mark the specified register and all aliases in the
3940 /// specified set.
3941 static void MarkRegAndAliases(unsigned Reg, std::set<unsigned> &Regs,
3942 const TargetRegisterInfo &TRI) {
3943 assert(TargetRegisterInfo::isPhysicalRegister(Reg) && "Isn't a physreg");
3944 Regs.insert(Reg);
3945 if (const unsigned *Aliases = TRI.getAliasSet(Reg))
3946 for (; *Aliases; ++Aliases)
3947 Regs.insert(*Aliases);
3948 }
Chris Lattner0c583402007-04-28 20:49:53 +00003949};
3950} // end anon namespace.
Chris Lattner864635a2006-02-22 22:37:12 +00003951
Chris Lattner3ff90dc2007-04-30 17:16:27 +00003952
Chris Lattner0fe71e92008-02-21 19:43:13 +00003953/// GetRegistersForValue - Assign registers (virtual or physical) for the
3954/// specified operand. We prefer to assign virtual registers, to allow the
3955/// register allocator handle the assignment process. However, if the asm uses
3956/// features that we can't model on machineinstrs, we have SDISel do the
3957/// allocation. This produces generally horrible, but correct, code.
3958///
3959/// OpInfo describes the operand.
3960/// HasEarlyClobber is true if there are any early clobber constraints (=&r)
3961/// or any explicitly clobbered registers.
3962/// Input and OutputRegs are the set of already allocated physical registers.
3963///
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003964void SelectionDAGLowering::
Evan Cheng5c807602008-02-26 02:33:44 +00003965GetRegistersForValue(SDISelAsmOperandInfo &OpInfo, bool HasEarlyClobber,
Chris Lattnerbf996f12007-04-30 17:29:31 +00003966 std::set<unsigned> &OutputRegs,
3967 std::set<unsigned> &InputRegs) {
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003968 // Compute whether this value requires an input register, an output register,
3969 // or both.
3970 bool isOutReg = false;
3971 bool isInReg = false;
3972 switch (OpInfo.Type) {
3973 case InlineAsm::isOutput:
3974 isOutReg = true;
3975
3976 // If this is an early-clobber output, or if there is an input
3977 // constraint that matches this, we need to reserve the input register
3978 // so no other inputs allocate to it.
3979 isInReg = OpInfo.isEarlyClobber || OpInfo.hasMatchingInput;
3980 break;
3981 case InlineAsm::isInput:
3982 isInReg = true;
3983 isOutReg = false;
3984 break;
3985 case InlineAsm::isClobber:
3986 isOutReg = true;
3987 isInReg = true;
3988 break;
3989 }
3990
3991
3992 MachineFunction &MF = DAG.getMachineFunction();
Chris Lattnerb606dba2008-04-28 06:44:42 +00003993 SmallVector<unsigned, 4> Regs;
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003994
3995 // If this is a constraint for a single physreg, or a constraint for a
3996 // register class, find it.
3997 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
3998 TLI.getRegForInlineAsmConstraint(OpInfo.ConstraintCode,
3999 OpInfo.ConstraintVT);
Chris Lattnerbf996f12007-04-30 17:29:31 +00004000
4001 unsigned NumRegs = 1;
4002 if (OpInfo.ConstraintVT != MVT::Other)
Dan Gohmanb9f10192007-06-21 14:42:22 +00004003 NumRegs = TLI.getNumRegisters(OpInfo.ConstraintVT);
Duncan Sands83ec4b62008-06-06 12:08:01 +00004004 MVT RegVT;
4005 MVT ValueVT = OpInfo.ConstraintVT;
Chris Lattnerbf996f12007-04-30 17:29:31 +00004006
Chris Lattnerbf996f12007-04-30 17:29:31 +00004007
4008 // If this is a constraint for a specific physical register, like {r17},
4009 // assign it now.
4010 if (PhysReg.first) {
4011 if (OpInfo.ConstraintVT == MVT::Other)
4012 ValueVT = *PhysReg.second->vt_begin();
4013
4014 // Get the actual register value type. This is important, because the user
4015 // may have asked for (e.g.) the AX register in i32 type. We need to
4016 // remember that AX is actually i16 to get the right extension.
4017 RegVT = *PhysReg.second->vt_begin();
4018
4019 // This is a explicit reference to a physical register.
4020 Regs.push_back(PhysReg.first);
4021
4022 // If this is an expanded reference, add the rest of the regs to Regs.
4023 if (NumRegs != 1) {
4024 TargetRegisterClass::iterator I = PhysReg.second->begin();
Chris Lattnerbf996f12007-04-30 17:29:31 +00004025 for (; *I != PhysReg.first; ++I)
Evan Cheng50871242008-05-14 20:07:51 +00004026 assert(I != PhysReg.second->end() && "Didn't find reg!");
Chris Lattnerbf996f12007-04-30 17:29:31 +00004027
4028 // Already added the first reg.
4029 --NumRegs; ++I;
4030 for (; NumRegs; --NumRegs, ++I) {
Evan Cheng50871242008-05-14 20:07:51 +00004031 assert(I != PhysReg.second->end() && "Ran out of registers to allocate!");
Chris Lattnerbf996f12007-04-30 17:29:31 +00004032 Regs.push_back(*I);
4033 }
4034 }
Dan Gohman23ce5022008-04-25 18:27:55 +00004035 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, RegVT, ValueVT);
Chris Lattner7cbeb242008-02-21 04:55:52 +00004036 const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
4037 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TRI);
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004038 return;
Chris Lattnerbf996f12007-04-30 17:29:31 +00004039 }
4040
4041 // Otherwise, if this was a reference to an LLVM register class, create vregs
4042 // for this reference.
4043 std::vector<unsigned> RegClassRegs;
Chris Lattnerc2c28fc2007-06-15 19:11:01 +00004044 const TargetRegisterClass *RC = PhysReg.second;
4045 if (RC) {
Chris Lattnerbf996f12007-04-30 17:29:31 +00004046 // If this is an early clobber or tied register, our regalloc doesn't know
4047 // how to maintain the constraint. If it isn't, go ahead and create vreg
4048 // and let the regalloc do the right thing.
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004049 if (!OpInfo.hasMatchingInput && !OpInfo.isEarlyClobber &&
4050 // If there is some other early clobber and this is an input register,
4051 // then we are forced to pre-allocate the input reg so it doesn't
4052 // conflict with the earlyclobber.
4053 !(OpInfo.Type == InlineAsm::isInput && HasEarlyClobber)) {
Chris Lattnerbf996f12007-04-30 17:29:31 +00004054 RegVT = *PhysReg.second->vt_begin();
4055
4056 if (OpInfo.ConstraintVT == MVT::Other)
4057 ValueVT = RegVT;
4058
4059 // Create the appropriate number of virtual registers.
Chris Lattner84bc5422007-12-31 04:13:23 +00004060 MachineRegisterInfo &RegInfo = MF.getRegInfo();
Chris Lattnerbf996f12007-04-30 17:29:31 +00004061 for (; NumRegs; --NumRegs)
Chris Lattner84bc5422007-12-31 04:13:23 +00004062 Regs.push_back(RegInfo.createVirtualRegister(PhysReg.second));
Chris Lattnerbf996f12007-04-30 17:29:31 +00004063
Dan Gohman23ce5022008-04-25 18:27:55 +00004064 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, RegVT, ValueVT);
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004065 return;
Chris Lattnerbf996f12007-04-30 17:29:31 +00004066 }
4067
4068 // Otherwise, we can't allocate it. Let the code below figure out how to
4069 // maintain these constraints.
4070 RegClassRegs.assign(PhysReg.second->begin(), PhysReg.second->end());
4071
4072 } else {
4073 // This is a reference to a register class that doesn't directly correspond
4074 // to an LLVM register class. Allocate NumRegs consecutive, available,
4075 // registers from the class.
4076 RegClassRegs = TLI.getRegClassForInlineAsmConstraint(OpInfo.ConstraintCode,
4077 OpInfo.ConstraintVT);
4078 }
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004079
Dan Gohman6f0d0242008-02-10 18:45:23 +00004080 const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
Chris Lattnerbf996f12007-04-30 17:29:31 +00004081 unsigned NumAllocated = 0;
4082 for (unsigned i = 0, e = RegClassRegs.size(); i != e; ++i) {
4083 unsigned Reg = RegClassRegs[i];
4084 // See if this register is available.
4085 if ((isOutReg && OutputRegs.count(Reg)) || // Already used.
4086 (isInReg && InputRegs.count(Reg))) { // Already used.
4087 // Make sure we find consecutive registers.
4088 NumAllocated = 0;
4089 continue;
4090 }
4091
4092 // Check to see if this register is allocatable (i.e. don't give out the
4093 // stack pointer).
Chris Lattnerc2c28fc2007-06-15 19:11:01 +00004094 if (RC == 0) {
Dan Gohman6f0d0242008-02-10 18:45:23 +00004095 RC = isAllocatableRegister(Reg, MF, TLI, TRI);
Chris Lattnerc2c28fc2007-06-15 19:11:01 +00004096 if (!RC) { // Couldn't allocate this register.
4097 // Reset NumAllocated to make sure we return consecutive registers.
4098 NumAllocated = 0;
4099 continue;
4100 }
Chris Lattnerbf996f12007-04-30 17:29:31 +00004101 }
4102
4103 // Okay, this register is good, we can use it.
4104 ++NumAllocated;
4105
4106 // If we allocated enough consecutive registers, succeed.
4107 if (NumAllocated == NumRegs) {
4108 unsigned RegStart = (i-NumAllocated)+1;
4109 unsigned RegEnd = i+1;
4110 // Mark all of the allocated registers used.
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004111 for (unsigned i = RegStart; i != RegEnd; ++i)
4112 Regs.push_back(RegClassRegs[i]);
Chris Lattnerbf996f12007-04-30 17:29:31 +00004113
Dan Gohman23ce5022008-04-25 18:27:55 +00004114 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, *RC->vt_begin(),
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004115 OpInfo.ConstraintVT);
Chris Lattner7cbeb242008-02-21 04:55:52 +00004116 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TRI);
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004117 return;
Chris Lattnerbf996f12007-04-30 17:29:31 +00004118 }
4119 }
4120
4121 // Otherwise, we couldn't allocate enough registers for this.
Chris Lattnerbf996f12007-04-30 17:29:31 +00004122}
4123
4124
Chris Lattnerce7518c2006-01-26 22:24:51 +00004125/// visitInlineAsm - Handle a call to an InlineAsm object.
4126///
Duncan Sandsfd7b3262007-12-17 18:08:19 +00004127void SelectionDAGLowering::visitInlineAsm(CallSite CS) {
4128 InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
Chris Lattnerce7518c2006-01-26 22:24:51 +00004129
Chris Lattner0c583402007-04-28 20:49:53 +00004130 /// ConstraintOperands - Information about all of the constraints.
Evan Cheng5c807602008-02-26 02:33:44 +00004131 std::vector<SDISelAsmOperandInfo> ConstraintOperands;
Chris Lattnerce7518c2006-01-26 22:24:51 +00004132
Dan Gohman475871a2008-07-27 21:46:04 +00004133 SDValue Chain = getRoot();
4134 SDValue Flag;
Chris Lattnerce7518c2006-01-26 22:24:51 +00004135
Chris Lattner4e4b5762006-02-01 18:59:47 +00004136 std::set<unsigned> OutputRegs, InputRegs;
Chris Lattner1efa40f2006-02-22 00:56:39 +00004137
Chris Lattner0c583402007-04-28 20:49:53 +00004138 // Do a prepass over the constraints, canonicalizing them, and building up the
4139 // ConstraintOperands list.
4140 std::vector<InlineAsm::ConstraintInfo>
4141 ConstraintInfos = IA->ParseConstraints();
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004142
4143 // SawEarlyClobber - Keep track of whether we saw an earlyclobber output
4144 // constraint. If so, we can't let the register allocator allocate any input
4145 // registers, because it will not know to avoid the earlyclobbered output reg.
4146 bool SawEarlyClobber = false;
4147
Duncan Sandsfd7b3262007-12-17 18:08:19 +00004148 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst.
Chris Lattneracf8b012008-04-27 23:44:28 +00004149 unsigned ResNo = 0; // ResNo - The result number of the next output.
Chris Lattner0c583402007-04-28 20:49:53 +00004150 for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) {
Evan Cheng5c807602008-02-26 02:33:44 +00004151 ConstraintOperands.push_back(SDISelAsmOperandInfo(ConstraintInfos[i]));
4152 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
Chris Lattner0c583402007-04-28 20:49:53 +00004153
Duncan Sands83ec4b62008-06-06 12:08:01 +00004154 MVT OpVT = MVT::Other;
Chris Lattner0c583402007-04-28 20:49:53 +00004155
4156 // Compute the value type for each operand.
4157 switch (OpInfo.Type) {
Chris Lattner1efa40f2006-02-22 00:56:39 +00004158 case InlineAsm::isOutput:
Chris Lattneracf8b012008-04-27 23:44:28 +00004159 // Indirect outputs just consume an argument.
4160 if (OpInfo.isIndirect) {
Duncan Sandsfd7b3262007-12-17 18:08:19 +00004161 OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
Chris Lattneracf8b012008-04-27 23:44:28 +00004162 break;
Chris Lattner1efa40f2006-02-22 00:56:39 +00004163 }
Chris Lattneracf8b012008-04-27 23:44:28 +00004164 // The return value of the call is this value. As such, there is no
4165 // corresponding argument.
4166 assert(CS.getType() != Type::VoidTy && "Bad inline asm!");
4167 if (const StructType *STy = dyn_cast<StructType>(CS.getType())) {
4168 OpVT = TLI.getValueType(STy->getElementType(ResNo));
4169 } else {
4170 assert(ResNo == 0 && "Asm only has one result!");
4171 OpVT = TLI.getValueType(CS.getType());
4172 }
4173 ++ResNo;
Chris Lattner1efa40f2006-02-22 00:56:39 +00004174 break;
4175 case InlineAsm::isInput:
Duncan Sandsfd7b3262007-12-17 18:08:19 +00004176 OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
Chris Lattner1efa40f2006-02-22 00:56:39 +00004177 break;
4178 case InlineAsm::isClobber:
Chris Lattner0c583402007-04-28 20:49:53 +00004179 // Nothing to do.
Chris Lattner1efa40f2006-02-22 00:56:39 +00004180 break;
4181 }
Chris Lattner1efa40f2006-02-22 00:56:39 +00004182
Chris Lattner0c583402007-04-28 20:49:53 +00004183 // If this is an input or an indirect output, process the call argument.
Dale Johanneseneb57ea72007-11-05 21:20:28 +00004184 // BasicBlocks are labels, currently appearing only in asm's.
Chris Lattner0c583402007-04-28 20:49:53 +00004185 if (OpInfo.CallOperandVal) {
Chris Lattner507ffd22008-04-27 00:16:18 +00004186 if (BasicBlock *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal))
4187 OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
Dale Johanneseneb57ea72007-11-05 21:20:28 +00004188 else {
4189 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
4190 const Type *OpTy = OpInfo.CallOperandVal->getType();
4191 // If this is an indirect operand, the operand is a pointer to the
4192 // accessed type.
4193 if (OpInfo.isIndirect)
4194 OpTy = cast<PointerType>(OpTy)->getElementType();
4195
Dan Gohman4fa2a3f2008-05-23 00:34:04 +00004196 // If OpTy is not a single value, it may be a struct/union that we
Dale Johanneseneb57ea72007-11-05 21:20:28 +00004197 // can tile with integers.
Dan Gohman4fa2a3f2008-05-23 00:34:04 +00004198 if (!OpTy->isSingleValueType() && OpTy->isSized()) {
Dale Johanneseneb57ea72007-11-05 21:20:28 +00004199 unsigned BitSize = TD->getTypeSizeInBits(OpTy);
4200 switch (BitSize) {
4201 default: break;
4202 case 1:
4203 case 8:
4204 case 16:
4205 case 32:
4206 case 64:
4207 OpTy = IntegerType::get(BitSize);
4208 break;
4209 }
Chris Lattner6995cf62007-04-29 18:58:03 +00004210 }
Dale Johanneseneb57ea72007-11-05 21:20:28 +00004211
4212 OpVT = TLI.getValueType(OpTy, true);
Chris Lattner0c583402007-04-28 20:49:53 +00004213 }
4214 }
4215
4216 OpInfo.ConstraintVT = OpVT;
Chris Lattner2a600be2007-04-28 21:01:43 +00004217
Chris Lattner3ff90dc2007-04-30 17:16:27 +00004218 // Compute the constraint code and ConstraintType to use.
Chris Lattner5a096902008-04-27 00:37:18 +00004219 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
Chris Lattner0c583402007-04-28 20:49:53 +00004220
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004221 // Keep track of whether we see an earlyclobber.
4222 SawEarlyClobber |= OpInfo.isEarlyClobber;
Chris Lattner09e4b7e2007-04-28 21:12:06 +00004223
Chris Lattner0fe71e92008-02-21 19:43:13 +00004224 // If we see a clobber of a register, it is an early clobber.
Chris Lattner69e6a8d2008-02-21 20:54:31 +00004225 if (!SawEarlyClobber &&
4226 OpInfo.Type == InlineAsm::isClobber &&
4227 OpInfo.ConstraintType == TargetLowering::C_Register) {
4228 // Note that we want to ignore things that we don't trick here, like
4229 // dirflag, fpsr, flags, etc.
4230 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
4231 TLI.getRegForInlineAsmConstraint(OpInfo.ConstraintCode,
4232 OpInfo.ConstraintVT);
4233 if (PhysReg.first || PhysReg.second) {
4234 // This is a register we know of.
4235 SawEarlyClobber = true;
4236 }
4237 }
Chris Lattner0fe71e92008-02-21 19:43:13 +00004238
Chris Lattner09e4b7e2007-04-28 21:12:06 +00004239 // If this is a memory input, and if the operand is not indirect, do what we
4240 // need to to provide an address for the memory input.
4241 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
4242 !OpInfo.isIndirect) {
4243 assert(OpInfo.Type == InlineAsm::isInput &&
4244 "Can only indirectify direct input operands!");
4245
4246 // Memory operands really want the address of the value. If we don't have
4247 // an indirect input, put it in the constpool if we can, otherwise spill
4248 // it to a stack slot.
4249
4250 // If the operand is a float, integer, or vector constant, spill to a
4251 // constant pool entry to get its address.
4252 Value *OpVal = OpInfo.CallOperandVal;
4253 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
4254 isa<ConstantVector>(OpVal)) {
4255 OpInfo.CallOperand = DAG.getConstantPool(cast<Constant>(OpVal),
4256 TLI.getPointerTy());
4257 } else {
4258 // Otherwise, create a stack slot and emit a store to it before the
4259 // asm.
4260 const Type *Ty = OpVal->getType();
Duncan Sands514ab342007-11-01 20:53:16 +00004261 uint64_t TySize = TLI.getTargetData()->getABITypeSize(Ty);
Chris Lattner09e4b7e2007-04-28 21:12:06 +00004262 unsigned Align = TLI.getTargetData()->getPrefTypeAlignment(Ty);
4263 MachineFunction &MF = DAG.getMachineFunction();
4264 int SSFI = MF.getFrameInfo()->CreateStackObject(TySize, Align);
Dan Gohman475871a2008-07-27 21:46:04 +00004265 SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getPointerTy());
Chris Lattner09e4b7e2007-04-28 21:12:06 +00004266 Chain = DAG.getStore(Chain, OpInfo.CallOperand, StackSlot, NULL, 0);
4267 OpInfo.CallOperand = StackSlot;
4268 }
4269
4270 // There is no longer a Value* corresponding to this operand.
4271 OpInfo.CallOperandVal = 0;
4272 // It is now an indirect operand.
4273 OpInfo.isIndirect = true;
4274 }
4275
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004276 // If this constraint is for a specific register, allocate it before
4277 // anything else.
4278 if (OpInfo.ConstraintType == TargetLowering::C_Register)
4279 GetRegistersForValue(OpInfo, SawEarlyClobber, OutputRegs, InputRegs);
Chris Lattner0c583402007-04-28 20:49:53 +00004280 }
Chris Lattner0c583402007-04-28 20:49:53 +00004281 ConstraintInfos.clear();
4282
4283
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004284 // Second pass - Loop over all of the operands, assigning virtual or physregs
4285 // to registerclass operands.
4286 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
Evan Cheng5c807602008-02-26 02:33:44 +00004287 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004288
4289 // C_Register operands have already been allocated, Other/Memory don't need
4290 // to be.
4291 if (OpInfo.ConstraintType == TargetLowering::C_RegisterClass)
4292 GetRegistersForValue(OpInfo, SawEarlyClobber, OutputRegs, InputRegs);
4293 }
4294
Chris Lattner0c583402007-04-28 20:49:53 +00004295 // AsmNodeOperands - The operands for the ISD::INLINEASM node.
Dan Gohman475871a2008-07-27 21:46:04 +00004296 std::vector<SDValue> AsmNodeOperands;
4297 AsmNodeOperands.push_back(SDValue()); // reserve space for input chain
Chris Lattner0c583402007-04-28 20:49:53 +00004298 AsmNodeOperands.push_back(
4299 DAG.getTargetExternalSymbol(IA->getAsmString().c_str(), MVT::Other));
4300
Chris Lattner2cc2f662006-02-01 01:28:23 +00004301
Chris Lattner0f0b7d42006-02-21 23:12:12 +00004302 // Loop over all of the inputs, copying the operand values into the
4303 // appropriate registers and processing the output regs.
Chris Lattner864635a2006-02-22 22:37:12 +00004304 RegsForValue RetValRegs;
Chris Lattner41f62592008-04-29 04:29:54 +00004305
Chris Lattner0c583402007-04-28 20:49:53 +00004306 // IndirectStoresToEmit - The set of stores to emit after the inline asm node.
4307 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
4308
4309 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
Evan Cheng5c807602008-02-26 02:33:44 +00004310 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
Chris Lattner1efa40f2006-02-22 00:56:39 +00004311
Chris Lattner0c583402007-04-28 20:49:53 +00004312 switch (OpInfo.Type) {
Chris Lattner2cc2f662006-02-01 01:28:23 +00004313 case InlineAsm::isOutput: {
Chris Lattnerc83994e2007-04-28 21:03:16 +00004314 if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass &&
4315 OpInfo.ConstraintType != TargetLowering::C_Register) {
Chris Lattnerf2f3cd52007-04-28 06:08:13 +00004316 // Memory output, or 'other' output (e.g. 'X' constraint).
Chris Lattner09e4b7e2007-04-28 21:12:06 +00004317 assert(OpInfo.isIndirect && "Memory output must be indirect operand");
Chris Lattner22873462006-02-27 23:45:39 +00004318
Chris Lattner22873462006-02-27 23:45:39 +00004319 // Add information to the INLINEASM node to know about this output.
4320 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
Chris Lattnerc90233b2007-05-15 01:33:58 +00004321 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
4322 TLI.getPointerTy()));
Chris Lattner09e4b7e2007-04-28 21:12:06 +00004323 AsmNodeOperands.push_back(OpInfo.CallOperand);
Chris Lattner22873462006-02-27 23:45:39 +00004324 break;
4325 }
4326
Chris Lattner2a600be2007-04-28 21:01:43 +00004327 // Otherwise, this is a register or register class output.
Chris Lattner22873462006-02-27 23:45:39 +00004328
Chris Lattner864635a2006-02-22 22:37:12 +00004329 // Copy the output from the appropriate register. Find a register that
Chris Lattner1efa40f2006-02-22 00:56:39 +00004330 // we can use.
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004331 if (OpInfo.AssignedRegs.Regs.empty()) {
Duncan Sandsa47c6c32008-06-17 03:24:13 +00004332 cerr << "Couldn't allocate output reg for constraint '"
Chris Lattner0c583402007-04-28 20:49:53 +00004333 << OpInfo.ConstraintCode << "'!\n";
Chris Lattnerd03f1582006-10-31 07:33:13 +00004334 exit(1);
4335 }
Chris Lattner1efa40f2006-02-22 00:56:39 +00004336
Chris Lattner41f62592008-04-29 04:29:54 +00004337 // If this is an indirect operand, store through the pointer after the
4338 // asm.
4339 if (OpInfo.isIndirect) {
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004340 IndirectStoresToEmit.push_back(std::make_pair(OpInfo.AssignedRegs,
Chris Lattner0c583402007-04-28 20:49:53 +00004341 OpInfo.CallOperandVal));
Chris Lattner41f62592008-04-29 04:29:54 +00004342 } else {
4343 // This is the result value of the call.
4344 assert(CS.getType() != Type::VoidTy && "Bad inline asm!");
4345 // Concatenate this output onto the outputs list.
4346 RetValRegs.append(OpInfo.AssignedRegs);
Chris Lattner2cc2f662006-02-01 01:28:23 +00004347 }
Chris Lattner6656dd12006-01-31 02:03:41 +00004348
4349 // Add information to the INLINEASM node to know that this register is
4350 // set.
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004351 OpInfo.AssignedRegs.AddInlineAsmOperands(2 /*REGDEF*/, DAG,
4352 AsmNodeOperands);
Chris Lattner6656dd12006-01-31 02:03:41 +00004353 break;
4354 }
4355 case InlineAsm::isInput: {
Dan Gohman475871a2008-07-27 21:46:04 +00004356 SDValue InOperandVal = OpInfo.CallOperand;
Chris Lattner3d81fee2006-02-04 02:16:44 +00004357
Chris Lattner0c583402007-04-28 20:49:53 +00004358 if (isdigit(OpInfo.ConstraintCode[0])) { // Matching constraint?
Chris Lattner2223aea2006-02-02 00:25:23 +00004359 // If this is required to match an output register we have already set,
4360 // just use its register.
Chris Lattner0c583402007-04-28 20:49:53 +00004361 unsigned OperandNo = atoi(OpInfo.ConstraintCode.c_str());
Chris Lattner3d81fee2006-02-04 02:16:44 +00004362
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00004363 // Scan until we find the definition we already emitted of this operand.
4364 // When we find it, create a RegsForValue operand.
4365 unsigned CurOp = 2; // The first operand.
4366 for (; OperandNo; --OperandNo) {
4367 // Advance to the next operand.
4368 unsigned NumOps =
4369 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
Chris Lattnera15cf702006-07-20 19:02:21 +00004370 assert(((NumOps & 7) == 2 /*REGDEF*/ ||
4371 (NumOps & 7) == 4 /*MEM*/) &&
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00004372 "Skipped past definitions?");
4373 CurOp += (NumOps>>3)+1;
4374 }
4375
4376 unsigned NumOps =
4377 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
Chris Lattner527fae12007-02-01 01:21:12 +00004378 if ((NumOps & 7) == 2 /*REGDEF*/) {
4379 // Add NumOps>>3 registers to MatchedRegs.
4380 RegsForValue MatchedRegs;
Dan Gohman23ce5022008-04-25 18:27:55 +00004381 MatchedRegs.TLI = &TLI;
Dan Gohman1fa850b2008-05-02 00:03:54 +00004382 MatchedRegs.ValueVTs.push_back(InOperandVal.getValueType());
4383 MatchedRegs.RegVTs.push_back(AsmNodeOperands[CurOp+1].getValueType());
Chris Lattner527fae12007-02-01 01:21:12 +00004384 for (unsigned i = 0, e = NumOps>>3; i != e; ++i) {
4385 unsigned Reg =
4386 cast<RegisterSDNode>(AsmNodeOperands[++CurOp])->getReg();
4387 MatchedRegs.Regs.push_back(Reg);
4388 }
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00004389
Chris Lattner527fae12007-02-01 01:21:12 +00004390 // Use the produced MatchedRegs object to
Dan Gohmanb6f5b002007-06-28 23:29:44 +00004391 MatchedRegs.getCopyToRegs(InOperandVal, DAG, Chain, &Flag);
Chris Lattner527fae12007-02-01 01:21:12 +00004392 MatchedRegs.AddInlineAsmOperands(1 /*REGUSE*/, DAG, AsmNodeOperands);
4393 break;
4394 } else {
4395 assert((NumOps & 7) == 4/*MEM*/ && "Unknown matching constraint!");
Chris Lattnerf9853bc2008-02-21 05:27:19 +00004396 assert((NumOps >> 3) == 1 && "Unexpected number of operands");
4397 // Add information to the INLINEASM node to know about this input.
4398 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
4399 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
4400 TLI.getPointerTy()));
4401 AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
4402 break;
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00004403 }
Chris Lattner2223aea2006-02-02 00:25:23 +00004404 }
Chris Lattner87bc3bd2006-02-24 01:11:24 +00004405
Chris Lattner2a600be2007-04-28 21:01:43 +00004406 if (OpInfo.ConstraintType == TargetLowering::C_Other) {
Chris Lattner0c583402007-04-28 20:49:53 +00004407 assert(!OpInfo.isIndirect &&
Chris Lattner44b2c502007-04-28 06:42:38 +00004408 "Don't know how to handle indirect other inputs yet!");
4409
Dan Gohman475871a2008-07-27 21:46:04 +00004410 std::vector<SDValue> Ops;
Chris Lattner48884cd2007-08-25 00:47:38 +00004411 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode[0],
4412 Ops, DAG);
4413 if (Ops.empty()) {
Bill Wendling832171c2006-12-07 20:04:42 +00004414 cerr << "Invalid operand for inline asm constraint '"
Chris Lattner0c583402007-04-28 20:49:53 +00004415 << OpInfo.ConstraintCode << "'!\n";
Chris Lattner53069fb2006-10-31 19:41:18 +00004416 exit(1);
4417 }
Chris Lattner87bc3bd2006-02-24 01:11:24 +00004418
4419 // Add information to the INLINEASM node to know about this input.
Chris Lattner48884cd2007-08-25 00:47:38 +00004420 unsigned ResOpType = 3 /*IMM*/ | (Ops.size() << 3);
Chris Lattnerc90233b2007-05-15 01:33:58 +00004421 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
4422 TLI.getPointerTy()));
Chris Lattner48884cd2007-08-25 00:47:38 +00004423 AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end());
Chris Lattner87bc3bd2006-02-24 01:11:24 +00004424 break;
Chris Lattner2a600be2007-04-28 21:01:43 +00004425 } else if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
Chris Lattner09e4b7e2007-04-28 21:12:06 +00004426 assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
Chris Lattner44b2c502007-04-28 06:42:38 +00004427 assert(InOperandVal.getValueType() == TLI.getPointerTy() &&
4428 "Memory operands expect pointer values");
4429
Chris Lattner87bc3bd2006-02-24 01:11:24 +00004430 // Add information to the INLINEASM node to know about this input.
4431 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
Chris Lattnerc90233b2007-05-15 01:33:58 +00004432 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
4433 TLI.getPointerTy()));
Chris Lattner87bc3bd2006-02-24 01:11:24 +00004434 AsmNodeOperands.push_back(InOperandVal);
4435 break;
4436 }
4437
Chris Lattner2a600be2007-04-28 21:01:43 +00004438 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
4439 OpInfo.ConstraintType == TargetLowering::C_Register) &&
4440 "Unknown constraint type!");
Chris Lattner0c583402007-04-28 20:49:53 +00004441 assert(!OpInfo.isIndirect &&
Chris Lattner44b2c502007-04-28 06:42:38 +00004442 "Don't know how to handle indirect register inputs yet!");
Chris Lattner87bc3bd2006-02-24 01:11:24 +00004443
4444 // Copy the input into the appropriate registers.
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004445 assert(!OpInfo.AssignedRegs.Regs.empty() &&
4446 "Couldn't allocate input reg!");
Chris Lattner87bc3bd2006-02-24 01:11:24 +00004447
Dan Gohmanb6f5b002007-06-28 23:29:44 +00004448 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, Chain, &Flag);
Chris Lattner87bc3bd2006-02-24 01:11:24 +00004449
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004450 OpInfo.AssignedRegs.AddInlineAsmOperands(1/*REGUSE*/, DAG,
4451 AsmNodeOperands);
Chris Lattner6656dd12006-01-31 02:03:41 +00004452 break;
4453 }
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00004454 case InlineAsm::isClobber: {
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00004455 // Add the clobbered value to the operand list, so that the register
4456 // allocator is aware that the physreg got clobbered.
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004457 if (!OpInfo.AssignedRegs.Regs.empty())
4458 OpInfo.AssignedRegs.AddInlineAsmOperands(2/*REGDEF*/, DAG,
4459 AsmNodeOperands);
Chris Lattner6656dd12006-01-31 02:03:41 +00004460 break;
4461 }
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00004462 }
Chris Lattner6656dd12006-01-31 02:03:41 +00004463 }
Chris Lattnerce7518c2006-01-26 22:24:51 +00004464
4465 // Finish up input operands.
4466 AsmNodeOperands[0] = Chain;
4467 if (Flag.Val) AsmNodeOperands.push_back(Flag);
4468
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00004469 Chain = DAG.getNode(ISD::INLINEASM,
4470 DAG.getNodeValueTypes(MVT::Other, MVT::Flag), 2,
Chris Lattnerbd564bf2006-08-08 02:23:42 +00004471 &AsmNodeOperands[0], AsmNodeOperands.size());
Chris Lattnerce7518c2006-01-26 22:24:51 +00004472 Flag = Chain.getValue(1);
4473
Chris Lattner6656dd12006-01-31 02:03:41 +00004474 // If this asm returns a register value, copy the result from that register
4475 // and set it as the value of the call.
Chris Lattner3a508c92007-04-12 06:00:20 +00004476 if (!RetValRegs.Regs.empty()) {
Dan Gohman475871a2008-07-27 21:46:04 +00004477 SDValue Val = RetValRegs.getCopyFromRegs(DAG, Chain, &Flag);
Chris Lattner3fb29682008-04-29 04:48:56 +00004478
4479 // If any of the results of the inline asm is a vector, it may have the
4480 // wrong width/num elts. This can happen for register classes that can
4481 // contain multiple different value types. The preg or vreg allocated may
4482 // not have the same VT as was expected. Convert it to the right type with
Dan Gohman7f321562007-06-25 16:23:39 +00004483 // bit_convert.
Chris Lattner3fb29682008-04-29 04:48:56 +00004484 if (const StructType *ResSTy = dyn_cast<StructType>(CS.getType())) {
4485 for (unsigned i = 0, e = ResSTy->getNumElements(); i != e; ++i) {
Duncan Sands83ec4b62008-06-06 12:08:01 +00004486 if (Val.Val->getValueType(i).isVector())
Chris Lattner3fb29682008-04-29 04:48:56 +00004487 Val = DAG.getNode(ISD::BIT_CONVERT,
4488 TLI.getValueType(ResSTy->getElementType(i)), Val);
4489 }
4490 } else {
Duncan Sands83ec4b62008-06-06 12:08:01 +00004491 if (Val.getValueType().isVector())
Chris Lattner3fb29682008-04-29 04:48:56 +00004492 Val = DAG.getNode(ISD::BIT_CONVERT, TLI.getValueType(CS.getType()),
4493 Val);
Chris Lattner3a508c92007-04-12 06:00:20 +00004494 }
Chris Lattner3fb29682008-04-29 04:48:56 +00004495
Duncan Sandsfd7b3262007-12-17 18:08:19 +00004496 setValue(CS.getInstruction(), Val);
Chris Lattner3a508c92007-04-12 06:00:20 +00004497 }
Chris Lattnerce7518c2006-01-26 22:24:51 +00004498
Dan Gohman475871a2008-07-27 21:46:04 +00004499 std::vector<std::pair<SDValue, Value*> > StoresToEmit;
Chris Lattner6656dd12006-01-31 02:03:41 +00004500
4501 // Process indirect outputs, first output all of the flagged copies out of
4502 // physregs.
4503 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
Chris Lattner864635a2006-02-22 22:37:12 +00004504 RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
Chris Lattner6656dd12006-01-31 02:03:41 +00004505 Value *Ptr = IndirectStoresToEmit[i].second;
Dan Gohman475871a2008-07-27 21:46:04 +00004506 SDValue OutVal = OutRegs.getCopyFromRegs(DAG, Chain, &Flag);
Chris Lattner864635a2006-02-22 22:37:12 +00004507 StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
Chris Lattner6656dd12006-01-31 02:03:41 +00004508 }
4509
4510 // Emit the non-flagged stores from the physregs.
Dan Gohman475871a2008-07-27 21:46:04 +00004511 SmallVector<SDValue, 8> OutChains;
Chris Lattner6656dd12006-01-31 02:03:41 +00004512 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i)
Chris Lattner0c583402007-04-28 20:49:53 +00004513 OutChains.push_back(DAG.getStore(Chain, StoresToEmit[i].first,
Chris Lattner6656dd12006-01-31 02:03:41 +00004514 getValue(StoresToEmit[i].second),
Evan Cheng8b2794a2006-10-13 21:14:26 +00004515 StoresToEmit[i].second, 0));
Chris Lattner6656dd12006-01-31 02:03:41 +00004516 if (!OutChains.empty())
Chris Lattnerbd564bf2006-08-08 02:23:42 +00004517 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
4518 &OutChains[0], OutChains.size());
Chris Lattnerce7518c2006-01-26 22:24:51 +00004519 DAG.setRoot(Chain);
4520}
4521
4522
Chris Lattner1c08c712005-01-07 07:47:53 +00004523void SelectionDAGLowering::visitMalloc(MallocInst &I) {
Dan Gohman475871a2008-07-27 21:46:04 +00004524 SDValue Src = getValue(I.getOperand(0));
Chris Lattner1c08c712005-01-07 07:47:53 +00004525
Duncan Sands83ec4b62008-06-06 12:08:01 +00004526 MVT IntPtr = TLI.getPointerTy();
Chris Lattner68cd65e2005-01-22 23:04:37 +00004527
Duncan Sands8e4eb092008-06-08 20:54:56 +00004528 if (IntPtr.bitsLT(Src.getValueType()))
Chris Lattner68cd65e2005-01-22 23:04:37 +00004529 Src = DAG.getNode(ISD::TRUNCATE, IntPtr, Src);
Duncan Sands8e4eb092008-06-08 20:54:56 +00004530 else if (IntPtr.bitsGT(Src.getValueType()))
Chris Lattner68cd65e2005-01-22 23:04:37 +00004531 Src = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, Src);
Chris Lattner1c08c712005-01-07 07:47:53 +00004532
4533 // Scale the source by the type size.
Duncan Sands514ab342007-11-01 20:53:16 +00004534 uint64_t ElementSize = TD->getABITypeSize(I.getType()->getElementType());
Chris Lattner1c08c712005-01-07 07:47:53 +00004535 Src = DAG.getNode(ISD::MUL, Src.getValueType(),
Chris Lattner0bd48932008-01-17 07:00:52 +00004536 Src, DAG.getIntPtrConstant(ElementSize));
Chris Lattner1c08c712005-01-07 07:47:53 +00004537
Reid Spencer47857812006-12-31 05:55:36 +00004538 TargetLowering::ArgListTy Args;
4539 TargetLowering::ArgListEntry Entry;
4540 Entry.Node = Src;
4541 Entry.Ty = TLI.getTargetData()->getIntPtrType();
Reid Spencer47857812006-12-31 05:55:36 +00004542 Args.push_back(Entry);
Chris Lattnercf5734d2005-01-08 19:26:18 +00004543
Dan Gohman475871a2008-07-27 21:46:04 +00004544 std::pair<SDValue,SDValue> Result =
Duncan Sands00fee652008-02-14 17:28:50 +00004545 TLI.LowerCallTo(getRoot(), I.getType(), false, false, false, CallingConv::C,
4546 true, DAG.getExternalSymbol("malloc", IntPtr), Args, DAG);
Chris Lattnercf5734d2005-01-08 19:26:18 +00004547 setValue(&I, Result.first); // Pointers always fit in registers
4548 DAG.setRoot(Result.second);
Chris Lattner1c08c712005-01-07 07:47:53 +00004549}
4550
4551void SelectionDAGLowering::visitFree(FreeInst &I) {
Reid Spencer47857812006-12-31 05:55:36 +00004552 TargetLowering::ArgListTy Args;
4553 TargetLowering::ArgListEntry Entry;
4554 Entry.Node = getValue(I.getOperand(0));
4555 Entry.Ty = TLI.getTargetData()->getIntPtrType();
Reid Spencer47857812006-12-31 05:55:36 +00004556 Args.push_back(Entry);
Duncan Sands83ec4b62008-06-06 12:08:01 +00004557 MVT IntPtr = TLI.getPointerTy();
Dan Gohman475871a2008-07-27 21:46:04 +00004558 std::pair<SDValue,SDValue> Result =
Duncan Sands00fee652008-02-14 17:28:50 +00004559 TLI.LowerCallTo(getRoot(), Type::VoidTy, false, false, false,
4560 CallingConv::C, true,
Chris Lattnercf5734d2005-01-08 19:26:18 +00004561 DAG.getExternalSymbol("free", IntPtr), Args, DAG);
4562 DAG.setRoot(Result.second);
Chris Lattner1c08c712005-01-07 07:47:53 +00004563}
4564
Evan Chengff9b3732008-01-30 18:18:23 +00004565// EmitInstrWithCustomInserter - This method should be implemented by targets
4566// that mark instructions with the 'usesCustomDAGSchedInserter' flag. These
Chris Lattner025c39b2005-08-26 20:54:47 +00004567// instructions are special in various ways, which require special support to
4568// insert. The specified MachineInstr is created but not inserted into any
4569// basic blocks, and the scheduler passes ownership of it to this method.
Evan Chengff9b3732008-01-30 18:18:23 +00004570MachineBasicBlock *TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
Chris Lattner025c39b2005-08-26 20:54:47 +00004571 MachineBasicBlock *MBB) {
Bill Wendling832171c2006-12-07 20:04:42 +00004572 cerr << "If a target marks an instruction with "
4573 << "'usesCustomDAGSchedInserter', it must implement "
Evan Chengff9b3732008-01-30 18:18:23 +00004574 << "TargetLowering::EmitInstrWithCustomInserter!\n";
Chris Lattner025c39b2005-08-26 20:54:47 +00004575 abort();
4576 return 0;
4577}
4578
Chris Lattner39ae3622005-01-09 00:00:49 +00004579void SelectionDAGLowering::visitVAStart(CallInst &I) {
Nate Begemanacc398c2006-01-25 18:21:52 +00004580 DAG.setRoot(DAG.getNode(ISD::VASTART, MVT::Other, getRoot(),
4581 getValue(I.getOperand(1)),
4582 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner39ae3622005-01-09 00:00:49 +00004583}
4584
4585void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
Dan Gohman475871a2008-07-27 21:46:04 +00004586 SDValue V = DAG.getVAArg(TLI.getValueType(I.getType()), getRoot(),
Nate Begemanacc398c2006-01-25 18:21:52 +00004587 getValue(I.getOperand(0)),
4588 DAG.getSrcValue(I.getOperand(0)));
4589 setValue(&I, V);
4590 DAG.setRoot(V.getValue(1));
Chris Lattner1c08c712005-01-07 07:47:53 +00004591}
4592
4593void SelectionDAGLowering::visitVAEnd(CallInst &I) {
Nate Begemanacc398c2006-01-25 18:21:52 +00004594 DAG.setRoot(DAG.getNode(ISD::VAEND, MVT::Other, getRoot(),
4595 getValue(I.getOperand(1)),
4596 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner1c08c712005-01-07 07:47:53 +00004597}
4598
4599void SelectionDAGLowering::visitVACopy(CallInst &I) {
Nate Begemanacc398c2006-01-25 18:21:52 +00004600 DAG.setRoot(DAG.getNode(ISD::VACOPY, MVT::Other, getRoot(),
4601 getValue(I.getOperand(1)),
4602 getValue(I.getOperand(2)),
4603 DAG.getSrcValue(I.getOperand(1)),
4604 DAG.getSrcValue(I.getOperand(2))));
Chris Lattner1c08c712005-01-07 07:47:53 +00004605}
4606
Chris Lattnerfdfded52006-04-12 16:20:43 +00004607/// TargetLowering::LowerArguments - This is the default LowerArguments
4608/// implementation, which just inserts a FORMAL_ARGUMENTS node. FIXME: When all
Chris Lattnerf4ec8172006-05-16 22:53:20 +00004609/// targets are migrated to using FORMAL_ARGUMENTS, this hook should be
4610/// integrated into SDISel.
Dan Gohmana44b6742008-06-30 20:31:15 +00004611void TargetLowering::LowerArguments(Function &F, SelectionDAG &DAG,
Dan Gohman475871a2008-07-27 21:46:04 +00004612 SmallVectorImpl<SDValue> &ArgValues) {
Chris Lattnerfdfded52006-04-12 16:20:43 +00004613 // Add CC# and isVararg as operands to the FORMAL_ARGUMENTS node.
Dan Gohman475871a2008-07-27 21:46:04 +00004614 SmallVector<SDValue, 3+16> Ops;
Chris Lattner8c0c10c2006-05-16 06:45:34 +00004615 Ops.push_back(DAG.getRoot());
Chris Lattnerfdfded52006-04-12 16:20:43 +00004616 Ops.push_back(DAG.getConstant(F.getCallingConv(), getPointerTy()));
4617 Ops.push_back(DAG.getConstant(F.isVarArg(), getPointerTy()));
4618
4619 // Add one result value for each formal argument.
Dan Gohmana44b6742008-06-30 20:31:15 +00004620 SmallVector<MVT, 16> RetVals;
Anton Korobeynikov6aa279d2007-01-28 18:01:49 +00004621 unsigned j = 1;
Anton Korobeynikovac2b2cf2007-01-28 16:04:40 +00004622 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end();
4623 I != E; ++I, ++j) {
Dan Gohmanf5025cf2008-06-09 21:19:23 +00004624 SmallVector<MVT, 4> ValueVTs;
4625 ComputeValueVTs(*this, I->getType(), ValueVTs);
4626 for (unsigned Value = 0, NumValues = ValueVTs.size();
4627 Value != NumValues; ++Value) {
4628 MVT VT = ValueVTs[Value];
4629 const Type *ArgTy = VT.getTypeForMVT();
4630 ISD::ArgFlagsTy Flags;
4631 unsigned OriginalAlignment =
4632 getTargetData()->getABITypeAlignment(ArgTy);
Lauro Ramos Venancio7aa47b62007-02-13 13:50:08 +00004633
Dan Gohmanf5025cf2008-06-09 21:19:23 +00004634 if (F.paramHasAttr(j, ParamAttr::ZExt))
4635 Flags.setZExt();
4636 if (F.paramHasAttr(j, ParamAttr::SExt))
4637 Flags.setSExt();
4638 if (F.paramHasAttr(j, ParamAttr::InReg))
4639 Flags.setInReg();
4640 if (F.paramHasAttr(j, ParamAttr::StructRet))
4641 Flags.setSRet();
4642 if (F.paramHasAttr(j, ParamAttr::ByVal)) {
4643 Flags.setByVal();
4644 const PointerType *Ty = cast<PointerType>(I->getType());
4645 const Type *ElementTy = Ty->getElementType();
4646 unsigned FrameAlign = getByValTypeAlignment(ElementTy);
4647 unsigned FrameSize = getTargetData()->getABITypeSize(ElementTy);
4648 // For ByVal, alignment should be passed from FE. BE will guess if
4649 // this info is not there but there are cases it cannot get right.
4650 if (F.getParamAlignment(j))
4651 FrameAlign = F.getParamAlignment(j);
4652 Flags.setByValAlign(FrameAlign);
4653 Flags.setByValSize(FrameSize);
4654 }
4655 if (F.paramHasAttr(j, ParamAttr::Nest))
4656 Flags.setNest();
4657 Flags.setOrigAlign(OriginalAlignment);
Duncan Sandsb988bac2008-02-11 20:58:28 +00004658
Dan Gohmanf5025cf2008-06-09 21:19:23 +00004659 MVT RegisterVT = getRegisterType(VT);
4660 unsigned NumRegs = getNumRegisters(VT);
4661 for (unsigned i = 0; i != NumRegs; ++i) {
4662 RetVals.push_back(RegisterVT);
4663 ISD::ArgFlagsTy MyFlags = Flags;
4664 if (NumRegs > 1 && i == 0)
4665 MyFlags.setSplit();
4666 // if it isn't first piece, alignment must be 1
4667 else if (i > 0)
4668 MyFlags.setOrigAlign(1);
4669 Ops.push_back(DAG.getArgFlags(MyFlags));
4670 }
Dan Gohmanb6f5b002007-06-28 23:29:44 +00004671 }
Chris Lattnerfdfded52006-04-12 16:20:43 +00004672 }
Evan Cheng3b0d2862006-04-25 23:03:35 +00004673
Chris Lattner8c0c10c2006-05-16 06:45:34 +00004674 RetVals.push_back(MVT::Other);
Chris Lattnerfdfded52006-04-12 16:20:43 +00004675
4676 // Create the node.
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00004677 SDNode *Result = DAG.getNode(ISD::FORMAL_ARGUMENTS,
Chris Lattner86ca3ca2008-02-13 07:39:09 +00004678 DAG.getVTList(&RetVals[0], RetVals.size()),
Chris Lattnerbd564bf2006-08-08 02:23:42 +00004679 &Ops[0], Ops.size()).Val;
Chris Lattner86ca3ca2008-02-13 07:39:09 +00004680
4681 // Prelower FORMAL_ARGUMENTS. This isn't required for functionality, but
4682 // allows exposing the loads that may be part of the argument access to the
4683 // first DAGCombiner pass.
Dan Gohman475871a2008-07-27 21:46:04 +00004684 SDValue TmpRes = LowerOperation(SDValue(Result, 0), DAG);
Chris Lattner86ca3ca2008-02-13 07:39:09 +00004685
4686 // The number of results should match up, except that the lowered one may have
4687 // an extra flag result.
4688 assert((Result->getNumValues() == TmpRes.Val->getNumValues() ||
4689 (Result->getNumValues()+1 == TmpRes.Val->getNumValues() &&
4690 TmpRes.getValue(Result->getNumValues()).getValueType() == MVT::Flag))
4691 && "Lowering produced unexpected number of results!");
Dan Gohman2dbc1672008-07-21 21:04:07 +00004692
4693 // The FORMAL_ARGUMENTS node itself is likely no longer needed.
4694 if (Result != TmpRes.Val && Result->use_empty()) {
4695 HandleSDNode Dummy(DAG.getRoot());
4696 DAG.RemoveDeadNode(Result);
4697 }
4698
Chris Lattner86ca3ca2008-02-13 07:39:09 +00004699 Result = TmpRes.Val;
4700
Dan Gohman27a70be2007-07-02 16:18:06 +00004701 unsigned NumArgRegs = Result->getNumValues() - 1;
Dan Gohman475871a2008-07-27 21:46:04 +00004702 DAG.setRoot(SDValue(Result, NumArgRegs));
Chris Lattnerfdfded52006-04-12 16:20:43 +00004703
4704 // Set up the return result vector.
Chris Lattnerfdfded52006-04-12 16:20:43 +00004705 unsigned i = 0;
Reid Spencer47857812006-12-31 05:55:36 +00004706 unsigned Idx = 1;
4707 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E;
4708 ++I, ++Idx) {
Dan Gohmanf5025cf2008-06-09 21:19:23 +00004709 SmallVector<MVT, 4> ValueVTs;
4710 ComputeValueVTs(*this, I->getType(), ValueVTs);
4711 for (unsigned Value = 0, NumValues = ValueVTs.size();
4712 Value != NumValues; ++Value) {
4713 MVT VT = ValueVTs[Value];
4714 MVT PartVT = getRegisterType(VT);
Duncan Sandsb988bac2008-02-11 20:58:28 +00004715
Dan Gohmanf5025cf2008-06-09 21:19:23 +00004716 unsigned NumParts = getNumRegisters(VT);
Dan Gohman475871a2008-07-27 21:46:04 +00004717 SmallVector<SDValue, 4> Parts(NumParts);
Dan Gohmanf5025cf2008-06-09 21:19:23 +00004718 for (unsigned j = 0; j != NumParts; ++j)
Dan Gohman475871a2008-07-27 21:46:04 +00004719 Parts[j] = SDValue(Result, i++);
Duncan Sandsb988bac2008-02-11 20:58:28 +00004720
Dan Gohmanf5025cf2008-06-09 21:19:23 +00004721 ISD::NodeType AssertOp = ISD::DELETED_NODE;
4722 if (F.paramHasAttr(Idx, ParamAttr::SExt))
4723 AssertOp = ISD::AssertSext;
4724 else if (F.paramHasAttr(Idx, ParamAttr::ZExt))
4725 AssertOp = ISD::AssertZext;
Duncan Sandsb988bac2008-02-11 20:58:28 +00004726
Dan Gohmana44b6742008-06-30 20:31:15 +00004727 ArgValues.push_back(getCopyFromParts(DAG, &Parts[0], NumParts, PartVT, VT,
4728 AssertOp));
Dan Gohmanf5025cf2008-06-09 21:19:23 +00004729 }
Chris Lattnerfdfded52006-04-12 16:20:43 +00004730 }
Dan Gohman27a70be2007-07-02 16:18:06 +00004731 assert(i == NumArgRegs && "Argument register count mismatch!");
Chris Lattnerfdfded52006-04-12 16:20:43 +00004732}
4733
Chris Lattnerf4ec8172006-05-16 22:53:20 +00004734
4735/// TargetLowering::LowerCallTo - This is the default LowerCallTo
4736/// implementation, which just inserts an ISD::CALL node, which is later custom
4737/// lowered by the target to something concrete. FIXME: When all targets are
4738/// migrated to using ISD::CALL, this hook should be integrated into SDISel.
Dan Gohman475871a2008-07-27 21:46:04 +00004739std::pair<SDValue, SDValue>
4740TargetLowering::LowerCallTo(SDValue Chain, const Type *RetTy,
Duncan Sands00fee652008-02-14 17:28:50 +00004741 bool RetSExt, bool RetZExt, bool isVarArg,
4742 unsigned CallingConv, bool isTailCall,
Dan Gohman475871a2008-07-27 21:46:04 +00004743 SDValue Callee,
Chris Lattnerf4ec8172006-05-16 22:53:20 +00004744 ArgListTy &Args, SelectionDAG &DAG) {
Dan Gohman475871a2008-07-27 21:46:04 +00004745 SmallVector<SDValue, 32> Ops;
Chris Lattnerf4ec8172006-05-16 22:53:20 +00004746 Ops.push_back(Chain); // Op#0 - Chain
4747 Ops.push_back(DAG.getConstant(CallingConv, getPointerTy())); // Op#1 - CC
4748 Ops.push_back(DAG.getConstant(isVarArg, getPointerTy())); // Op#2 - VarArg
4749 Ops.push_back(DAG.getConstant(isTailCall, getPointerTy())); // Op#3 - Tail
4750 Ops.push_back(Callee);
4751
4752 // Handle all of the outgoing arguments.
4753 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
Dan Gohmanf5025cf2008-06-09 21:19:23 +00004754 SmallVector<MVT, 4> ValueVTs;
4755 ComputeValueVTs(*this, Args[i].Ty, ValueVTs);
4756 for (unsigned Value = 0, NumValues = ValueVTs.size();
4757 Value != NumValues; ++Value) {
4758 MVT VT = ValueVTs[Value];
4759 const Type *ArgTy = VT.getTypeForMVT();
Dan Gohman475871a2008-07-27 21:46:04 +00004760 SDValue Op = SDValue(Args[i].Node.Val, Args[i].Node.ResNo + Value);
Dan Gohmanf5025cf2008-06-09 21:19:23 +00004761 ISD::ArgFlagsTy Flags;
4762 unsigned OriginalAlignment =
4763 getTargetData()->getABITypeAlignment(ArgTy);
Duncan Sands276dcbd2008-03-21 09:14:45 +00004764
Dan Gohmanf5025cf2008-06-09 21:19:23 +00004765 if (Args[i].isZExt)
4766 Flags.setZExt();
4767 if (Args[i].isSExt)
4768 Flags.setSExt();
4769 if (Args[i].isInReg)
4770 Flags.setInReg();
4771 if (Args[i].isSRet)
4772 Flags.setSRet();
4773 if (Args[i].isByVal) {
4774 Flags.setByVal();
4775 const PointerType *Ty = cast<PointerType>(Args[i].Ty);
4776 const Type *ElementTy = Ty->getElementType();
4777 unsigned FrameAlign = getByValTypeAlignment(ElementTy);
4778 unsigned FrameSize = getTargetData()->getABITypeSize(ElementTy);
4779 // For ByVal, alignment should come from FE. BE will guess if this
4780 // info is not there but there are cases it cannot get right.
4781 if (Args[i].Alignment)
4782 FrameAlign = Args[i].Alignment;
4783 Flags.setByValAlign(FrameAlign);
4784 Flags.setByValSize(FrameSize);
4785 }
4786 if (Args[i].isNest)
4787 Flags.setNest();
4788 Flags.setOrigAlign(OriginalAlignment);
Dan Gohman27a70be2007-07-02 16:18:06 +00004789
Dan Gohmanf5025cf2008-06-09 21:19:23 +00004790 MVT PartVT = getRegisterType(VT);
4791 unsigned NumParts = getNumRegisters(VT);
Dan Gohman475871a2008-07-27 21:46:04 +00004792 SmallVector<SDValue, 4> Parts(NumParts);
Dan Gohmanf5025cf2008-06-09 21:19:23 +00004793 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
Duncan Sandsb988bac2008-02-11 20:58:28 +00004794
Dan Gohmanf5025cf2008-06-09 21:19:23 +00004795 if (Args[i].isSExt)
4796 ExtendKind = ISD::SIGN_EXTEND;
4797 else if (Args[i].isZExt)
4798 ExtendKind = ISD::ZERO_EXTEND;
Duncan Sandsb988bac2008-02-11 20:58:28 +00004799
Dan Gohmanf5025cf2008-06-09 21:19:23 +00004800 getCopyToParts(DAG, Op, &Parts[0], NumParts, PartVT, ExtendKind);
Duncan Sandsb988bac2008-02-11 20:58:28 +00004801
Dan Gohmanf5025cf2008-06-09 21:19:23 +00004802 for (unsigned i = 0; i != NumParts; ++i) {
4803 // if it isn't first piece, alignment must be 1
4804 ISD::ArgFlagsTy MyFlags = Flags;
4805 if (NumParts > 1 && i == 0)
4806 MyFlags.setSplit();
4807 else if (i != 0)
4808 MyFlags.setOrigAlign(1);
Duncan Sandsb988bac2008-02-11 20:58:28 +00004809
Dan Gohmanf5025cf2008-06-09 21:19:23 +00004810 Ops.push_back(Parts[i]);
4811 Ops.push_back(DAG.getArgFlags(MyFlags));
4812 }
Dan Gohman27a70be2007-07-02 16:18:06 +00004813 }
Chris Lattnerf4ec8172006-05-16 22:53:20 +00004814 }
4815
Dan Gohmanef5d1942008-03-11 21:11:25 +00004816 // Figure out the result value types. We start by making a list of
Dan Gohman23ce5022008-04-25 18:27:55 +00004817 // the potentially illegal return value types.
Duncan Sands83ec4b62008-06-06 12:08:01 +00004818 SmallVector<MVT, 4> LoweredRetTys;
4819 SmallVector<MVT, 4> RetTys;
Dan Gohman23ce5022008-04-25 18:27:55 +00004820 ComputeValueVTs(*this, RetTy, RetTys);
Dan Gohmanef5d1942008-03-11 21:11:25 +00004821
Dan Gohman23ce5022008-04-25 18:27:55 +00004822 // Then we translate that to a list of legal types.
4823 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
Duncan Sands83ec4b62008-06-06 12:08:01 +00004824 MVT VT = RetTys[I];
4825 MVT RegisterVT = getRegisterType(VT);
Dan Gohmanef5d1942008-03-11 21:11:25 +00004826 unsigned NumRegs = getNumRegisters(VT);
4827 for (unsigned i = 0; i != NumRegs; ++i)
4828 LoweredRetTys.push_back(RegisterVT);
4829 }
Chris Lattnerf4ec8172006-05-16 22:53:20 +00004830
Dan Gohmanef5d1942008-03-11 21:11:25 +00004831 LoweredRetTys.push_back(MVT::Other); // Always has a chain.
Chris Lattnerf4ec8172006-05-16 22:53:20 +00004832
Dan Gohmanb6f5b002007-06-28 23:29:44 +00004833 // Create the CALL node.
Dan Gohman475871a2008-07-27 21:46:04 +00004834 SDValue Res = DAG.getNode(ISD::CALL,
Dan Gohmanef5d1942008-03-11 21:11:25 +00004835 DAG.getVTList(&LoweredRetTys[0],
4836 LoweredRetTys.size()),
Chris Lattnerbe384162006-08-16 22:57:46 +00004837 &Ops[0], Ops.size());
Dan Gohmanef5d1942008-03-11 21:11:25 +00004838 Chain = Res.getValue(LoweredRetTys.size() - 1);
Dan Gohmanb6f5b002007-06-28 23:29:44 +00004839
4840 // Gather up the call result into a single value.
4841 if (RetTy != Type::VoidTy) {
Duncan Sands00fee652008-02-14 17:28:50 +00004842 ISD::NodeType AssertOp = ISD::DELETED_NODE;
4843
4844 if (RetSExt)
4845 AssertOp = ISD::AssertSext;
4846 else if (RetZExt)
Dan Gohmanb6f5b002007-06-28 23:29:44 +00004847 AssertOp = ISD::AssertZext;
Duncan Sands00fee652008-02-14 17:28:50 +00004848
Dan Gohman475871a2008-07-27 21:46:04 +00004849 SmallVector<SDValue, 4> ReturnValues;
Dan Gohmanef5d1942008-03-11 21:11:25 +00004850 unsigned RegNo = 0;
Dan Gohman23ce5022008-04-25 18:27:55 +00004851 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
Duncan Sands83ec4b62008-06-06 12:08:01 +00004852 MVT VT = RetTys[I];
4853 MVT RegisterVT = getRegisterType(VT);
Dan Gohmanef5d1942008-03-11 21:11:25 +00004854 unsigned NumRegs = getNumRegisters(VT);
4855 unsigned RegNoEnd = NumRegs + RegNo;
Dan Gohman475871a2008-07-27 21:46:04 +00004856 SmallVector<SDValue, 4> Results;
Dan Gohmanef5d1942008-03-11 21:11:25 +00004857 for (; RegNo != RegNoEnd; ++RegNo)
4858 Results.push_back(Res.getValue(RegNo));
Dan Gohman475871a2008-07-27 21:46:04 +00004859 SDValue ReturnValue =
Dan Gohmanef5d1942008-03-11 21:11:25 +00004860 getCopyFromParts(DAG, &Results[0], NumRegs, RegisterVT, VT,
4861 AssertOp);
4862 ReturnValues.push_back(ReturnValue);
4863 }
Duncan Sandsf9516202008-06-30 10:19:09 +00004864 Res = DAG.getMergeValues(DAG.getVTList(&RetTys[0], RetTys.size()),
4865 &ReturnValues[0], ReturnValues.size());
Chris Lattnerf4ec8172006-05-16 22:53:20 +00004866 }
Dan Gohmanb6f5b002007-06-28 23:29:44 +00004867
4868 return std::make_pair(Res, Chain);
Chris Lattnerf4ec8172006-05-16 22:53:20 +00004869}
4870
Dan Gohman475871a2008-07-27 21:46:04 +00004871SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) {
Chris Lattner171453a2005-01-16 07:28:41 +00004872 assert(0 && "LowerOperation not implemented for this target!");
4873 abort();
Dan Gohman475871a2008-07-27 21:46:04 +00004874 return SDValue();
Chris Lattner171453a2005-01-16 07:28:41 +00004875}
4876
Nate Begeman0aed7842006-01-28 03:14:31 +00004877
Chris Lattner7041ee32005-01-11 05:56:49 +00004878//===----------------------------------------------------------------------===//
4879// SelectionDAGISel code
4880//===----------------------------------------------------------------------===//
Chris Lattner1c08c712005-01-07 07:47:53 +00004881
Duncan Sands83ec4b62008-06-06 12:08:01 +00004882unsigned SelectionDAGISel::MakeReg(MVT VT) {
Chris Lattner84bc5422007-12-31 04:13:23 +00004883 return RegInfo->createVirtualRegister(TLI.getRegClassFor(VT));
Chris Lattner1c08c712005-01-07 07:47:53 +00004884}
4885
Chris Lattner495a0b52005-08-17 06:37:43 +00004886void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const {
Jim Laskeyc7c3f112006-10-16 20:52:31 +00004887 AU.addRequired<AliasAnalysis>();
Gordon Henriksen5eca0752008-08-17 18:44:35 +00004888 AU.addRequired<GCModuleInfo>();
Chris Lattnerc8d288f2007-03-31 04:18:03 +00004889 AU.setPreservesAll();
Chris Lattner495a0b52005-08-17 06:37:43 +00004890}
Chris Lattner1c08c712005-01-07 07:47:53 +00004891
Chris Lattner1c08c712005-01-07 07:47:53 +00004892bool SelectionDAGISel::runOnFunction(Function &Fn) {
Dan Gohman5f43f922007-08-27 16:26:13 +00004893 // Get alias analysis for load/store combining.
4894 AA = &getAnalysis<AliasAnalysis>();
4895
Chris Lattner1c08c712005-01-07 07:47:53 +00004896 MachineFunction &MF = MachineFunction::construct(&Fn, TLI.getTargetMachine());
Gordon Henriksen5eca0752008-08-17 18:44:35 +00004897 if (MF.getFunction()->hasGC())
4898 GFI = &getAnalysis<GCModuleInfo>().getFunctionInfo(*MF.getFunction());
Gordon Henriksence224772008-01-07 01:30:38 +00004899 else
Gordon Henriksen5eca0752008-08-17 18:44:35 +00004900 GFI = 0;
Chris Lattner84bc5422007-12-31 04:13:23 +00004901 RegInfo = &MF.getRegInfo();
Bill Wendling832171c2006-12-07 20:04:42 +00004902 DOUT << "\n\n\n=== " << Fn.getName() << "\n";
Chris Lattner1c08c712005-01-07 07:47:53 +00004903
4904 FunctionLoweringInfo FuncInfo(TLI, Fn, MF);
4905
Dale Johannesen1532f3d2008-04-02 00:25:04 +00004906 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
4907 if (InvokeInst *Invoke = dyn_cast<InvokeInst>(I->getTerminator()))
4908 // Mark landing pad.
4909 FuncInfo.MBBMap[Invoke->getSuccessor(1)]->setIsLandingPad();
Duncan Sands9fac0b52007-06-06 10:05:18 +00004910
Dan Gohman0e5f1302008-07-07 23:02:41 +00004911 SelectAllBasicBlocks(Fn, MF, FuncInfo);
Misha Brukmanedf128a2005-04-21 22:36:52 +00004912
Evan Chengad2070c2007-02-10 02:43:39 +00004913 // Add function live-ins to entry block live-in set.
4914 BasicBlock *EntryBB = &Fn.getEntryBlock();
4915 BB = FuncInfo.MBBMap[EntryBB];
Chris Lattner84bc5422007-12-31 04:13:23 +00004916 if (!RegInfo->livein_empty())
4917 for (MachineRegisterInfo::livein_iterator I = RegInfo->livein_begin(),
4918 E = RegInfo->livein_end(); I != E; ++I)
Evan Chengad2070c2007-02-10 02:43:39 +00004919 BB->addLiveIn(I->first);
4920
Duncan Sandsf4070822007-06-15 19:04:19 +00004921#ifndef NDEBUG
4922 assert(FuncInfo.CatchInfoFound.size() == FuncInfo.CatchInfoLost.size() &&
4923 "Not all catch info was assigned to a landing pad!");
4924#endif
4925
Chris Lattner1c08c712005-01-07 07:47:53 +00004926 return true;
4927}
4928
Chris Lattner6833b062008-04-28 07:16:35 +00004929void SelectionDAGLowering::CopyValueToVirtualRegister(Value *V, unsigned Reg) {
Dan Gohman475871a2008-07-27 21:46:04 +00004930 SDValue Op = getValue(V);
Chris Lattner18c2f132005-01-13 20:50:02 +00004931 assert((Op.getOpcode() != ISD::CopyFromReg ||
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00004932 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
Chris Lattner18c2f132005-01-13 20:50:02 +00004933 "Copy from a reg to the same reg!");
Dan Gohman86e1ebf2008-03-27 19:56:19 +00004934 assert(!TargetRegisterInfo::isPhysicalRegister(Reg) && "Is a physreg");
Dan Gohmanb6f5b002007-06-28 23:29:44 +00004935
Dan Gohman23ce5022008-04-25 18:27:55 +00004936 RegsForValue RFV(TLI, Reg, V->getType());
Dan Gohman475871a2008-07-27 21:46:04 +00004937 SDValue Chain = DAG.getEntryNode();
Dan Gohman23ce5022008-04-25 18:27:55 +00004938 RFV.getCopyToRegs(Op, DAG, Chain, 0);
4939 PendingExports.push_back(Chain);
Chris Lattner1c08c712005-01-07 07:47:53 +00004940}
4941
Chris Lattner068a81e2005-01-17 17:15:02 +00004942void SelectionDAGISel::
Dan Gohman86e1ebf2008-03-27 19:56:19 +00004943LowerArguments(BasicBlock *LLVMBB, SelectionDAGLowering &SDL) {
Chris Lattner068a81e2005-01-17 17:15:02 +00004944 // If this is the entry block, emit arguments.
Evan Cheng15699fc2007-02-10 01:08:18 +00004945 Function &F = *LLVMBB->getParent();
Chris Lattner0afa8e32005-01-17 17:55:19 +00004946 FunctionLoweringInfo &FuncInfo = SDL.FuncInfo;
Dan Gohman475871a2008-07-27 21:46:04 +00004947 SDValue OldRoot = SDL.DAG.getRoot();
4948 SmallVector<SDValue, 16> Args;
Dan Gohmana44b6742008-06-30 20:31:15 +00004949 TLI.LowerArguments(F, SDL.DAG, Args);
Chris Lattner068a81e2005-01-17 17:15:02 +00004950
Chris Lattnerbf209482005-10-30 19:42:35 +00004951 unsigned a = 0;
4952 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
Dan Gohmanf5025cf2008-06-09 21:19:23 +00004953 AI != E; ++AI) {
4954 SmallVector<MVT, 4> ValueVTs;
4955 ComputeValueVTs(TLI, AI->getType(), ValueVTs);
4956 unsigned NumValues = ValueVTs.size();
Chris Lattnerbf209482005-10-30 19:42:35 +00004957 if (!AI->use_empty()) {
Duncan Sands4bdcb612008-07-02 17:40:58 +00004958 SDL.setValue(AI, SDL.DAG.getMergeValues(&Args[a], NumValues));
Chris Lattnerbf209482005-10-30 19:42:35 +00004959 // If this argument is live outside of the entry block, insert a copy from
4960 // whereever we got it to the vreg that other BB's will reference it as.
Chris Lattner251db182007-02-25 18:40:32 +00004961 DenseMap<const Value*, unsigned>::iterator VMI=FuncInfo.ValueMap.find(AI);
4962 if (VMI != FuncInfo.ValueMap.end()) {
Dan Gohman86e1ebf2008-03-27 19:56:19 +00004963 SDL.CopyValueToVirtualRegister(AI, VMI->second);
Chris Lattnerbf209482005-10-30 19:42:35 +00004964 }
Chris Lattner0afa8e32005-01-17 17:55:19 +00004965 }
Dan Gohmanf5025cf2008-06-09 21:19:23 +00004966 a += NumValues;
4967 }
Chris Lattnerbf209482005-10-30 19:42:35 +00004968
Chris Lattnerbf209482005-10-30 19:42:35 +00004969 // Finally, if the target has anything special to do, allow it to do so.
Chris Lattner96645412006-05-16 06:10:58 +00004970 // FIXME: this should insert code into the DAG!
Chris Lattnerbf209482005-10-30 19:42:35 +00004971 EmitFunctionEntryCode(F, SDL.DAG.getMachineFunction());
Chris Lattner068a81e2005-01-17 17:15:02 +00004972}
4973
Duncan Sandsf4070822007-06-15 19:04:19 +00004974static void copyCatchInfo(BasicBlock *SrcBB, BasicBlock *DestBB,
4975 MachineModuleInfo *MMI, FunctionLoweringInfo &FLI) {
Duncan Sandsf4070822007-06-15 19:04:19 +00004976 for (BasicBlock::iterator I = SrcBB->begin(), E = --SrcBB->end(); I != E; ++I)
Duncan Sandscf26d7c2007-07-04 20:52:51 +00004977 if (isSelector(I)) {
Duncan Sandsf4070822007-06-15 19:04:19 +00004978 // Apply the catch info to DestBB.
4979 addCatchInfo(cast<CallInst>(*I), MMI, FLI.MBBMap[DestBB]);
4980#ifndef NDEBUG
Duncan Sands560a7372007-11-15 09:54:37 +00004981 if (!FLI.MBBMap[SrcBB]->isLandingPad())
4982 FLI.CatchInfoFound.insert(I);
Duncan Sandsf4070822007-06-15 19:04:19 +00004983#endif
4984 }
4985}
4986
Arnold Schwaighofer30e62c02008-04-30 09:16:33 +00004987/// IsFixedFrameObjectWithPosOffset - Check if object is a fixed frame object and
4988/// whether object offset >= 0.
4989static bool
Dan Gohman475871a2008-07-27 21:46:04 +00004990IsFixedFrameObjectWithPosOffset(MachineFrameInfo * MFI, SDValue Op) {
Arnold Schwaighofer30e62c02008-04-30 09:16:33 +00004991 if (!isa<FrameIndexSDNode>(Op)) return false;
4992
4993 FrameIndexSDNode * FrameIdxNode = dyn_cast<FrameIndexSDNode>(Op);
4994 int FrameIdx = FrameIdxNode->getIndex();
4995 return MFI->isFixedObjectIndex(FrameIdx) &&
4996 MFI->getObjectOffset(FrameIdx) >= 0;
4997}
4998
4999/// IsPossiblyOverwrittenArgumentOfTailCall - Check if the operand could
5000/// possibly be overwritten when lowering the outgoing arguments in a tail
5001/// call. Currently the implementation of this call is very conservative and
5002/// assumes all arguments sourcing from FORMAL_ARGUMENTS or a CopyFromReg with
5003/// virtual registers would be overwritten by direct lowering.
Dan Gohman475871a2008-07-27 21:46:04 +00005004static bool IsPossiblyOverwrittenArgumentOfTailCall(SDValue Op,
Arnold Schwaighofer30e62c02008-04-30 09:16:33 +00005005 MachineFrameInfo * MFI) {
5006 RegisterSDNode * OpReg = NULL;
5007 if (Op.getOpcode() == ISD::FORMAL_ARGUMENTS ||
5008 (Op.getOpcode()== ISD::CopyFromReg &&
5009 (OpReg = dyn_cast<RegisterSDNode>(Op.getOperand(1))) &&
5010 (OpReg->getReg() >= TargetRegisterInfo::FirstVirtualRegister)) ||
5011 (Op.getOpcode() == ISD::LOAD &&
5012 IsFixedFrameObjectWithPosOffset(MFI, Op.getOperand(1))) ||
5013 (Op.getOpcode() == ISD::MERGE_VALUES &&
5014 Op.getOperand(Op.ResNo).getOpcode() == ISD::LOAD &&
5015 IsFixedFrameObjectWithPosOffset(MFI, Op.getOperand(Op.ResNo).
5016 getOperand(1))))
5017 return true;
5018 return false;
5019}
5020
Arnold Schwaighoferc85e1712007-10-11 19:40:01 +00005021/// CheckDAGForTailCallsAndFixThem - This Function looks for CALL nodes in the
Arnold Schwaighofer48abc5c2007-10-12 21:30:57 +00005022/// DAG and fixes their tailcall attribute operand.
Arnold Schwaighoferc85e1712007-10-11 19:40:01 +00005023static void CheckDAGForTailCallsAndFixThem(SelectionDAG &DAG,
5024 TargetLowering& TLI) {
5025 SDNode * Ret = NULL;
Dan Gohman475871a2008-07-27 21:46:04 +00005026 SDValue Terminator = DAG.getRoot();
Arnold Schwaighoferc85e1712007-10-11 19:40:01 +00005027
5028 // Find RET node.
5029 if (Terminator.getOpcode() == ISD::RET) {
5030 Ret = Terminator.Val;
5031 }
5032
5033 // Fix tail call attribute of CALL nodes.
5034 for (SelectionDAG::allnodes_iterator BE = DAG.allnodes_begin(),
Dan Gohman0e5f1302008-07-07 23:02:41 +00005035 BI = DAG.allnodes_end(); BI != BE; ) {
5036 --BI;
Arnold Schwaighoferc85e1712007-10-11 19:40:01 +00005037 if (BI->getOpcode() == ISD::CALL) {
Dan Gohman475871a2008-07-27 21:46:04 +00005038 SDValue OpRet(Ret, 0);
5039 SDValue OpCall(BI, 0);
Arnold Schwaighoferc85e1712007-10-11 19:40:01 +00005040 bool isMarkedTailCall =
5041 cast<ConstantSDNode>(OpCall.getOperand(3))->getValue() != 0;
5042 // If CALL node has tail call attribute set to true and the call is not
5043 // eligible (no RET or the target rejects) the attribute is fixed to
Arnold Schwaighofer48abc5c2007-10-12 21:30:57 +00005044 // false. The TargetLowering::IsEligibleForTailCallOptimization function
Arnold Schwaighoferc85e1712007-10-11 19:40:01 +00005045 // must correctly identify tail call optimizable calls.
Arnold Schwaighofer30e62c02008-04-30 09:16:33 +00005046 if (!isMarkedTailCall) continue;
5047 if (Ret==NULL ||
5048 !TLI.IsEligibleForTailCallOptimization(OpCall, OpRet, DAG)) {
5049 // Not eligible. Mark CALL node as non tail call.
Dan Gohman475871a2008-07-27 21:46:04 +00005050 SmallVector<SDValue, 32> Ops;
Arnold Schwaighoferc85e1712007-10-11 19:40:01 +00005051 unsigned idx=0;
Arnold Schwaighofer30e62c02008-04-30 09:16:33 +00005052 for(SDNode::op_iterator I =OpCall.Val->op_begin(),
5053 E = OpCall.Val->op_end(); I != E; I++, idx++) {
Arnold Schwaighoferc85e1712007-10-11 19:40:01 +00005054 if (idx!=3)
5055 Ops.push_back(*I);
Arnold Schwaighofer30e62c02008-04-30 09:16:33 +00005056 else
Arnold Schwaighoferc85e1712007-10-11 19:40:01 +00005057 Ops.push_back(DAG.getConstant(false, TLI.getPointerTy()));
5058 }
5059 DAG.UpdateNodeOperands(OpCall, Ops.begin(), Ops.size());
Arnold Schwaighofer30e62c02008-04-30 09:16:33 +00005060 } else {
5061 // Look for tail call clobbered arguments. Emit a series of
5062 // copyto/copyfrom virtual register nodes to protect them.
Dan Gohman475871a2008-07-27 21:46:04 +00005063 SmallVector<SDValue, 32> Ops;
5064 SDValue Chain = OpCall.getOperand(0), InFlag;
Arnold Schwaighofer30e62c02008-04-30 09:16:33 +00005065 unsigned idx=0;
5066 for(SDNode::op_iterator I = OpCall.Val->op_begin(),
5067 E = OpCall.Val->op_end(); I != E; I++, idx++) {
Dan Gohman475871a2008-07-27 21:46:04 +00005068 SDValue Arg = *I;
Arnold Schwaighofer30e62c02008-04-30 09:16:33 +00005069 if (idx > 4 && (idx % 2)) {
5070 bool isByVal = cast<ARG_FLAGSSDNode>(OpCall.getOperand(idx+1))->
5071 getArgFlags().isByVal();
5072 MachineFunction &MF = DAG.getMachineFunction();
5073 MachineFrameInfo *MFI = MF.getFrameInfo();
5074 if (!isByVal &&
5075 IsPossiblyOverwrittenArgumentOfTailCall(Arg, MFI)) {
Duncan Sands83ec4b62008-06-06 12:08:01 +00005076 MVT VT = Arg.getValueType();
Arnold Schwaighofer30e62c02008-04-30 09:16:33 +00005077 unsigned VReg = MF.getRegInfo().
5078 createVirtualRegister(TLI.getRegClassFor(VT));
5079 Chain = DAG.getCopyToReg(Chain, VReg, Arg, InFlag);
5080 InFlag = Chain.getValue(1);
5081 Arg = DAG.getCopyFromReg(Chain, VReg, VT, InFlag);
5082 Chain = Arg.getValue(1);
5083 InFlag = Arg.getValue(2);
5084 }
5085 }
5086 Ops.push_back(Arg);
5087 }
5088 // Link in chain of CopyTo/CopyFromReg.
5089 Ops[0] = Chain;
5090 DAG.UpdateNodeOperands(OpCall, Ops.begin(), Ops.size());
Arnold Schwaighoferc85e1712007-10-11 19:40:01 +00005091 }
5092 }
5093 }
5094}
5095
Chris Lattner1c08c712005-01-07 07:47:53 +00005096void SelectionDAGISel::BuildSelectionDAG(SelectionDAG &DAG, BasicBlock *LLVMBB,
5097 std::vector<std::pair<MachineInstr*, unsigned> > &PHINodesToUpdate,
Nate Begemanf15485a2006-03-27 01:32:24 +00005098 FunctionLoweringInfo &FuncInfo) {
Gordon Henriksen5eca0752008-08-17 18:44:35 +00005099 SelectionDAGLowering SDL(DAG, TLI, *AA, FuncInfo, GFI);
Dan Gohman78eca172008-08-19 22:33:34 +00005100 BB = FuncInfo.MBBMap[LLVMBB];
5101
5102 // Before doing SelectionDAG ISel, see if FastISel has been requested.
5103 // FastISel doesn't currently support entry blocks, because that
5104 // requires special handling for arguments. And it doesn't support EH
5105 // landing pads, which also require special handling.
5106 // For now, also exclude blocks with terminators that aren't
5107 // unconditional branches.
Dan Gohman3e697cf2008-08-20 00:47:54 +00005108 BasicBlock::iterator Begin = LLVMBB->begin();
Dan Gohman78eca172008-08-19 22:33:34 +00005109 if (EnableFastISel &&
5110 LLVMBB != &LLVMBB->getParent()->getEntryBlock() &&
5111 !BB->isLandingPad() &&
5112 isa<BranchInst>(LLVMBB->getTerminator()) &&
5113 cast<BranchInst>(LLVMBB->getTerminator())->isUnconditional()) {
Dan Gohmanbb466332008-08-20 21:05:57 +00005114 if (FastISel *F = TLI.createFastISel(FuncInfo.MF)) {
5115 Begin = F->SelectInstructions(Begin, LLVMBB->end(),
5116 FuncInfo.ValueMap, BB);
Dan Gohmancc8430f2008-08-20 00:56:17 +00005117
5118 // Clean up the FastISel object. TODO: Reorganize what data is
5119 // stored in the FastISel class itself and what is merely passed
5120 // to the SelectInstructions method, and then move the creation
5121 // and deletion of the FastISel object up so that it is only
5122 // done once per MachineFunction.
5123 delete F;
5124
Dan Gohman3e697cf2008-08-20 00:47:54 +00005125 if (Begin == LLVMBB->end())
Dan Gohman78eca172008-08-19 22:33:34 +00005126 // The "fast" selector selected the entire block, so we're done.
5127 return;
5128
Dan Gohman3e697cf2008-08-20 00:47:54 +00005129 if (!DisableFastISelAbort) {
5130 // The "fast" selector couldn't handle something and bailed.
5131 // For the purpose of debugging, just abort.
Dan Gohman23858522008-08-20 20:47:32 +00005132#ifndef NDEBUG
5133 Begin->dump();
5134#endif
Dan Gohman3e697cf2008-08-20 00:47:54 +00005135 assert(0 && "FastISel didn't select the entire block");
5136 abort();
5137 }
Dan Gohman78eca172008-08-19 22:33:34 +00005138 }
5139 }
Chris Lattnerddb870b2005-01-13 17:59:43 +00005140
Chris Lattnerbf209482005-10-30 19:42:35 +00005141 // Lower any arguments needed in this block if this is the entry block.
Dan Gohmanecb7a772007-03-22 16:38:57 +00005142 if (LLVMBB == &LLVMBB->getParent()->getEntryBlock())
Dan Gohman86e1ebf2008-03-27 19:56:19 +00005143 LowerArguments(LLVMBB, SDL);
Chris Lattner1c08c712005-01-07 07:47:53 +00005144
Chris Lattner1c08c712005-01-07 07:47:53 +00005145 SDL.setCurrentBasicBlock(BB);
5146
Duncan Sandsf4070822007-06-15 19:04:19 +00005147 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Duncan Sands9fac0b52007-06-06 10:05:18 +00005148
Dale Johannesen1532f3d2008-04-02 00:25:04 +00005149 if (MMI && BB->isLandingPad()) {
Duncan Sandsf4070822007-06-15 19:04:19 +00005150 // Add a label to mark the beginning of the landing pad. Deletion of the
5151 // landing pad can thus be detected via the MachineModuleInfo.
5152 unsigned LabelID = MMI->addLandingPad(BB);
Dan Gohman44066042008-07-01 00:05:16 +00005153 DAG.setRoot(DAG.getLabel(ISD::EH_LABEL, DAG.getEntryNode(), LabelID));
Duncan Sandsf4070822007-06-15 19:04:19 +00005154
Evan Chenge47c3332007-06-27 18:45:32 +00005155 // Mark exception register as live in.
5156 unsigned Reg = TLI.getExceptionAddressRegister();
5157 if (Reg) BB->addLiveIn(Reg);
5158
5159 // Mark exception selector register as live in.
5160 Reg = TLI.getExceptionSelectorRegister();
5161 if (Reg) BB->addLiveIn(Reg);
5162
Duncan Sandsf4070822007-06-15 19:04:19 +00005163 // FIXME: Hack around an exception handling flaw (PR1508): the personality
5164 // function and list of typeids logically belong to the invoke (or, if you
5165 // like, the basic block containing the invoke), and need to be associated
5166 // with it in the dwarf exception handling tables. Currently however the
Duncan Sandscf26d7c2007-07-04 20:52:51 +00005167 // information is provided by an intrinsic (eh.selector) that can be moved
5168 // to unexpected places by the optimizers: if the unwind edge is critical,
5169 // then breaking it can result in the intrinsics being in the successor of
5170 // the landing pad, not the landing pad itself. This results in exceptions
5171 // not being caught because no typeids are associated with the invoke.
5172 // This may not be the only way things can go wrong, but it is the only way
5173 // we try to work around for the moment.
Duncan Sandsf4070822007-06-15 19:04:19 +00005174 BranchInst *Br = dyn_cast<BranchInst>(LLVMBB->getTerminator());
5175
5176 if (Br && Br->isUnconditional()) { // Critical edge?
5177 BasicBlock::iterator I, E;
5178 for (I = LLVMBB->begin(), E = --LLVMBB->end(); I != E; ++I)
Duncan Sandscf26d7c2007-07-04 20:52:51 +00005179 if (isSelector(I))
Duncan Sandsf4070822007-06-15 19:04:19 +00005180 break;
5181
5182 if (I == E)
5183 // No catch info found - try to extract some from the successor.
5184 copyCatchInfo(Br->getSuccessor(0), LLVMBB, MMI, FuncInfo);
Duncan Sands9fac0b52007-06-06 10:05:18 +00005185 }
5186 }
5187
Chris Lattner1c08c712005-01-07 07:47:53 +00005188 // Lower all of the non-terminator instructions.
Dan Gohman3e697cf2008-08-20 00:47:54 +00005189 for (BasicBlock::iterator I = Begin, E = --LLVMBB->end();
Chris Lattner1c08c712005-01-07 07:47:53 +00005190 I != E; ++I)
5191 SDL.visit(*I);
Duncan Sandsf19f6bb2007-06-13 05:51:31 +00005192
Chris Lattner1c08c712005-01-07 07:47:53 +00005193 // Ensure that all instructions which are used outside of their defining
Duncan Sandsf19f6bb2007-06-13 05:51:31 +00005194 // blocks are available as virtual registers. Invoke is handled elsewhere.
Dan Gohman3e697cf2008-08-20 00:47:54 +00005195 for (BasicBlock::iterator I = Begin, E = LLVMBB->end(); I != E;++I)
Duncan Sandsf19f6bb2007-06-13 05:51:31 +00005196 if (!I->use_empty() && !isa<PHINode>(I) && !isa<InvokeInst>(I)) {
Chris Lattner9f24ad72007-02-04 01:35:11 +00005197 DenseMap<const Value*, unsigned>::iterator VMI =FuncInfo.ValueMap.find(I);
Chris Lattner1c08c712005-01-07 07:47:53 +00005198 if (VMI != FuncInfo.ValueMap.end())
Dan Gohman86e1ebf2008-03-27 19:56:19 +00005199 SDL.CopyValueToVirtualRegister(I, VMI->second);
Chris Lattner1c08c712005-01-07 07:47:53 +00005200 }
5201
5202 // Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
5203 // ensure constants are generated when needed. Remember the virtual registers
5204 // that need to be added to the Machine PHI nodes as input. We cannot just
5205 // directly add them, because expansion might result in multiple MBB's for one
5206 // BB. As such, the start of the BB might correspond to a different MBB than
5207 // the end.
Misha Brukmanedf128a2005-04-21 22:36:52 +00005208 //
Chris Lattner8c494ab2006-10-27 23:50:33 +00005209 TerminatorInst *TI = LLVMBB->getTerminator();
Chris Lattner1c08c712005-01-07 07:47:53 +00005210
5211 // Emit constants only once even if used by multiple PHI nodes.
5212 std::map<Constant*, unsigned> ConstantsOut;
Chris Lattnerd5e93c02006-09-07 01:59:34 +00005213
Dan Gohmanc53ec492008-08-20 14:58:41 +00005214 BitVector SuccsHandled;
Chris Lattner8c494ab2006-10-27 23:50:33 +00005215 if (TI->getNumSuccessors())
5216 SuccsHandled.resize(BB->getParent()->getNumBlockIDs());
5217
Dan Gohman532dc2e2007-07-09 20:59:04 +00005218 // Check successor nodes' PHI nodes that expect a constant to be available
5219 // from this block.
Chris Lattner1c08c712005-01-07 07:47:53 +00005220 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
5221 BasicBlock *SuccBB = TI->getSuccessor(succ);
Chris Lattnerd5e93c02006-09-07 01:59:34 +00005222 if (!isa<PHINode>(SuccBB->begin())) continue;
Chris Lattner8c494ab2006-10-27 23:50:33 +00005223 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
Chris Lattnerd5e93c02006-09-07 01:59:34 +00005224
Chris Lattner8c494ab2006-10-27 23:50:33 +00005225 // If this terminator has multiple identical successors (common for
5226 // switches), only handle each succ once.
5227 unsigned SuccMBBNo = SuccMBB->getNumber();
5228 if (SuccsHandled[SuccMBBNo]) continue;
5229 SuccsHandled[SuccMBBNo] = true;
5230
5231 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
Chris Lattner1c08c712005-01-07 07:47:53 +00005232 PHINode *PN;
5233
5234 // At this point we know that there is a 1-1 correspondence between LLVM PHI
5235 // nodes and Machine PHI nodes, but the incoming operands have not been
5236 // emitted yet.
5237 for (BasicBlock::iterator I = SuccBB->begin();
Chris Lattner8c494ab2006-10-27 23:50:33 +00005238 (PN = dyn_cast<PHINode>(I)); ++I) {
5239 // Ignore dead phi's.
5240 if (PN->use_empty()) continue;
5241
5242 unsigned Reg;
5243 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
Chris Lattner3f7927c2006-11-29 01:12:32 +00005244
Chris Lattner8c494ab2006-10-27 23:50:33 +00005245 if (Constant *C = dyn_cast<Constant>(PHIOp)) {
5246 unsigned &RegOut = ConstantsOut[C];
5247 if (RegOut == 0) {
5248 RegOut = FuncInfo.CreateRegForValue(C);
Dan Gohman86e1ebf2008-03-27 19:56:19 +00005249 SDL.CopyValueToVirtualRegister(C, RegOut);
Chris Lattner1c08c712005-01-07 07:47:53 +00005250 }
Chris Lattner8c494ab2006-10-27 23:50:33 +00005251 Reg = RegOut;
5252 } else {
5253 Reg = FuncInfo.ValueMap[PHIOp];
5254 if (Reg == 0) {
5255 assert(isa<AllocaInst>(PHIOp) &&
5256 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
5257 "Didn't codegen value into a register!??");
5258 Reg = FuncInfo.CreateRegForValue(PHIOp);
Dan Gohman86e1ebf2008-03-27 19:56:19 +00005259 SDL.CopyValueToVirtualRegister(PHIOp, Reg);
Chris Lattner7e021512006-03-31 02:12:18 +00005260 }
Chris Lattner1c08c712005-01-07 07:47:53 +00005261 }
Chris Lattner8c494ab2006-10-27 23:50:33 +00005262
5263 // Remember that this register needs to added to the machine PHI node as
5264 // the input for this MBB.
Dan Gohman6f498b02008-08-04 23:42:46 +00005265 SmallVector<MVT, 4> ValueVTs;
5266 ComputeValueVTs(TLI, PN->getType(), ValueVTs);
5267 for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
5268 MVT VT = ValueVTs[vti];
5269 unsigned NumRegisters = TLI.getNumRegisters(VT);
5270 for (unsigned i = 0, e = NumRegisters; i != e; ++i)
5271 PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
5272 Reg += NumRegisters;
5273 }
Chris Lattner8c494ab2006-10-27 23:50:33 +00005274 }
Chris Lattner1c08c712005-01-07 07:47:53 +00005275 }
5276 ConstantsOut.clear();
5277
5278 // Lower the terminator after the copies are emitted.
Duncan Sandsf19f6bb2007-06-13 05:51:31 +00005279 SDL.visit(*LLVMBB->getTerminator());
Chris Lattnera651cf62005-01-17 19:43:36 +00005280
Nate Begemanf15485a2006-03-27 01:32:24 +00005281 // Copy over any CaseBlock records that may now exist due to SwitchInst
Nate Begeman37efe672006-04-22 18:53:45 +00005282 // lowering, as well as any jump table information.
Nate Begemanf15485a2006-03-27 01:32:24 +00005283 SwitchCases.clear();
5284 SwitchCases = SDL.SwitchCases;
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00005285 JTCases.clear();
5286 JTCases = SDL.JTCases;
Anton Korobeynikov4198c582007-04-09 12:31:58 +00005287 BitTestCases.clear();
5288 BitTestCases = SDL.BitTestCases;
5289
Chris Lattnera651cf62005-01-17 19:43:36 +00005290 // Make sure the root of the DAG is up-to-date.
Dan Gohman86e1ebf2008-03-27 19:56:19 +00005291 DAG.setRoot(SDL.getControlRoot());
Arnold Schwaighoferc85e1712007-10-11 19:40:01 +00005292
5293 // Check whether calls in this block are real tail calls. Fix up CALL nodes
5294 // with correct tailcall attribute so that the target can rely on the tailcall
5295 // attribute indicating whether the call is really eligible for tail call
5296 // optimization.
5297 CheckDAGForTailCallsAndFixThem(DAG, TLI);
Chris Lattner1c08c712005-01-07 07:47:53 +00005298}
5299
Chris Lattneread0d882008-06-17 06:09:18 +00005300void SelectionDAGISel::ComputeLiveOutVRegInfo(SelectionDAG &DAG) {
5301 SmallPtrSet<SDNode*, 128> VisitedNodes;
5302 SmallVector<SDNode*, 128> Worklist;
5303
5304 Worklist.push_back(DAG.getRoot().Val);
5305
5306 APInt Mask;
5307 APInt KnownZero;
5308 APInt KnownOne;
5309
5310 while (!Worklist.empty()) {
5311 SDNode *N = Worklist.back();
5312 Worklist.pop_back();
5313
5314 // If we've already seen this node, ignore it.
5315 if (!VisitedNodes.insert(N))
5316 continue;
5317
5318 // Otherwise, add all chain operands to the worklist.
5319 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
5320 if (N->getOperand(i).getValueType() == MVT::Other)
5321 Worklist.push_back(N->getOperand(i).Val);
5322
5323 // If this is a CopyToReg with a vreg dest, process it.
5324 if (N->getOpcode() != ISD::CopyToReg)
5325 continue;
5326
5327 unsigned DestReg = cast<RegisterSDNode>(N->getOperand(1))->getReg();
5328 if (!TargetRegisterInfo::isVirtualRegister(DestReg))
5329 continue;
5330
5331 // Ignore non-scalar or non-integer values.
Dan Gohman475871a2008-07-27 21:46:04 +00005332 SDValue Src = N->getOperand(2);
Chris Lattneread0d882008-06-17 06:09:18 +00005333 MVT SrcVT = Src.getValueType();
5334 if (!SrcVT.isInteger() || SrcVT.isVector())
5335 continue;
5336
5337 unsigned NumSignBits = DAG.ComputeNumSignBits(Src);
5338 Mask = APInt::getAllOnesValue(SrcVT.getSizeInBits());
5339 DAG.ComputeMaskedBits(Src, Mask, KnownZero, KnownOne);
5340
5341 // Only install this information if it tells us something.
5342 if (NumSignBits != 1 || KnownZero != 0 || KnownOne != 0) {
5343 DestReg -= TargetRegisterInfo::FirstVirtualRegister;
5344 FunctionLoweringInfo &FLI = DAG.getFunctionLoweringInfo();
5345 if (DestReg >= FLI.LiveOutRegInfo.size())
5346 FLI.LiveOutRegInfo.resize(DestReg+1);
5347 FunctionLoweringInfo::LiveOutInfo &LOI = FLI.LiveOutRegInfo[DestReg];
5348 LOI.NumSignBits = NumSignBits;
5349 LOI.KnownOne = NumSignBits;
5350 LOI.KnownZero = NumSignBits;
5351 }
5352 }
5353}
5354
Nate Begemanf15485a2006-03-27 01:32:24 +00005355void SelectionDAGISel::CodeGenAndEmitDAG(SelectionDAG &DAG) {
Dan Gohman462dc7f2008-07-21 20:00:07 +00005356 std::string GroupName;
5357 if (TimePassesIsEnabled)
5358 GroupName = "Instruction Selection and Scheduling";
5359 std::string BlockName;
5360 if (ViewDAGCombine1 || ViewLegalizeTypesDAGs || ViewLegalizeDAGs ||
5361 ViewDAGCombine2 || ViewISelDAGs || ViewSchedDAGs || ViewSUnitDAGs)
5362 BlockName = DAG.getMachineFunction().getFunction()->getName() + ':' +
5363 BB->getBasicBlock()->getName();
5364
5365 DOUT << "Initial selection DAG:\n";
Dan Gohman417e11b2007-10-08 15:12:17 +00005366 DEBUG(DAG.dump());
Dan Gohman462dc7f2008-07-21 20:00:07 +00005367
5368 if (ViewDAGCombine1) DAG.viewGraph("dag-combine1 input for " + BlockName);
Dan Gohman417e11b2007-10-08 15:12:17 +00005369
Chris Lattneraf21d552005-10-10 16:47:10 +00005370 // Run the DAG combiner in pre-legalize mode.
Evan Chengebffb662008-07-01 17:59:20 +00005371 if (TimePassesIsEnabled) {
Dan Gohman5e843682008-07-14 18:19:29 +00005372 NamedRegionTimer T("DAG Combining 1", GroupName);
Dan Gohmana2676512008-08-20 16:30:28 +00005373 DAG.Combine(false, *AA, Fast);
Evan Chengebffb662008-07-01 17:59:20 +00005374 } else {
Dan Gohmana2676512008-08-20 16:30:28 +00005375 DAG.Combine(false, *AA, Fast);
Evan Chengebffb662008-07-01 17:59:20 +00005376 }
Nate Begeman2300f552005-09-07 00:15:36 +00005377
Dan Gohman417e11b2007-10-08 15:12:17 +00005378 DOUT << "Optimized lowered selection DAG:\n";
Chris Lattner1c08c712005-01-07 07:47:53 +00005379 DEBUG(DAG.dump());
Duncan Sandsf00e74f2008-07-17 17:06:03 +00005380
Chris Lattner1c08c712005-01-07 07:47:53 +00005381 // Second step, hack on the DAG until it only uses operations and types that
5382 // the target supports.
Duncan Sandsf00e74f2008-07-17 17:06:03 +00005383 if (EnableLegalizeTypes) {// Enable this some day.
Dan Gohman462dc7f2008-07-21 20:00:07 +00005384 if (ViewLegalizeTypesDAGs) DAG.viewGraph("legalize-types input for " +
5385 BlockName);
5386
5387 if (TimePassesIsEnabled) {
5388 NamedRegionTimer T("Type Legalization", GroupName);
5389 DAG.LegalizeTypes();
5390 } else {
5391 DAG.LegalizeTypes();
5392 }
5393
5394 DOUT << "Type-legalized selection DAG:\n";
5395 DEBUG(DAG.dump());
5396
Chris Lattner70587ea2008-07-10 23:37:50 +00005397 // TODO: enable a dag combine pass here.
5398 }
Duncan Sandsf00e74f2008-07-17 17:06:03 +00005399
Dan Gohman462dc7f2008-07-21 20:00:07 +00005400 if (ViewLegalizeDAGs) DAG.viewGraph("legalize input for " + BlockName);
5401
Evan Chengebffb662008-07-01 17:59:20 +00005402 if (TimePassesIsEnabled) {
Dan Gohman5e843682008-07-14 18:19:29 +00005403 NamedRegionTimer T("DAG Legalization", GroupName);
Evan Chengebffb662008-07-01 17:59:20 +00005404 DAG.Legalize();
5405 } else {
5406 DAG.Legalize();
5407 }
Nate Begemanf15485a2006-03-27 01:32:24 +00005408
Bill Wendling832171c2006-12-07 20:04:42 +00005409 DOUT << "Legalized selection DAG:\n";
Chris Lattner1c08c712005-01-07 07:47:53 +00005410 DEBUG(DAG.dump());
Nate Begemanf15485a2006-03-27 01:32:24 +00005411
Dan Gohman462dc7f2008-07-21 20:00:07 +00005412 if (ViewDAGCombine2) DAG.viewGraph("dag-combine2 input for " + BlockName);
5413
Chris Lattneraf21d552005-10-10 16:47:10 +00005414 // Run the DAG combiner in post-legalize mode.
Evan Chengebffb662008-07-01 17:59:20 +00005415 if (TimePassesIsEnabled) {
Dan Gohman5e843682008-07-14 18:19:29 +00005416 NamedRegionTimer T("DAG Combining 2", GroupName);
Dan Gohmana2676512008-08-20 16:30:28 +00005417 DAG.Combine(true, *AA, Fast);
Evan Chengebffb662008-07-01 17:59:20 +00005418 } else {
Dan Gohmana2676512008-08-20 16:30:28 +00005419 DAG.Combine(true, *AA, Fast);
Evan Chengebffb662008-07-01 17:59:20 +00005420 }
Nate Begeman2300f552005-09-07 00:15:36 +00005421
Dan Gohman417e11b2007-10-08 15:12:17 +00005422 DOUT << "Optimized legalized selection DAG:\n";
5423 DEBUG(DAG.dump());
5424
Dan Gohman462dc7f2008-07-21 20:00:07 +00005425 if (ViewISelDAGs) DAG.viewGraph("isel input for " + BlockName);
Chris Lattneread0d882008-06-17 06:09:18 +00005426
Dan Gohman925a7e82008-08-13 19:47:40 +00005427 if (!Fast && EnableValueProp)
Chris Lattneread0d882008-06-17 06:09:18 +00005428 ComputeLiveOutVRegInfo(DAG);
Evan Cheng552c4a82006-04-28 02:09:19 +00005429
Chris Lattnera33ef482005-03-30 01:10:47 +00005430 // Third, instruction select all of the operations to machine code, adding the
5431 // code to the MachineBasicBlock.
Evan Chengebffb662008-07-01 17:59:20 +00005432 if (TimePassesIsEnabled) {
Dan Gohman5e843682008-07-14 18:19:29 +00005433 NamedRegionTimer T("Instruction Selection", GroupName);
Evan Chengebffb662008-07-01 17:59:20 +00005434 InstructionSelect(DAG);
5435 } else {
5436 InstructionSelect(DAG);
5437 }
Evan Chengdb8d56b2008-06-30 20:45:06 +00005438
Dan Gohman462dc7f2008-07-21 20:00:07 +00005439 DOUT << "Selected selection DAG:\n";
5440 DEBUG(DAG.dump());
5441
5442 if (ViewSchedDAGs) DAG.viewGraph("scheduler input for " + BlockName);
5443
Dan Gohman5e843682008-07-14 18:19:29 +00005444 // Schedule machine code.
5445 ScheduleDAG *Scheduler;
5446 if (TimePassesIsEnabled) {
5447 NamedRegionTimer T("Instruction Scheduling", GroupName);
5448 Scheduler = Schedule(DAG);
5449 } else {
5450 Scheduler = Schedule(DAG);
5451 }
5452
Dan Gohman462dc7f2008-07-21 20:00:07 +00005453 if (ViewSUnitDAGs) Scheduler->viewGraph();
5454
Evan Chengdb8d56b2008-06-30 20:45:06 +00005455 // Emit machine code to BB. This can change 'BB' to the last block being
5456 // inserted into.
Evan Chengebffb662008-07-01 17:59:20 +00005457 if (TimePassesIsEnabled) {
Dan Gohman5e843682008-07-14 18:19:29 +00005458 NamedRegionTimer T("Instruction Creation", GroupName);
5459 BB = Scheduler->EmitSchedule();
Evan Chengebffb662008-07-01 17:59:20 +00005460 } else {
Dan Gohman5e843682008-07-14 18:19:29 +00005461 BB = Scheduler->EmitSchedule();
5462 }
5463
5464 // Free the scheduler state.
5465 if (TimePassesIsEnabled) {
5466 NamedRegionTimer T("Instruction Scheduling Cleanup", GroupName);
5467 delete Scheduler;
5468 } else {
5469 delete Scheduler;
Evan Chengebffb662008-07-01 17:59:20 +00005470 }
Evan Chengdb8d56b2008-06-30 20:45:06 +00005471
5472 // Perform target specific isel post processing.
Evan Chengebffb662008-07-01 17:59:20 +00005473 if (TimePassesIsEnabled) {
Dan Gohman5e843682008-07-14 18:19:29 +00005474 NamedRegionTimer T("Instruction Selection Post Processing", GroupName);
Dan Gohman462dc7f2008-07-21 20:00:07 +00005475 InstructionSelectPostProcessing();
Evan Chengebffb662008-07-01 17:59:20 +00005476 } else {
Dan Gohman462dc7f2008-07-21 20:00:07 +00005477 InstructionSelectPostProcessing();
Evan Chengebffb662008-07-01 17:59:20 +00005478 }
Nate Begemanf15485a2006-03-27 01:32:24 +00005479
Bill Wendling832171c2006-12-07 20:04:42 +00005480 DOUT << "Selected machine code:\n";
Chris Lattner1c08c712005-01-07 07:47:53 +00005481 DEBUG(BB->dump());
Nate Begemanf15485a2006-03-27 01:32:24 +00005482}
Chris Lattner1c08c712005-01-07 07:47:53 +00005483
Dan Gohman0e5f1302008-07-07 23:02:41 +00005484void SelectionDAGISel::SelectAllBasicBlocks(Function &Fn, MachineFunction &MF,
5485 FunctionLoweringInfo &FuncInfo) {
Dan Gohmanfed90b62008-07-28 21:51:04 +00005486 // Define NodeAllocator here so that memory allocation is reused for
Dan Gohman0e5f1302008-07-07 23:02:41 +00005487 // each basic block.
Dan Gohmanfed90b62008-07-28 21:51:04 +00005488 NodeAllocatorType NodeAllocator;
Dan Gohman0e5f1302008-07-07 23:02:41 +00005489
Evan Cheng39fd6e82008-08-07 00:43:25 +00005490 std::vector<std::pair<MachineInstr*, unsigned> > PHINodesToUpdate;
5491 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I) {
5492 BasicBlock *LLVMBB = &*I;
5493 PHINodesToUpdate.clear();
Evan Cheng381cb072008-08-08 07:27:28 +00005494
Evan Chengd4207892008-08-20 17:50:32 +00005495 SelectBasicBlock(LLVMBB, MF, FuncInfo, PHINodesToUpdate, NodeAllocator);
Evan Cheng39fd6e82008-08-07 00:43:25 +00005496 FinishBasicBlock(LLVMBB, MF, FuncInfo, PHINodesToUpdate, NodeAllocator);
5497 }
Dan Gohman0e5f1302008-07-07 23:02:41 +00005498}
5499
Dan Gohmanfed90b62008-07-28 21:51:04 +00005500void
5501SelectionDAGISel::SelectBasicBlock(BasicBlock *LLVMBB, MachineFunction &MF,
5502 FunctionLoweringInfo &FuncInfo,
Evan Cheng39fd6e82008-08-07 00:43:25 +00005503 std::vector<std::pair<MachineInstr*, unsigned> > &PHINodesToUpdate,
Dan Gohmanfed90b62008-07-28 21:51:04 +00005504 NodeAllocatorType &NodeAllocator) {
Evan Cheng39fd6e82008-08-07 00:43:25 +00005505 SelectionDAG DAG(TLI, MF, FuncInfo,
5506 getAnalysisToUpdate<MachineModuleInfo>(),
5507 NodeAllocator);
5508 CurDAG = &DAG;
Nate Begemanf15485a2006-03-27 01:32:24 +00005509
Evan Cheng39fd6e82008-08-07 00:43:25 +00005510 // First step, lower LLVM code to some DAG. This DAG may use operations and
5511 // types that are not supported by the target.
5512 BuildSelectionDAG(DAG, LLVMBB, PHINodesToUpdate, FuncInfo);
Nate Begemanf15485a2006-03-27 01:32:24 +00005513
Evan Cheng39fd6e82008-08-07 00:43:25 +00005514 // Second step, emit the lowered DAG as machine code.
5515 CodeGenAndEmitDAG(DAG);
5516}
Anton Korobeynikov4198c582007-04-09 12:31:58 +00005517
Evan Cheng39fd6e82008-08-07 00:43:25 +00005518void
5519SelectionDAGISel::FinishBasicBlock(BasicBlock *LLVMBB, MachineFunction &MF,
5520 FunctionLoweringInfo &FuncInfo,
5521 std::vector<std::pair<MachineInstr*, unsigned> > &PHINodesToUpdate,
5522 NodeAllocatorType &NodeAllocator) {
Anton Korobeynikov4198c582007-04-09 12:31:58 +00005523 DOUT << "Total amount of phi nodes to update: "
5524 << PHINodesToUpdate.size() << "\n";
5525 DEBUG(for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i)
5526 DOUT << "Node " << i << " : (" << PHINodesToUpdate[i].first
5527 << ", " << PHINodesToUpdate[i].second << ")\n";);
Nate Begemanf15485a2006-03-27 01:32:24 +00005528
Chris Lattnera33ef482005-03-30 01:10:47 +00005529 // Next, now that we know what the last MBB the LLVM BB expanded is, update
Chris Lattner1c08c712005-01-07 07:47:53 +00005530 // PHI nodes in successors.
Anton Korobeynikov4198c582007-04-09 12:31:58 +00005531 if (SwitchCases.empty() && JTCases.empty() && BitTestCases.empty()) {
Nate Begemanf15485a2006-03-27 01:32:24 +00005532 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
5533 MachineInstr *PHI = PHINodesToUpdate[i].first;
5534 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
5535 "This is not a machine PHI node that we are updating!");
Chris Lattner9ce2e9d2007-12-30 00:57:42 +00005536 PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[i].second,
5537 false));
5538 PHI->addOperand(MachineOperand::CreateMBB(BB));
Nate Begemanf15485a2006-03-27 01:32:24 +00005539 }
5540 return;
Chris Lattner1c08c712005-01-07 07:47:53 +00005541 }
Anton Korobeynikov4198c582007-04-09 12:31:58 +00005542
5543 for (unsigned i = 0, e = BitTestCases.size(); i != e; ++i) {
5544 // Lower header first, if it wasn't already lowered
5545 if (!BitTestCases[i].Emitted) {
Chris Lattneread0d882008-06-17 06:09:18 +00005546 SelectionDAG HSDAG(TLI, MF, FuncInfo,
Dan Gohman0e5f1302008-07-07 23:02:41 +00005547 getAnalysisToUpdate<MachineModuleInfo>(),
Dan Gohmanfed90b62008-07-28 21:51:04 +00005548 NodeAllocator);
Anton Korobeynikov4198c582007-04-09 12:31:58 +00005549 CurDAG = &HSDAG;
Gordon Henriksen5eca0752008-08-17 18:44:35 +00005550 SelectionDAGLowering HSDL(HSDAG, TLI, *AA, FuncInfo, GFI);
Anton Korobeynikov4198c582007-04-09 12:31:58 +00005551 // Set the current basic block to the mbb we wish to insert the code into
5552 BB = BitTestCases[i].Parent;
5553 HSDL.setCurrentBasicBlock(BB);
5554 // Emit the code
5555 HSDL.visitBitTestHeader(BitTestCases[i]);
5556 HSDAG.setRoot(HSDL.getRoot());
5557 CodeGenAndEmitDAG(HSDAG);
5558 }
5559
5560 for (unsigned j = 0, ej = BitTestCases[i].Cases.size(); j != ej; ++j) {
Chris Lattneread0d882008-06-17 06:09:18 +00005561 SelectionDAG BSDAG(TLI, MF, FuncInfo,
Dan Gohman0e5f1302008-07-07 23:02:41 +00005562 getAnalysisToUpdate<MachineModuleInfo>(),
Dan Gohmanfed90b62008-07-28 21:51:04 +00005563 NodeAllocator);
Anton Korobeynikov4198c582007-04-09 12:31:58 +00005564 CurDAG = &BSDAG;
Gordon Henriksen5eca0752008-08-17 18:44:35 +00005565 SelectionDAGLowering BSDL(BSDAG, TLI, *AA, FuncInfo, GFI);
Anton Korobeynikov4198c582007-04-09 12:31:58 +00005566 // Set the current basic block to the mbb we wish to insert the code into
5567 BB = BitTestCases[i].Cases[j].ThisBB;
5568 BSDL.setCurrentBasicBlock(BB);
5569 // Emit the code
5570 if (j+1 != ej)
5571 BSDL.visitBitTestCase(BitTestCases[i].Cases[j+1].ThisBB,
5572 BitTestCases[i].Reg,
5573 BitTestCases[i].Cases[j]);
5574 else
5575 BSDL.visitBitTestCase(BitTestCases[i].Default,
5576 BitTestCases[i].Reg,
5577 BitTestCases[i].Cases[j]);
5578
5579
5580 BSDAG.setRoot(BSDL.getRoot());
5581 CodeGenAndEmitDAG(BSDAG);
5582 }
5583
5584 // Update PHI Nodes
5585 for (unsigned pi = 0, pe = PHINodesToUpdate.size(); pi != pe; ++pi) {
5586 MachineInstr *PHI = PHINodesToUpdate[pi].first;
5587 MachineBasicBlock *PHIBB = PHI->getParent();
5588 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
5589 "This is not a machine PHI node that we are updating!");
5590 // This is "default" BB. We have two jumps to it. From "header" BB and
5591 // from last "case" BB.
5592 if (PHIBB == BitTestCases[i].Default) {
Chris Lattner9ce2e9d2007-12-30 00:57:42 +00005593 PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[pi].second,
5594 false));
5595 PHI->addOperand(MachineOperand::CreateMBB(BitTestCases[i].Parent));
5596 PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[pi].second,
5597 false));
5598 PHI->addOperand(MachineOperand::CreateMBB(BitTestCases[i].Cases.
5599 back().ThisBB));
Anton Korobeynikov4198c582007-04-09 12:31:58 +00005600 }
5601 // One of "cases" BB.
5602 for (unsigned j = 0, ej = BitTestCases[i].Cases.size(); j != ej; ++j) {
5603 MachineBasicBlock* cBB = BitTestCases[i].Cases[j].ThisBB;
5604 if (cBB->succ_end() !=
5605 std::find(cBB->succ_begin(),cBB->succ_end(), PHIBB)) {
Chris Lattner9ce2e9d2007-12-30 00:57:42 +00005606 PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[pi].second,
5607 false));
5608 PHI->addOperand(MachineOperand::CreateMBB(cBB));
Anton Korobeynikov4198c582007-04-09 12:31:58 +00005609 }
5610 }
5611 }
5612 }
5613
Nate Begeman9453eea2006-04-23 06:26:20 +00005614 // If the JumpTable record is filled in, then we need to emit a jump table.
5615 // Updating the PHI nodes is tricky in this case, since we need to determine
5616 // whether the PHI is a successor of the range check MBB or the jump table MBB
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00005617 for (unsigned i = 0, e = JTCases.size(); i != e; ++i) {
5618 // Lower header first, if it wasn't already lowered
5619 if (!JTCases[i].first.Emitted) {
Chris Lattneread0d882008-06-17 06:09:18 +00005620 SelectionDAG HSDAG(TLI, MF, FuncInfo,
Dan Gohman0e5f1302008-07-07 23:02:41 +00005621 getAnalysisToUpdate<MachineModuleInfo>(),
Dan Gohmanfed90b62008-07-28 21:51:04 +00005622 NodeAllocator);
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00005623 CurDAG = &HSDAG;
Gordon Henriksen5eca0752008-08-17 18:44:35 +00005624 SelectionDAGLowering HSDL(HSDAG, TLI, *AA, FuncInfo, GFI);
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00005625 // Set the current basic block to the mbb we wish to insert the code into
5626 BB = JTCases[i].first.HeaderBB;
5627 HSDL.setCurrentBasicBlock(BB);
5628 // Emit the code
5629 HSDL.visitJumpTableHeader(JTCases[i].second, JTCases[i].first);
5630 HSDAG.setRoot(HSDL.getRoot());
5631 CodeGenAndEmitDAG(HSDAG);
Anton Korobeynikov4198c582007-04-09 12:31:58 +00005632 }
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00005633
Chris Lattneread0d882008-06-17 06:09:18 +00005634 SelectionDAG JSDAG(TLI, MF, FuncInfo,
Dan Gohman0e5f1302008-07-07 23:02:41 +00005635 getAnalysisToUpdate<MachineModuleInfo>(),
Dan Gohmanfed90b62008-07-28 21:51:04 +00005636 NodeAllocator);
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00005637 CurDAG = &JSDAG;
Gordon Henriksen5eca0752008-08-17 18:44:35 +00005638 SelectionDAGLowering JSDL(JSDAG, TLI, *AA, FuncInfo, GFI);
Nate Begeman37efe672006-04-22 18:53:45 +00005639 // Set the current basic block to the mbb we wish to insert the code into
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00005640 BB = JTCases[i].second.MBB;
5641 JSDL.setCurrentBasicBlock(BB);
Nate Begeman37efe672006-04-22 18:53:45 +00005642 // Emit the code
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00005643 JSDL.visitJumpTable(JTCases[i].second);
5644 JSDAG.setRoot(JSDL.getRoot());
5645 CodeGenAndEmitDAG(JSDAG);
5646
Nate Begeman37efe672006-04-22 18:53:45 +00005647 // Update PHI Nodes
5648 for (unsigned pi = 0, pe = PHINodesToUpdate.size(); pi != pe; ++pi) {
5649 MachineInstr *PHI = PHINodesToUpdate[pi].first;
5650 MachineBasicBlock *PHIBB = PHI->getParent();
5651 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
5652 "This is not a machine PHI node that we are updating!");
Anton Korobeynikov4198c582007-04-09 12:31:58 +00005653 // "default" BB. We can go there only from header BB.
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00005654 if (PHIBB == JTCases[i].second.Default) {
Chris Lattner9ce2e9d2007-12-30 00:57:42 +00005655 PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[pi].second,
5656 false));
5657 PHI->addOperand(MachineOperand::CreateMBB(JTCases[i].first.HeaderBB));
Nate Begemanf4360a42006-05-03 03:48:02 +00005658 }
Anton Korobeynikov4198c582007-04-09 12:31:58 +00005659 // JT BB. Just iterate over successors here
Nate Begemanf4360a42006-05-03 03:48:02 +00005660 if (BB->succ_end() != std::find(BB->succ_begin(),BB->succ_end(), PHIBB)) {
Chris Lattner9ce2e9d2007-12-30 00:57:42 +00005661 PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[pi].second,
5662 false));
5663 PHI->addOperand(MachineOperand::CreateMBB(BB));
Nate Begeman37efe672006-04-22 18:53:45 +00005664 }
5665 }
Nate Begeman37efe672006-04-22 18:53:45 +00005666 }
5667
Chris Lattnerb2e806e2006-10-22 23:00:53 +00005668 // If the switch block involved a branch to one of the actual successors, we
5669 // need to update PHI nodes in that block.
5670 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
5671 MachineInstr *PHI = PHINodesToUpdate[i].first;
5672 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
5673 "This is not a machine PHI node that we are updating!");
5674 if (BB->isSuccessor(PHI->getParent())) {
Chris Lattner9ce2e9d2007-12-30 00:57:42 +00005675 PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[i].second,
5676 false));
5677 PHI->addOperand(MachineOperand::CreateMBB(BB));
Chris Lattnerb2e806e2006-10-22 23:00:53 +00005678 }
5679 }
5680
Nate Begemanf15485a2006-03-27 01:32:24 +00005681 // If we generated any switch lowering information, build and codegen any
5682 // additional DAGs necessary.
Chris Lattnerd5e93c02006-09-07 01:59:34 +00005683 for (unsigned i = 0, e = SwitchCases.size(); i != e; ++i) {
Chris Lattneread0d882008-06-17 06:09:18 +00005684 SelectionDAG SDAG(TLI, MF, FuncInfo,
Dan Gohman0e5f1302008-07-07 23:02:41 +00005685 getAnalysisToUpdate<MachineModuleInfo>(),
Dan Gohmanfed90b62008-07-28 21:51:04 +00005686 NodeAllocator);
Nate Begemanf15485a2006-03-27 01:32:24 +00005687 CurDAG = &SDAG;
Gordon Henriksen5eca0752008-08-17 18:44:35 +00005688 SelectionDAGLowering SDL(SDAG, TLI, *AA, FuncInfo, GFI);
Chris Lattnerd5e93c02006-09-07 01:59:34 +00005689
Nate Begemanf15485a2006-03-27 01:32:24 +00005690 // Set the current basic block to the mbb we wish to insert the code into
5691 BB = SwitchCases[i].ThisBB;
5692 SDL.setCurrentBasicBlock(BB);
Chris Lattnerd5e93c02006-09-07 01:59:34 +00005693
Nate Begemanf15485a2006-03-27 01:32:24 +00005694 // Emit the code
5695 SDL.visitSwitchCase(SwitchCases[i]);
5696 SDAG.setRoot(SDL.getRoot());
5697 CodeGenAndEmitDAG(SDAG);
Chris Lattnerd5e93c02006-09-07 01:59:34 +00005698
5699 // Handle any PHI nodes in successors of this chunk, as if we were coming
5700 // from the original BB before switch expansion. Note that PHI nodes can
5701 // occur multiple times in PHINodesToUpdate. We have to be very careful to
5702 // handle them the right number of times.
Chris Lattner57ab6592006-10-24 17:57:59 +00005703 while ((BB = SwitchCases[i].TrueBB)) { // Handle LHS and RHS.
Chris Lattnerd5e93c02006-09-07 01:59:34 +00005704 for (MachineBasicBlock::iterator Phi = BB->begin();
5705 Phi != BB->end() && Phi->getOpcode() == TargetInstrInfo::PHI; ++Phi){
5706 // This value for this PHI node is recorded in PHINodesToUpdate, get it.
5707 for (unsigned pn = 0; ; ++pn) {
5708 assert(pn != PHINodesToUpdate.size() && "Didn't find PHI entry!");
5709 if (PHINodesToUpdate[pn].first == Phi) {
Chris Lattner9ce2e9d2007-12-30 00:57:42 +00005710 Phi->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[pn].
5711 second, false));
5712 Phi->addOperand(MachineOperand::CreateMBB(SwitchCases[i].ThisBB));
Chris Lattnerd5e93c02006-09-07 01:59:34 +00005713 break;
5714 }
5715 }
Nate Begemanf15485a2006-03-27 01:32:24 +00005716 }
Chris Lattnerd5e93c02006-09-07 01:59:34 +00005717
5718 // Don't process RHS if same block as LHS.
Chris Lattner57ab6592006-10-24 17:57:59 +00005719 if (BB == SwitchCases[i].FalseBB)
5720 SwitchCases[i].FalseBB = 0;
Chris Lattnerd5e93c02006-09-07 01:59:34 +00005721
5722 // If we haven't handled the RHS, do so now. Otherwise, we're done.
Chris Lattner24525952006-10-24 18:07:37 +00005723 SwitchCases[i].TrueBB = SwitchCases[i].FalseBB;
Chris Lattner57ab6592006-10-24 17:57:59 +00005724 SwitchCases[i].FalseBB = 0;
Nate Begemanf15485a2006-03-27 01:32:24 +00005725 }
Chris Lattner57ab6592006-10-24 17:57:59 +00005726 assert(SwitchCases[i].TrueBB == 0 && SwitchCases[i].FalseBB == 0);
Chris Lattnera33ef482005-03-30 01:10:47 +00005727 }
Chris Lattner1c08c712005-01-07 07:47:53 +00005728}
Evan Chenga9c20912006-01-21 02:32:06 +00005729
Jim Laskey13ec7022006-08-01 14:21:23 +00005730
Dan Gohman5e843682008-07-14 18:19:29 +00005731/// Schedule - Pick a safe ordering for instructions for each
Evan Chenga9c20912006-01-21 02:32:06 +00005732/// target node in the graph.
Dan Gohman5e843682008-07-14 18:19:29 +00005733///
5734ScheduleDAG *SelectionDAGISel::Schedule(SelectionDAG &DAG) {
Jim Laskeyeb577ba2006-08-02 12:30:23 +00005735 RegisterScheduler::FunctionPassCtor Ctor = RegisterScheduler::getDefault();
Jim Laskey13ec7022006-08-01 14:21:23 +00005736
5737 if (!Ctor) {
Jim Laskeyeb577ba2006-08-02 12:30:23 +00005738 Ctor = ISHeuristic;
Jim Laskey9373beb2006-08-01 19:14:14 +00005739 RegisterScheduler::setDefault(Ctor);
Evan Cheng4ef10862006-01-23 07:01:07 +00005740 }
Jim Laskey13ec7022006-08-01 14:21:23 +00005741
Dan Gohman925a7e82008-08-13 19:47:40 +00005742 ScheduleDAG *Scheduler = Ctor(this, &DAG, BB, Fast);
Dan Gohman5e843682008-07-14 18:19:29 +00005743 Scheduler->Run();
Dan Gohman3e1a7ae2007-08-28 20:32:58 +00005744
Dan Gohman5e843682008-07-14 18:19:29 +00005745 return Scheduler;
Evan Chenga9c20912006-01-21 02:32:06 +00005746}
Chris Lattner0e43f2b2006-02-24 02:13:54 +00005747
Chris Lattner03fc53c2006-03-06 00:22:00 +00005748
Jim Laskey9ff542f2006-08-01 18:29:48 +00005749HazardRecognizer *SelectionDAGISel::CreateTargetHazardRecognizer() {
5750 return new HazardRecognizer();
5751}
5752
Chris Lattner75548062006-10-11 03:58:02 +00005753//===----------------------------------------------------------------------===//
5754// Helper functions used by the generated instruction selector.
5755//===----------------------------------------------------------------------===//
5756// Calls to these methods are generated by tblgen.
5757
5758/// CheckAndMask - The isel is trying to match something like (and X, 255). If
5759/// the dag combiner simplified the 255, we still want to match. RHS is the
5760/// actual value in the DAG on the RHS of an AND, and DesiredMaskS is the value
5761/// specified in the .td file (e.g. 255).
Dan Gohman475871a2008-07-27 21:46:04 +00005762bool SelectionDAGISel::CheckAndMask(SDValue LHS, ConstantSDNode *RHS,
Dan Gohmandc9b3d02007-07-24 23:00:27 +00005763 int64_t DesiredMaskS) const {
Dan Gohman2e68b6f2008-02-25 21:11:39 +00005764 const APInt &ActualMask = RHS->getAPIntValue();
5765 const APInt &DesiredMask = APInt(LHS.getValueSizeInBits(), DesiredMaskS);
Chris Lattner75548062006-10-11 03:58:02 +00005766
5767 // If the actual mask exactly matches, success!
5768 if (ActualMask == DesiredMask)
5769 return true;
5770
5771 // If the actual AND mask is allowing unallowed bits, this doesn't match.
Dan Gohman2e68b6f2008-02-25 21:11:39 +00005772 if (ActualMask.intersects(~DesiredMask))
Chris Lattner75548062006-10-11 03:58:02 +00005773 return false;
5774
5775 // Otherwise, the DAG Combiner may have proven that the value coming in is
5776 // either already zero or is not demanded. Check for known zero input bits.
Dan Gohman2e68b6f2008-02-25 21:11:39 +00005777 APInt NeededMask = DesiredMask & ~ActualMask;
Dan Gohmanea859be2007-06-22 14:59:07 +00005778 if (CurDAG->MaskedValueIsZero(LHS, NeededMask))
Chris Lattner75548062006-10-11 03:58:02 +00005779 return true;
5780
5781 // TODO: check to see if missing bits are just not demanded.
5782
5783 // Otherwise, this pattern doesn't match.
5784 return false;
5785}
5786
5787/// CheckOrMask - The isel is trying to match something like (or X, 255). If
5788/// the dag combiner simplified the 255, we still want to match. RHS is the
5789/// actual value in the DAG on the RHS of an OR, and DesiredMaskS is the value
5790/// specified in the .td file (e.g. 255).
Dan Gohman475871a2008-07-27 21:46:04 +00005791bool SelectionDAGISel::CheckOrMask(SDValue LHS, ConstantSDNode *RHS,
Dan Gohman2e68b6f2008-02-25 21:11:39 +00005792 int64_t DesiredMaskS) const {
5793 const APInt &ActualMask = RHS->getAPIntValue();
5794 const APInt &DesiredMask = APInt(LHS.getValueSizeInBits(), DesiredMaskS);
Chris Lattner75548062006-10-11 03:58:02 +00005795
5796 // If the actual mask exactly matches, success!
5797 if (ActualMask == DesiredMask)
5798 return true;
5799
5800 // If the actual AND mask is allowing unallowed bits, this doesn't match.
Dan Gohman2e68b6f2008-02-25 21:11:39 +00005801 if (ActualMask.intersects(~DesiredMask))
Chris Lattner75548062006-10-11 03:58:02 +00005802 return false;
5803
5804 // Otherwise, the DAG Combiner may have proven that the value coming in is
5805 // either already zero or is not demanded. Check for known zero input bits.
Dan Gohman2e68b6f2008-02-25 21:11:39 +00005806 APInt NeededMask = DesiredMask & ~ActualMask;
Chris Lattner75548062006-10-11 03:58:02 +00005807
Dan Gohman2e68b6f2008-02-25 21:11:39 +00005808 APInt KnownZero, KnownOne;
Dan Gohmanea859be2007-06-22 14:59:07 +00005809 CurDAG->ComputeMaskedBits(LHS, NeededMask, KnownZero, KnownOne);
Chris Lattner75548062006-10-11 03:58:02 +00005810
5811 // If all the missing bits in the or are already known to be set, match!
5812 if ((NeededMask & KnownOne) == NeededMask)
5813 return true;
5814
5815 // TODO: check to see if missing bits are just not demanded.
5816
5817 // Otherwise, this pattern doesn't match.
5818 return false;
5819}
5820
Jim Laskey9ff542f2006-08-01 18:29:48 +00005821
Chris Lattner0e43f2b2006-02-24 02:13:54 +00005822/// SelectInlineAsmMemoryOperands - Calls to this are automatically generated
5823/// by tblgen. Others should not call it.
5824void SelectionDAGISel::
Dan Gohman475871a2008-07-27 21:46:04 +00005825SelectInlineAsmMemoryOperands(std::vector<SDValue> &Ops, SelectionDAG &DAG) {
5826 std::vector<SDValue> InOps;
Chris Lattner0e43f2b2006-02-24 02:13:54 +00005827 std::swap(InOps, Ops);
5828
5829 Ops.push_back(InOps[0]); // input chain.
5830 Ops.push_back(InOps[1]); // input asm string.
5831
Chris Lattner0e43f2b2006-02-24 02:13:54 +00005832 unsigned i = 2, e = InOps.size();
5833 if (InOps[e-1].getValueType() == MVT::Flag)
5834 --e; // Don't process a flag operand if it is here.
5835
5836 while (i != e) {
5837 unsigned Flags = cast<ConstantSDNode>(InOps[i])->getValue();
5838 if ((Flags & 7) != 4 /*MEM*/) {
5839 // Just skip over this operand, copying the operands verbatim.
5840 Ops.insert(Ops.end(), InOps.begin()+i, InOps.begin()+i+(Flags >> 3) + 1);
5841 i += (Flags >> 3) + 1;
5842 } else {
5843 assert((Flags >> 3) == 1 && "Memory operand with multiple values?");
5844 // Otherwise, this is a memory operand. Ask the target to select it.
Dan Gohman475871a2008-07-27 21:46:04 +00005845 std::vector<SDValue> SelOps;
Chris Lattner0e43f2b2006-02-24 02:13:54 +00005846 if (SelectInlineAsmMemoryOperand(InOps[i+1], 'm', SelOps, DAG)) {
Bill Wendling832171c2006-12-07 20:04:42 +00005847 cerr << "Could not match memory address. Inline asm failure!\n";
Chris Lattner0e43f2b2006-02-24 02:13:54 +00005848 exit(1);
5849 }
5850
5851 // Add this to the output node.
Duncan Sands83ec4b62008-06-06 12:08:01 +00005852 MVT IntPtrTy = DAG.getTargetLoweringInfo().getPointerTy();
Chris Lattner36d43962006-12-16 21:14:48 +00005853 Ops.push_back(DAG.getTargetConstant(4/*MEM*/ | (SelOps.size() << 3),
Chris Lattner4b993b12007-04-09 00:33:58 +00005854 IntPtrTy));
Chris Lattner0e43f2b2006-02-24 02:13:54 +00005855 Ops.insert(Ops.end(), SelOps.begin(), SelOps.end());
5856 i += 2;
5857 }
5858 }
5859
5860 // Add the flag input back if present.
5861 if (e != InOps.size())
5862 Ops.push_back(InOps.back());
5863}
Devang Patel794fd752007-05-01 21:15:47 +00005864
Devang Patel19974732007-05-03 01:11:54 +00005865char SelectionDAGISel::ID = 0;