blob: f0afdae866be429cd62114f96bed00704e489944 [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;
Dan Gohman7c3234c2008-08-27 23:52:12 +0000316 Function *Fn;
317 MachineFunction *MF;
318 MachineRegisterInfo *RegInfo;
Chris Lattner1c08c712005-01-07 07:47:53 +0000319
Dan Gohman7c3234c2008-08-27 23:52:12 +0000320 explicit FunctionLoweringInfo(TargetLowering &TLI);
321
322 /// set - Initialize this FunctionLoweringInfo with the given Function
323 /// and its associated MachineFunction.
324 ///
325 void set(Function &Fn, MachineFunction &MF);
Chris Lattner1c08c712005-01-07 07:47:53 +0000326
327 /// MBBMap - A mapping from LLVM basic blocks to their machine code entry.
Dan Gohman6ecf5092008-08-23 02:44:46 +0000328 DenseMap<const BasicBlock*, MachineBasicBlock *> MBBMap;
Chris Lattner1c08c712005-01-07 07:47:53 +0000329
330 /// ValueMap - Since we emit code for the function a basic block at a time,
331 /// we must remember which virtual registers hold the values for
332 /// cross-basic-block values.
Chris Lattner9f24ad72007-02-04 01:35:11 +0000333 DenseMap<const Value*, unsigned> ValueMap;
Chris Lattner1c08c712005-01-07 07:47:53 +0000334
335 /// StaticAllocaMap - Keep track of frame indices for fixed sized allocas in
336 /// the entry block. This allows the allocas to be efficiently referenced
337 /// anywhere in the function.
Dan Gohman6ecf5092008-08-23 02:44:46 +0000338 DenseMap<const AllocaInst*, int> StaticAllocaMap;
Chris Lattner1c08c712005-01-07 07:47:53 +0000339
Duncan Sandsf4070822007-06-15 19:04:19 +0000340#ifndef NDEBUG
341 SmallSet<Instruction*, 8> CatchInfoLost;
342 SmallSet<Instruction*, 8> CatchInfoFound;
343#endif
344
Duncan Sands83ec4b62008-06-06 12:08:01 +0000345 unsigned MakeReg(MVT VT) {
Dan Gohman7c3234c2008-08-27 23:52:12 +0000346 return RegInfo->createVirtualRegister(TLI.getRegClassFor(VT));
Chris Lattner1c08c712005-01-07 07:47:53 +0000347 }
Chris Lattner571e4342006-10-27 21:36:01 +0000348
349 /// isExportedInst - Return true if the specified value is an instruction
350 /// exported from its block.
351 bool isExportedInst(const Value *V) {
352 return ValueMap.count(V);
353 }
Misha Brukmanedf128a2005-04-21 22:36:52 +0000354
Chris Lattner3c384492006-03-16 19:51:18 +0000355 unsigned CreateRegForValue(const Value *V);
356
Chris Lattner1c08c712005-01-07 07:47:53 +0000357 unsigned InitializeRegForValue(const Value *V) {
358 unsigned &R = ValueMap[V];
359 assert(R == 0 && "Already initialized this value register!");
360 return R = CreateRegForValue(V);
361 }
Chris Lattneread0d882008-06-17 06:09:18 +0000362
363 struct LiveOutInfo {
364 unsigned NumSignBits;
365 APInt KnownOne, KnownZero;
366 LiveOutInfo() : NumSignBits(0) {}
367 };
368
369 /// LiveOutRegInfo - Information about live out vregs, indexed by their
370 /// register number offset by 'FirstVirtualRegister'.
371 std::vector<LiveOutInfo> LiveOutRegInfo;
Dan Gohman7c3234c2008-08-27 23:52:12 +0000372
373 /// clear - Clear out all the function-specific state. This returns this
374 /// FunctionLoweringInfo to an empty state, ready to be used for a
375 /// different function.
376 void clear() {
377 MBBMap.clear();
378 ValueMap.clear();
379 StaticAllocaMap.clear();
380#ifndef NDEBUG
381 CatchInfoLost.clear();
382 CatchInfoFound.clear();
383#endif
384 LiveOutRegInfo.clear();
385 }
Chris Lattner1c08c712005-01-07 07:47:53 +0000386 };
387}
388
Duncan Sandscf26d7c2007-07-04 20:52:51 +0000389/// isSelector - Return true if this instruction is a call to the
390/// eh.selector intrinsic.
391static bool isSelector(Instruction *I) {
Duncan Sandsf4070822007-06-15 19:04:19 +0000392 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
Anton Korobeynikov8806c7b2007-09-07 11:39:35 +0000393 return (II->getIntrinsicID() == Intrinsic::eh_selector_i32 ||
394 II->getIntrinsicID() == Intrinsic::eh_selector_i64);
Duncan Sandsf4070822007-06-15 19:04:19 +0000395 return false;
396}
397
Chris Lattner1c08c712005-01-07 07:47:53 +0000398/// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by
Nate Begemanf15485a2006-03-27 01:32:24 +0000399/// PHI nodes or outside of the basic block that defines it, or used by a
Andrew Lenharthab0b9492008-02-21 06:45:13 +0000400/// switch or atomic instruction, which may expand to multiple basic blocks.
Chris Lattner1c08c712005-01-07 07:47:53 +0000401static bool isUsedOutsideOfDefiningBlock(Instruction *I) {
402 if (isa<PHINode>(I)) return true;
403 BasicBlock *BB = I->getParent();
404 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; ++UI)
Nate Begemanf15485a2006-03-27 01:32:24 +0000405 if (cast<Instruction>(*UI)->getParent() != BB || isa<PHINode>(*UI) ||
Chris Lattner571e4342006-10-27 21:36:01 +0000406 // FIXME: Remove switchinst special case.
Nate Begemanf15485a2006-03-27 01:32:24 +0000407 isa<SwitchInst>(*UI))
Chris Lattner1c08c712005-01-07 07:47:53 +0000408 return true;
409 return false;
410}
411
Chris Lattnerbf209482005-10-30 19:42:35 +0000412/// isOnlyUsedInEntryBlock - If the specified argument is only used in the
Nate Begemanf15485a2006-03-27 01:32:24 +0000413/// entry block, return true. This includes arguments used by switches, since
414/// the switch may expand into multiple basic blocks.
Chris Lattnerbf209482005-10-30 19:42:35 +0000415static bool isOnlyUsedInEntryBlock(Argument *A) {
Dan Gohmanf350b272008-08-23 02:25:05 +0000416 // With FastISel active, we may be splitting blocks, so force creation
417 // of virtual registers for all non-dead arguments.
418 if (EnableFastISel)
419 return A->use_empty();
420
Chris Lattnerbf209482005-10-30 19:42:35 +0000421 BasicBlock *Entry = A->getParent()->begin();
422 for (Value::use_iterator UI = A->use_begin(), E = A->use_end(); UI != E; ++UI)
Nate Begemanf15485a2006-03-27 01:32:24 +0000423 if (cast<Instruction>(*UI)->getParent() != Entry || isa<SwitchInst>(*UI))
Chris Lattnerbf209482005-10-30 19:42:35 +0000424 return false; // Use not in entry block.
425 return true;
426}
427
Dan Gohman7c3234c2008-08-27 23:52:12 +0000428FunctionLoweringInfo::FunctionLoweringInfo(TargetLowering &tli)
429 : TLI(tli) {
430}
431
432void FunctionLoweringInfo::set(Function &fn, MachineFunction &mf) {
433 Fn = &fn;
434 MF = &mf;
435 RegInfo = &MF->getRegInfo();
Chris Lattner1c08c712005-01-07 07:47:53 +0000436
Chris Lattnerbf209482005-10-30 19:42:35 +0000437 // Create a vreg for each argument register that is not dead and is used
438 // outside of the entry block for the function.
Dan Gohman7c3234c2008-08-27 23:52:12 +0000439 for (Function::arg_iterator AI = Fn->arg_begin(), E = Fn->arg_end();
Chris Lattnerbf209482005-10-30 19:42:35 +0000440 AI != E; ++AI)
441 if (!isOnlyUsedInEntryBlock(AI))
442 InitializeRegForValue(AI);
443
Chris Lattner1c08c712005-01-07 07:47:53 +0000444 // Initialize the mapping of values to registers. This is only set up for
445 // instruction values that are used outside of the block that defines
446 // them.
Dan Gohman7c3234c2008-08-27 23:52:12 +0000447 Function::iterator BB = Fn->begin(), EB = Fn->end();
Chris Lattner1c08c712005-01-07 07:47:53 +0000448 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
449 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
Reid Spencerb83eb642006-10-20 07:07:24 +0000450 if (ConstantInt *CUI = dyn_cast<ConstantInt>(AI->getArraySize())) {
Chris Lattner1c08c712005-01-07 07:47:53 +0000451 const Type *Ty = AI->getAllocatedType();
Duncan Sands514ab342007-11-01 20:53:16 +0000452 uint64_t TySize = TLI.getTargetData()->getABITypeSize(Ty);
Nate Begemanae232e72005-11-06 09:00:38 +0000453 unsigned Align =
Chris Lattnerd2b7cec2007-02-14 05:52:17 +0000454 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
Nate Begemanae232e72005-11-06 09:00:38 +0000455 AI->getAlignment());
Chris Lattnera8217e32005-05-13 23:14:17 +0000456
Reid Spencerb83eb642006-10-20 07:07:24 +0000457 TySize *= CUI->getZExtValue(); // Get total allocated size.
Chris Lattnerd222f6a2005-10-18 22:14:06 +0000458 if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
Chris Lattner1c08c712005-01-07 07:47:53 +0000459 StaticAllocaMap[AI] =
Dan Gohman7c3234c2008-08-27 23:52:12 +0000460 MF->getFrameInfo()->CreateStackObject(TySize, Align);
Chris Lattner1c08c712005-01-07 07:47:53 +0000461 }
462
Jeff Cohen2aeaf4e2005-10-01 03:57:14 +0000463 for (; BB != EB; ++BB)
464 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
Chris Lattner1c08c712005-01-07 07:47:53 +0000465 if (!I->use_empty() && isUsedOutsideOfDefiningBlock(I))
466 if (!isa<AllocaInst>(I) ||
467 !StaticAllocaMap.count(cast<AllocaInst>(I)))
468 InitializeRegForValue(I);
469
470 // Create an initial MachineBasicBlock for each LLVM BasicBlock in F. This
471 // also creates the initial PHI MachineInstrs, though none of the input
472 // operands are populated.
Dan Gohman7c3234c2008-08-27 23:52:12 +0000473 for (BB = Fn->begin(), EB = Fn->end(); BB != EB; ++BB) {
Dan Gohman0e5f1302008-07-07 23:02:41 +0000474 MachineBasicBlock *MBB = mf.CreateMachineBasicBlock(BB);
Chris Lattner1c08c712005-01-07 07:47:53 +0000475 MBBMap[BB] = MBB;
Dan Gohman7c3234c2008-08-27 23:52:12 +0000476 MF->push_back(MBB);
Chris Lattner1c08c712005-01-07 07:47:53 +0000477
478 // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
479 // appropriate.
480 PHINode *PN;
Chris Lattner8c494ab2006-10-27 23:50:33 +0000481 for (BasicBlock::iterator I = BB->begin();(PN = dyn_cast<PHINode>(I)); ++I){
482 if (PN->use_empty()) continue;
483
Chris Lattner8c494ab2006-10-27 23:50:33 +0000484 unsigned PHIReg = ValueMap[PN];
485 assert(PHIReg && "PHI node does not have an assigned virtual register!");
Dan Gohman6f498b02008-08-04 23:42:46 +0000486
487 SmallVector<MVT, 4> ValueVTs;
488 ComputeValueVTs(TLI, PN->getType(), ValueVTs);
489 for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
490 MVT VT = ValueVTs[vti];
491 unsigned NumRegisters = TLI.getNumRegisters(VT);
492 const TargetInstrInfo *TII = TLI.getTargetMachine().getInstrInfo();
493 for (unsigned i = 0; i != NumRegisters; ++i)
494 BuildMI(MBB, TII->get(TargetInstrInfo::PHI), PHIReg+i);
495 PHIReg += NumRegisters;
496 }
Chris Lattner8c494ab2006-10-27 23:50:33 +0000497 }
Chris Lattner1c08c712005-01-07 07:47:53 +0000498 }
499}
500
Chris Lattner3c384492006-03-16 19:51:18 +0000501/// CreateRegForValue - Allocate the appropriate number of virtual registers of
502/// the correctly promoted or expanded types. Assign these registers
503/// consecutive vreg numbers and return the first assigned number.
Dan Gohman10a6b7a2008-04-28 18:19:43 +0000504///
505/// In the case that the given value has struct or array type, this function
506/// will assign registers for each member or element.
507///
Chris Lattner3c384492006-03-16 19:51:18 +0000508unsigned FunctionLoweringInfo::CreateRegForValue(const Value *V) {
Duncan Sands83ec4b62008-06-06 12:08:01 +0000509 SmallVector<MVT, 4> ValueVTs;
Chris Lattnerb606dba2008-04-28 06:44:42 +0000510 ComputeValueVTs(TLI, V->getType(), ValueVTs);
Bill Wendling95b39552007-04-24 21:13:23 +0000511
Dan Gohman23ce5022008-04-25 18:27:55 +0000512 unsigned FirstReg = 0;
Dan Gohmanb20d4f82008-04-28 17:42:03 +0000513 for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
Duncan Sands83ec4b62008-06-06 12:08:01 +0000514 MVT ValueVT = ValueVTs[Value];
515 MVT RegisterVT = TLI.getRegisterType(ValueVT);
Dan Gohman8c8c5fc2007-06-27 14:34:07 +0000516
Chris Lattnerb606dba2008-04-28 06:44:42 +0000517 unsigned NumRegs = TLI.getNumRegisters(ValueVT);
Dan Gohman23ce5022008-04-25 18:27:55 +0000518 for (unsigned i = 0; i != NumRegs; ++i) {
519 unsigned R = MakeReg(RegisterVT);
520 if (!FirstReg) FirstReg = R;
521 }
522 }
523 return FirstReg;
Chris Lattner3c384492006-03-16 19:51:18 +0000524}
Chris Lattner1c08c712005-01-07 07:47:53 +0000525
526//===----------------------------------------------------------------------===//
527/// SelectionDAGLowering - This is the common target-independent lowering
528/// implementation that is parameterized by a TargetLowering object.
529/// Also, targets can overload any lowering method.
530///
531namespace llvm {
532class SelectionDAGLowering {
533 MachineBasicBlock *CurMBB;
534
Dan Gohman475871a2008-07-27 21:46:04 +0000535 DenseMap<const Value*, SDValue> NodeMap;
Chris Lattner1c08c712005-01-07 07:47:53 +0000536
Chris Lattnerd3948112005-01-17 22:19:26 +0000537 /// PendingLoads - Loads are not emitted to the program immediately. We bunch
538 /// them up and then emit token factor nodes when possible. This allows us to
539 /// get simple disambiguation between loads without worrying about alias
540 /// analysis.
Dan Gohman475871a2008-07-27 21:46:04 +0000541 SmallVector<SDValue, 8> PendingLoads;
Chris Lattnerd3948112005-01-17 22:19:26 +0000542
Dan Gohman86e1ebf2008-03-27 19:56:19 +0000543 /// PendingExports - CopyToReg nodes that copy values to virtual registers
544 /// for export to other blocks need to be emitted before any terminator
545 /// instruction, but they have no other ordering requirements. We bunch them
546 /// up and the emit a single tokenfactor for them just before terminator
547 /// instructions.
Dan Gohman7c3234c2008-08-27 23:52:12 +0000548 SmallVector<SDValue, 8> PendingExports;
Dan Gohman86e1ebf2008-03-27 19:56:19 +0000549
Anton Korobeynikov5502bf62007-04-04 21:14:49 +0000550 /// Case - A struct to record the Value for a switch case, and the
551 /// case's target basic block.
552 struct Case {
553 Constant* Low;
554 Constant* High;
555 MachineBasicBlock* BB;
556
557 Case() : Low(0), High(0), BB(0) { }
558 Case(Constant* low, Constant* high, MachineBasicBlock* bb) :
559 Low(low), High(high), BB(bb) { }
560 uint64_t size() const {
561 uint64_t rHigh = cast<ConstantInt>(High)->getSExtValue();
562 uint64_t rLow = cast<ConstantInt>(Low)->getSExtValue();
563 return (rHigh - rLow + 1ULL);
564 }
565 };
566
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000567 struct CaseBits {
568 uint64_t Mask;
569 MachineBasicBlock* BB;
570 unsigned Bits;
571
572 CaseBits(uint64_t mask, MachineBasicBlock* bb, unsigned bits):
573 Mask(mask), BB(bb), Bits(bits) { }
574 };
575
Anton Korobeynikov5502bf62007-04-04 21:14:49 +0000576 typedef std::vector<Case> CaseVector;
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000577 typedef std::vector<CaseBits> CaseBitsVector;
Anton Korobeynikov5502bf62007-04-04 21:14:49 +0000578 typedef CaseVector::iterator CaseItr;
579 typedef std::pair<CaseItr, CaseItr> CaseRange;
Nate Begemanf15485a2006-03-27 01:32:24 +0000580
581 /// CaseRec - A struct with ctor used in lowering switches to a binary tree
582 /// of conditional branches.
583 struct CaseRec {
584 CaseRec(MachineBasicBlock *bb, Constant *lt, Constant *ge, CaseRange r) :
585 CaseBB(bb), LT(lt), GE(ge), Range(r) {}
586
587 /// CaseBB - The MBB in which to emit the compare and branch
588 MachineBasicBlock *CaseBB;
589 /// LT, GE - If nonzero, we know the current case value must be less-than or
590 /// greater-than-or-equal-to these Constants.
591 Constant *LT;
592 Constant *GE;
593 /// Range - A pair of iterators representing the range of case values to be
594 /// processed at this point in the binary search tree.
595 CaseRange Range;
596 };
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +0000597
598 typedef std::vector<CaseRec> CaseRecVector;
Anton Korobeynikov5502bf62007-04-04 21:14:49 +0000599
600 /// The comparison function for sorting the switch case values in the vector.
601 /// WARNING: Case ranges should be disjoint!
Nate Begemanf15485a2006-03-27 01:32:24 +0000602 struct CaseCmp {
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000603 bool operator () (const Case& C1, const Case& C2) {
Anton Korobeynikov5502bf62007-04-04 21:14:49 +0000604 assert(isa<ConstantInt>(C1.Low) && isa<ConstantInt>(C2.High));
605 const ConstantInt* CI1 = cast<const ConstantInt>(C1.Low);
606 const ConstantInt* CI2 = cast<const ConstantInt>(C2.High);
607 return CI1->getValue().slt(CI2->getValue());
Nate Begemanf15485a2006-03-27 01:32:24 +0000608 }
609 };
Anton Korobeynikov5502bf62007-04-04 21:14:49 +0000610
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000611 struct CaseBitsCmp {
612 bool operator () (const CaseBits& C1, const CaseBits& C2) {
613 return C1.Bits > C2.Bits;
614 }
615 };
616
Anton Korobeynikov5502bf62007-04-04 21:14:49 +0000617 unsigned Clusterify(CaseVector& Cases, const SwitchInst &SI);
Nate Begemanf15485a2006-03-27 01:32:24 +0000618
Dan Gohman9ffd8b52008-08-28 20:38:18 +0000619 /// CaseBlock - This structure is used to communicate between SDLowering and
620 /// SDISel for the code generation of additional basic blocks needed by multi-
621 /// case switch statements.
622 struct CaseBlock {
623 CaseBlock(ISD::CondCode cc, Value *cmplhs, Value *cmprhs, Value *cmpmiddle,
624 MachineBasicBlock *truebb, MachineBasicBlock *falsebb,
625 MachineBasicBlock *me)
626 : CC(cc), CmpLHS(cmplhs), CmpMHS(cmpmiddle), CmpRHS(cmprhs),
627 TrueBB(truebb), FalseBB(falsebb), ThisBB(me) {}
628 // CC - the condition code to use for the case block's setcc node
629 ISD::CondCode CC;
630 // CmpLHS/CmpRHS/CmpMHS - The LHS/MHS/RHS of the comparison to emit.
631 // Emit by default LHS op RHS. MHS is used for range comparisons:
632 // If MHS is not null: (LHS <= MHS) and (MHS <= RHS).
633 Value *CmpLHS, *CmpMHS, *CmpRHS;
634 // TrueBB/FalseBB - the block to branch to if the setcc is true/false.
635 MachineBasicBlock *TrueBB, *FalseBB;
636 // ThisBB - the block into which to emit the code for the setcc and branches
637 MachineBasicBlock *ThisBB;
638 };
639 struct JumpTable {
640 JumpTable(unsigned R, unsigned J, MachineBasicBlock *M,
641 MachineBasicBlock *D): Reg(R), JTI(J), MBB(M), Default(D) {}
642
643 /// Reg - the virtual register containing the index of the jump table entry
644 //. to jump to.
645 unsigned Reg;
646 /// JTI - the JumpTableIndex for this jump table in the function.
647 unsigned JTI;
648 /// MBB - the MBB into which to emit the code for the indirect jump.
649 MachineBasicBlock *MBB;
650 /// Default - the MBB of the default bb, which is a successor of the range
651 /// check MBB. This is when updating PHI nodes in successors.
652 MachineBasicBlock *Default;
653 };
654 struct JumpTableHeader {
655 JumpTableHeader(uint64_t F, uint64_t L, Value* SV, MachineBasicBlock* H,
656 bool E = false):
657 First(F), Last(L), SValue(SV), HeaderBB(H), Emitted(E) {}
658 uint64_t First;
659 uint64_t Last;
660 Value *SValue;
661 MachineBasicBlock *HeaderBB;
662 bool Emitted;
663 };
664 typedef std::pair<JumpTableHeader, JumpTable> JumpTableBlock;
665
666 struct BitTestCase {
667 BitTestCase(uint64_t M, MachineBasicBlock* T, MachineBasicBlock* Tr):
668 Mask(M), ThisBB(T), TargetBB(Tr) { }
669 uint64_t Mask;
670 MachineBasicBlock* ThisBB;
671 MachineBasicBlock* TargetBB;
672 };
673
674 typedef SmallVector<BitTestCase, 3> BitTestInfo;
675
676 struct BitTestBlock {
677 BitTestBlock(uint64_t F, uint64_t R, Value* SV,
678 unsigned Rg, bool E,
679 MachineBasicBlock* P, MachineBasicBlock* D,
680 const BitTestInfo& C):
681 First(F), Range(R), SValue(SV), Reg(Rg), Emitted(E),
682 Parent(P), Default(D), Cases(C) { }
683 uint64_t First;
684 uint64_t Range;
685 Value *SValue;
686 unsigned Reg;
687 bool Emitted;
688 MachineBasicBlock *Parent;
689 MachineBasicBlock *Default;
690 BitTestInfo Cases;
691 };
692
Chris Lattner1c08c712005-01-07 07:47:53 +0000693public:
694 // TLI - This is information that describes the available target features we
695 // need for lowering. This indicates when operations are unavailable,
696 // implemented with a libcall, etc.
697 TargetLowering &TLI;
698 SelectionDAG &DAG;
Owen Andersona69571c2006-05-03 01:29:57 +0000699 const TargetData *TD;
Dan Gohman7c3234c2008-08-27 23:52:12 +0000700 AliasAnalysis *AA;
Chris Lattner1c08c712005-01-07 07:47:53 +0000701
Nate Begemanf15485a2006-03-27 01:32:24 +0000702 /// SwitchCases - Vector of CaseBlock structures used to communicate
703 /// SwitchInst code generation information.
Dan Gohman7c3234c2008-08-27 23:52:12 +0000704 std::vector<CaseBlock> SwitchCases;
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +0000705 /// JTCases - Vector of JumpTable structures used to communicate
706 /// SwitchInst code generation information.
Dan Gohman7c3234c2008-08-27 23:52:12 +0000707 std::vector<JumpTableBlock> JTCases;
708 /// BitTestCases - Vector of BitTestBlock structures used to communicate
709 /// SwitchInst code generation information.
710 std::vector<BitTestBlock> BitTestCases;
Nate Begemanf15485a2006-03-27 01:32:24 +0000711
Dan Gohman7c3234c2008-08-27 23:52:12 +0000712 std::vector<std::pair<MachineInstr*, unsigned> > PHINodesToUpdate;
713
714 // Emit PHI-node-operand constants only once even if used by multiple
715 // PHI nodes.
716 DenseMap<Constant*, unsigned> ConstantsOut;
717
Chris Lattner1c08c712005-01-07 07:47:53 +0000718 /// FuncInfo - Information about the function as a whole.
719 ///
720 FunctionLoweringInfo &FuncInfo;
Gordon Henriksence224772008-01-07 01:30:38 +0000721
Gordon Henriksen5eca0752008-08-17 18:44:35 +0000722 /// GFI - Garbage collection metadata for the function.
723 GCFunctionInfo *GFI;
Chris Lattner1c08c712005-01-07 07:47:53 +0000724
725 SelectionDAGLowering(SelectionDAG &dag, TargetLowering &tli,
Dan Gohman7c3234c2008-08-27 23:52:12 +0000726 FunctionLoweringInfo &funcinfo)
727 : TLI(tli), DAG(dag), FuncInfo(funcinfo) {
728 }
729
730 void init(GCFunctionInfo *gfi, AliasAnalysis &aa) {
731 AA = &aa;
732 GFI = gfi;
733 TD = DAG.getTarget().getTargetData();
734 }
735
736 /// clear - Clear out the curret SelectionDAG and the associated
737 /// state and prepare this SelectionDAGLowering object to be used
738 /// for a new block. This doesn't clear out information about
739 /// additional blocks that are needed to complete switch lowering
740 /// or PHI node updating; that information is cleared out as it is
741 /// consumed.
742 void clear() {
743 NodeMap.clear();
744 PendingLoads.clear();
745 PendingExports.clear();
746 DAG.clear();
Chris Lattner1c08c712005-01-07 07:47:53 +0000747 }
748
Dan Gohman86e1ebf2008-03-27 19:56:19 +0000749 /// getRoot - Return the current virtual root of the Selection DAG,
750 /// flushing any PendingLoad items. This must be done before emitting
751 /// a store or any other node that may need to be ordered after any
752 /// prior load instructions.
Chris Lattnera651cf62005-01-17 19:43:36 +0000753 ///
Dan Gohman475871a2008-07-27 21:46:04 +0000754 SDValue getRoot() {
Chris Lattnerd3948112005-01-17 22:19:26 +0000755 if (PendingLoads.empty())
756 return DAG.getRoot();
Misha Brukmanedf128a2005-04-21 22:36:52 +0000757
Chris Lattnerd3948112005-01-17 22:19:26 +0000758 if (PendingLoads.size() == 1) {
Dan Gohman475871a2008-07-27 21:46:04 +0000759 SDValue Root = PendingLoads[0];
Chris Lattnerd3948112005-01-17 22:19:26 +0000760 DAG.setRoot(Root);
761 PendingLoads.clear();
762 return Root;
763 }
764
765 // Otherwise, we have to make a token factor node.
Dan Gohman475871a2008-07-27 21:46:04 +0000766 SDValue Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
Chris Lattnerbd564bf2006-08-08 02:23:42 +0000767 &PendingLoads[0], PendingLoads.size());
Chris Lattnerd3948112005-01-17 22:19:26 +0000768 PendingLoads.clear();
769 DAG.setRoot(Root);
770 return Root;
Chris Lattnera651cf62005-01-17 19:43:36 +0000771 }
772
Dan Gohman86e1ebf2008-03-27 19:56:19 +0000773 /// getControlRoot - Similar to getRoot, but instead of flushing all the
774 /// PendingLoad items, flush all the PendingExports items. It is necessary
775 /// to do this before emitting a terminator instruction.
776 ///
Dan Gohman475871a2008-07-27 21:46:04 +0000777 SDValue getControlRoot() {
778 SDValue Root = DAG.getRoot();
Dan Gohman86e1ebf2008-03-27 19:56:19 +0000779
780 if (PendingExports.empty())
781 return Root;
782
783 // Turn all of the CopyToReg chains into one factored node.
784 if (Root.getOpcode() != ISD::EntryToken) {
785 unsigned i = 0, e = PendingExports.size();
786 for (; i != e; ++i) {
Gabor Greifba36cb52008-08-28 21:40:38 +0000787 assert(PendingExports[i].getNode()->getNumOperands() > 1);
788 if (PendingExports[i].getNode()->getOperand(0) == Root)
Dan Gohman86e1ebf2008-03-27 19:56:19 +0000789 break; // Don't add the root if we already indirectly depend on it.
790 }
791
792 if (i == e)
793 PendingExports.push_back(Root);
794 }
795
796 Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
797 &PendingExports[0],
798 PendingExports.size());
799 PendingExports.clear();
800 DAG.setRoot(Root);
801 return Root;
802 }
803
804 void CopyValueToVirtualRegister(Value *V, unsigned Reg);
Chris Lattner571e4342006-10-27 21:36:01 +0000805
Chris Lattner1c08c712005-01-07 07:47:53 +0000806 void visit(Instruction &I) { visit(I.getOpcode(), I); }
807
808 void visit(unsigned Opcode, User &I) {
Chris Lattner1e7aa5c2006-11-10 04:41:34 +0000809 // Note: this doesn't use InstVisitor, because it has to work with
810 // ConstantExpr's in addition to instructions.
Chris Lattner1c08c712005-01-07 07:47:53 +0000811 switch (Opcode) {
812 default: assert(0 && "Unknown instruction type encountered!");
813 abort();
814 // Build the switch statement using the Instruction.def file.
815#define HANDLE_INST(NUM, OPCODE, CLASS) \
816 case Instruction::OPCODE:return visit##OPCODE((CLASS&)I);
817#include "llvm/Instruction.def"
818 }
819 }
820
821 void setCurrentBasicBlock(MachineBasicBlock *MBB) { CurMBB = MBB; }
822
Dan Gohman475871a2008-07-27 21:46:04 +0000823 SDValue getValue(const Value *V);
Chris Lattner1c08c712005-01-07 07:47:53 +0000824
Dan Gohman475871a2008-07-27 21:46:04 +0000825 void setValue(const Value *V, SDValue NewN) {
826 SDValue &N = NodeMap[V];
Gabor Greifba36cb52008-08-28 21:40:38 +0000827 assert(N.getNode() == 0 && "Already set a value for this node!");
Chris Lattner0da331f2007-02-04 01:31:47 +0000828 N = NewN;
Chris Lattner1c08c712005-01-07 07:47:53 +0000829 }
Chris Lattner4e4b5762006-02-01 18:59:47 +0000830
Evan Cheng5c807602008-02-26 02:33:44 +0000831 void GetRegistersForValue(SDISelAsmOperandInfo &OpInfo, bool HasEarlyClobber,
Chris Lattnere7cf56a2007-04-30 21:11:17 +0000832 std::set<unsigned> &OutputRegs,
833 std::set<unsigned> &InputRegs);
Nate Begemanf15485a2006-03-27 01:32:24 +0000834
Chris Lattner571e4342006-10-27 21:36:01 +0000835 void FindMergedConditions(Value *Cond, MachineBasicBlock *TBB,
836 MachineBasicBlock *FBB, MachineBasicBlock *CurBB,
837 unsigned Opc);
Dan Gohman9ffd8b52008-08-28 20:38:18 +0000838 bool ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases);
Chris Lattner8c494ab2006-10-27 23:50:33 +0000839 bool isExportableFromCurrentBlock(Value *V, const BasicBlock *FromBB);
Chris Lattner571e4342006-10-27 21:36:01 +0000840 void ExportFromCurrentBlock(Value *V);
Dan Gohman475871a2008-07-27 21:46:04 +0000841 void LowerCallTo(CallSite CS, SDValue Callee, bool IsTailCall,
Anton Korobeynikov070280e2007-05-23 11:08:31 +0000842 MachineBasicBlock *LandingPad = NULL);
Duncan Sandsdc024672007-11-27 13:23:08 +0000843
Chris Lattner1c08c712005-01-07 07:47:53 +0000844 // Terminator instructions.
845 void visitRet(ReturnInst &I);
846 void visitBr(BranchInst &I);
Nate Begemanf15485a2006-03-27 01:32:24 +0000847 void visitSwitch(SwitchInst &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000848 void visitUnreachable(UnreachableInst &I) { /* noop */ }
849
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +0000850 // Helpers for visitSwitch
Anton Korobeynikovdd433212007-03-27 12:05:48 +0000851 bool handleSmallSwitchRange(CaseRec& CR,
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +0000852 CaseRecVector& WorkList,
853 Value* SV,
854 MachineBasicBlock* Default);
Anton Korobeynikovdd433212007-03-27 12:05:48 +0000855 bool handleJTSwitchCase(CaseRec& CR,
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +0000856 CaseRecVector& WorkList,
857 Value* SV,
858 MachineBasicBlock* Default);
Anton Korobeynikovdd433212007-03-27 12:05:48 +0000859 bool handleBTSplitSwitchCase(CaseRec& CR,
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +0000860 CaseRecVector& WorkList,
861 Value* SV,
862 MachineBasicBlock* Default);
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000863 bool handleBitTestsSwitchCase(CaseRec& CR,
864 CaseRecVector& WorkList,
865 Value* SV,
866 MachineBasicBlock* Default);
Dan Gohman7c3234c2008-08-27 23:52:12 +0000867 void visitSwitchCase(CaseBlock &CB);
868 void visitBitTestHeader(BitTestBlock &B);
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000869 void visitBitTestCase(MachineBasicBlock* NextMBB,
870 unsigned Reg,
Dan Gohman7c3234c2008-08-27 23:52:12 +0000871 BitTestCase &B);
872 void visitJumpTable(JumpTable &JT);
873 void visitJumpTableHeader(JumpTable &JT, JumpTableHeader &JTH);
Nate Begemanf15485a2006-03-27 01:32:24 +0000874
Chris Lattner1c08c712005-01-07 07:47:53 +0000875 // These all get lowered before this pass.
Jim Laskeyb180aa12007-02-21 22:53:45 +0000876 void visitInvoke(InvokeInst &I);
877 void visitUnwind(UnwindInst &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000878
Dan Gohman7f321562007-06-25 16:23:39 +0000879 void visitBinary(User &I, unsigned OpCode);
Nate Begemane21ea612005-11-18 07:42:56 +0000880 void visitShift(User &I, unsigned Opcode);
Nate Begeman5fbb5d22005-11-19 00:36:38 +0000881 void visitAdd(User &I) {
Dan Gohman7f321562007-06-25 16:23:39 +0000882 if (I.getType()->isFPOrFPVector())
883 visitBinary(I, ISD::FADD);
Reid Spencer1628cec2006-10-26 06:15:43 +0000884 else
Dan Gohman7f321562007-06-25 16:23:39 +0000885 visitBinary(I, ISD::ADD);
Chris Lattner01b3d732005-09-28 22:28:18 +0000886 }
Chris Lattnerb9fccc42005-04-02 05:04:50 +0000887 void visitSub(User &I);
Reid Spencer1628cec2006-10-26 06:15:43 +0000888 void visitMul(User &I) {
Dan Gohman7f321562007-06-25 16:23:39 +0000889 if (I.getType()->isFPOrFPVector())
890 visitBinary(I, ISD::FMUL);
Reid Spencer1628cec2006-10-26 06:15:43 +0000891 else
Dan Gohman7f321562007-06-25 16:23:39 +0000892 visitBinary(I, ISD::MUL);
Chris Lattner01b3d732005-09-28 22:28:18 +0000893 }
Dan Gohman7f321562007-06-25 16:23:39 +0000894 void visitURem(User &I) { visitBinary(I, ISD::UREM); }
895 void visitSRem(User &I) { visitBinary(I, ISD::SREM); }
896 void visitFRem(User &I) { visitBinary(I, ISD::FREM); }
897 void visitUDiv(User &I) { visitBinary(I, ISD::UDIV); }
898 void visitSDiv(User &I) { visitBinary(I, ISD::SDIV); }
899 void visitFDiv(User &I) { visitBinary(I, ISD::FDIV); }
900 void visitAnd (User &I) { visitBinary(I, ISD::AND); }
901 void visitOr (User &I) { visitBinary(I, ISD::OR); }
902 void visitXor (User &I) { visitBinary(I, ISD::XOR); }
Reid Spencer24d6da52007-01-21 00:29:26 +0000903 void visitShl (User &I) { visitShift(I, ISD::SHL); }
Reid Spencer3822ff52006-11-08 06:47:33 +0000904 void visitLShr(User &I) { visitShift(I, ISD::SRL); }
905 void visitAShr(User &I) { visitShift(I, ISD::SRA); }
Reid Spencer45fb3f32006-11-20 01:22:35 +0000906 void visitICmp(User &I);
907 void visitFCmp(User &I);
Nate Begemanb43e9c12008-05-12 19:40:03 +0000908 void visitVICmp(User &I);
909 void visitVFCmp(User &I);
Reid Spencer3da59db2006-11-27 01:05:10 +0000910 // Visit the conversion instructions
911 void visitTrunc(User &I);
912 void visitZExt(User &I);
913 void visitSExt(User &I);
914 void visitFPTrunc(User &I);
915 void visitFPExt(User &I);
916 void visitFPToUI(User &I);
917 void visitFPToSI(User &I);
918 void visitUIToFP(User &I);
919 void visitSIToFP(User &I);
920 void visitPtrToInt(User &I);
921 void visitIntToPtr(User &I);
922 void visitBitCast(User &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000923
Chris Lattner2bbd8102006-03-29 00:11:43 +0000924 void visitExtractElement(User &I);
925 void visitInsertElement(User &I);
Chris Lattner3e104b12006-04-08 04:15:24 +0000926 void visitShuffleVector(User &I);
Chris Lattnerc7029802006-03-18 01:44:44 +0000927
Dan Gohman1d685a42008-06-07 02:02:36 +0000928 void visitExtractValue(ExtractValueInst &I);
929 void visitInsertValue(InsertValueInst &I);
Dan Gohman041e2eb2008-05-15 19:50:34 +0000930
Chris Lattner1c08c712005-01-07 07:47:53 +0000931 void visitGetElementPtr(User &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000932 void visitSelect(User &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000933
934 void visitMalloc(MallocInst &I);
935 void visitFree(FreeInst &I);
936 void visitAlloca(AllocaInst &I);
937 void visitLoad(LoadInst &I);
938 void visitStore(StoreInst &I);
939 void visitPHI(PHINode &I) { } // PHI nodes are handled specially.
940 void visitCall(CallInst &I);
Duncan Sandsfd7b3262007-12-17 18:08:19 +0000941 void visitInlineAsm(CallSite CS);
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +0000942 const char *visitIntrinsicCall(CallInst &I, unsigned Intrinsic);
Chris Lattner0eade312006-03-24 02:22:33 +0000943 void visitTargetIntrinsic(CallInst &I, unsigned Intrinsic);
Chris Lattner1c08c712005-01-07 07:47:53 +0000944
Chris Lattner1c08c712005-01-07 07:47:53 +0000945 void visitVAStart(CallInst &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000946 void visitVAArg(VAArgInst &I);
947 void visitVAEnd(CallInst &I);
948 void visitVACopy(CallInst &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000949
Chris Lattner1c08c712005-01-07 07:47:53 +0000950 void visitUserOp1(Instruction &I) {
951 assert(0 && "UserOp1 should not exist at instruction selection time!");
952 abort();
953 }
954 void visitUserOp2(Instruction &I) {
955 assert(0 && "UserOp2 should not exist at instruction selection time!");
956 abort();
957 }
Mon P Wang63307c32008-05-05 19:05:59 +0000958
959private:
960 inline const char *implVisitBinaryAtomic(CallInst& I, ISD::NodeType Op);
961
Chris Lattner1c08c712005-01-07 07:47:53 +0000962};
963} // end namespace llvm
964
Dan Gohman6183f782007-07-05 20:12:34 +0000965
Duncan Sandsb988bac2008-02-11 20:58:28 +0000966/// getCopyFromParts - Create a value that contains the specified legal parts
967/// combined into the value they represent. If the parts combine to a type
968/// larger then ValueVT then AssertOp can be used to specify whether the extra
969/// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
Chris Lattner4468c1f2008-03-09 09:38:46 +0000970/// (ISD::AssertSext).
Dan Gohman475871a2008-07-27 21:46:04 +0000971static SDValue getCopyFromParts(SelectionDAG &DAG,
972 const SDValue *Parts,
Dan Gohman6183f782007-07-05 20:12:34 +0000973 unsigned NumParts,
Duncan Sands83ec4b62008-06-06 12:08:01 +0000974 MVT PartVT,
975 MVT ValueVT,
Chris Lattner4468c1f2008-03-09 09:38:46 +0000976 ISD::NodeType AssertOp = ISD::DELETED_NODE) {
Duncan Sands014e04a2008-02-12 20:46:31 +0000977 assert(NumParts > 0 && "No parts to assemble!");
978 TargetLowering &TLI = DAG.getTargetLoweringInfo();
Dan Gohman475871a2008-07-27 21:46:04 +0000979 SDValue Val = Parts[0];
Dan Gohman6183f782007-07-05 20:12:34 +0000980
Duncan Sands014e04a2008-02-12 20:46:31 +0000981 if (NumParts > 1) {
982 // Assemble the value from multiple parts.
Duncan Sands83ec4b62008-06-06 12:08:01 +0000983 if (!ValueVT.isVector()) {
984 unsigned PartBits = PartVT.getSizeInBits();
985 unsigned ValueBits = ValueVT.getSizeInBits();
Dan Gohman6183f782007-07-05 20:12:34 +0000986
Duncan Sands014e04a2008-02-12 20:46:31 +0000987 // Assemble the power of 2 part.
988 unsigned RoundParts = NumParts & (NumParts - 1) ?
989 1 << Log2_32(NumParts) : NumParts;
990 unsigned RoundBits = PartBits * RoundParts;
Duncan Sands83ec4b62008-06-06 12:08:01 +0000991 MVT RoundVT = RoundBits == ValueBits ?
992 ValueVT : MVT::getIntegerVT(RoundBits);
Dan Gohman475871a2008-07-27 21:46:04 +0000993 SDValue Lo, Hi;
Duncan Sands014e04a2008-02-12 20:46:31 +0000994
995 if (RoundParts > 2) {
Duncan Sands83ec4b62008-06-06 12:08:01 +0000996 MVT HalfVT = MVT::getIntegerVT(RoundBits/2);
Duncan Sands014e04a2008-02-12 20:46:31 +0000997 Lo = getCopyFromParts(DAG, Parts, RoundParts/2, PartVT, HalfVT);
998 Hi = getCopyFromParts(DAG, Parts+RoundParts/2, RoundParts/2,
999 PartVT, HalfVT);
Dan Gohman6183f782007-07-05 20:12:34 +00001000 } else {
Duncan Sands014e04a2008-02-12 20:46:31 +00001001 Lo = Parts[0];
1002 Hi = Parts[1];
Dan Gohman6183f782007-07-05 20:12:34 +00001003 }
Duncan Sands014e04a2008-02-12 20:46:31 +00001004 if (TLI.isBigEndian())
1005 std::swap(Lo, Hi);
1006 Val = DAG.getNode(ISD::BUILD_PAIR, RoundVT, Lo, Hi);
1007
1008 if (RoundParts < NumParts) {
1009 // Assemble the trailing non-power-of-2 part.
1010 unsigned OddParts = NumParts - RoundParts;
Duncan Sands83ec4b62008-06-06 12:08:01 +00001011 MVT OddVT = MVT::getIntegerVT(OddParts * PartBits);
Duncan Sands014e04a2008-02-12 20:46:31 +00001012 Hi = getCopyFromParts(DAG, Parts+RoundParts, OddParts, PartVT, OddVT);
1013
1014 // Combine the round and odd parts.
1015 Lo = Val;
1016 if (TLI.isBigEndian())
1017 std::swap(Lo, Hi);
Duncan Sands83ec4b62008-06-06 12:08:01 +00001018 MVT TotalVT = MVT::getIntegerVT(NumParts * PartBits);
Duncan Sands014e04a2008-02-12 20:46:31 +00001019 Hi = DAG.getNode(ISD::ANY_EXTEND, TotalVT, Hi);
1020 Hi = DAG.getNode(ISD::SHL, TotalVT, Hi,
Duncan Sands83ec4b62008-06-06 12:08:01 +00001021 DAG.getConstant(Lo.getValueType().getSizeInBits(),
Duncan Sands014e04a2008-02-12 20:46:31 +00001022 TLI.getShiftAmountTy()));
1023 Lo = DAG.getNode(ISD::ZERO_EXTEND, TotalVT, Lo);
1024 Val = DAG.getNode(ISD::OR, TotalVT, Lo, Hi);
1025 }
1026 } else {
1027 // Handle a multi-element vector.
Duncan Sands83ec4b62008-06-06 12:08:01 +00001028 MVT IntermediateVT, RegisterVT;
Duncan Sands014e04a2008-02-12 20:46:31 +00001029 unsigned NumIntermediates;
1030 unsigned NumRegs =
1031 TLI.getVectorTypeBreakdown(ValueVT, IntermediateVT, NumIntermediates,
1032 RegisterVT);
Duncan Sands014e04a2008-02-12 20:46:31 +00001033 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
Evan Cheng35213342008-05-14 20:29:30 +00001034 NumParts = NumRegs; // Silence a compiler warning.
Duncan Sands014e04a2008-02-12 20:46:31 +00001035 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
1036 assert(RegisterVT == Parts[0].getValueType() &&
1037 "Part type doesn't match part!");
1038
1039 // Assemble the parts into intermediate operands.
Dan Gohman475871a2008-07-27 21:46:04 +00001040 SmallVector<SDValue, 8> Ops(NumIntermediates);
Duncan Sands014e04a2008-02-12 20:46:31 +00001041 if (NumIntermediates == NumParts) {
1042 // If the register was not expanded, truncate or copy the value,
1043 // as appropriate.
1044 for (unsigned i = 0; i != NumParts; ++i)
1045 Ops[i] = getCopyFromParts(DAG, &Parts[i], 1,
1046 PartVT, IntermediateVT);
1047 } else if (NumParts > 0) {
1048 // If the intermediate type was expanded, build the intermediate operands
1049 // from the parts.
1050 assert(NumParts % NumIntermediates == 0 &&
1051 "Must expand into a divisible number of parts!");
1052 unsigned Factor = NumParts / NumIntermediates;
1053 for (unsigned i = 0; i != NumIntermediates; ++i)
1054 Ops[i] = getCopyFromParts(DAG, &Parts[i * Factor], Factor,
1055 PartVT, IntermediateVT);
1056 }
1057
1058 // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the intermediate
1059 // operands.
Duncan Sands83ec4b62008-06-06 12:08:01 +00001060 Val = DAG.getNode(IntermediateVT.isVector() ?
Duncan Sands014e04a2008-02-12 20:46:31 +00001061 ISD::CONCAT_VECTORS : ISD::BUILD_VECTOR,
1062 ValueVT, &Ops[0], NumIntermediates);
Dan Gohman6183f782007-07-05 20:12:34 +00001063 }
Dan Gohman6183f782007-07-05 20:12:34 +00001064 }
1065
Duncan Sands014e04a2008-02-12 20:46:31 +00001066 // There is now one part, held in Val. Correct it to match ValueVT.
1067 PartVT = Val.getValueType();
Dan Gohman6183f782007-07-05 20:12:34 +00001068
Duncan Sands014e04a2008-02-12 20:46:31 +00001069 if (PartVT == ValueVT)
1070 return Val;
Dan Gohman6183f782007-07-05 20:12:34 +00001071
Duncan Sands83ec4b62008-06-06 12:08:01 +00001072 if (PartVT.isVector()) {
1073 assert(ValueVT.isVector() && "Unknown vector conversion!");
Duncan Sands014e04a2008-02-12 20:46:31 +00001074 return DAG.getNode(ISD::BIT_CONVERT, ValueVT, Val);
Dan Gohman6183f782007-07-05 20:12:34 +00001075 }
Duncan Sands014e04a2008-02-12 20:46:31 +00001076
Duncan Sands83ec4b62008-06-06 12:08:01 +00001077 if (ValueVT.isVector()) {
1078 assert(ValueVT.getVectorElementType() == PartVT &&
1079 ValueVT.getVectorNumElements() == 1 &&
Duncan Sands014e04a2008-02-12 20:46:31 +00001080 "Only trivial scalar-to-vector conversions should get here!");
1081 return DAG.getNode(ISD::BUILD_VECTOR, ValueVT, Val);
1082 }
1083
Duncan Sands83ec4b62008-06-06 12:08:01 +00001084 if (PartVT.isInteger() &&
1085 ValueVT.isInteger()) {
Duncan Sands8e4eb092008-06-08 20:54:56 +00001086 if (ValueVT.bitsLT(PartVT)) {
Duncan Sands014e04a2008-02-12 20:46:31 +00001087 // For a truncate, see if we have any information to
1088 // indicate whether the truncated bits will always be
1089 // zero or sign-extension.
1090 if (AssertOp != ISD::DELETED_NODE)
1091 Val = DAG.getNode(AssertOp, PartVT, Val,
1092 DAG.getValueType(ValueVT));
1093 return DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
1094 } else {
1095 return DAG.getNode(ISD::ANY_EXTEND, ValueVT, Val);
1096 }
1097 }
1098
Duncan Sands83ec4b62008-06-06 12:08:01 +00001099 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
Duncan Sands8e4eb092008-06-08 20:54:56 +00001100 if (ValueVT.bitsLT(Val.getValueType()))
Chris Lattner4468c1f2008-03-09 09:38:46 +00001101 // FP_ROUND's are always exact here.
Chris Lattnerd43d85c2008-03-09 07:47:22 +00001102 return DAG.getNode(ISD::FP_ROUND, ValueVT, Val,
Chris Lattner4468c1f2008-03-09 09:38:46 +00001103 DAG.getIntPtrConstant(1));
Chris Lattnerd43d85c2008-03-09 07:47:22 +00001104 return DAG.getNode(ISD::FP_EXTEND, ValueVT, Val);
1105 }
Duncan Sands014e04a2008-02-12 20:46:31 +00001106
Duncan Sands83ec4b62008-06-06 12:08:01 +00001107 if (PartVT.getSizeInBits() == ValueVT.getSizeInBits())
Duncan Sands014e04a2008-02-12 20:46:31 +00001108 return DAG.getNode(ISD::BIT_CONVERT, ValueVT, Val);
1109
1110 assert(0 && "Unknown mismatch!");
Dan Gohman475871a2008-07-27 21:46:04 +00001111 return SDValue();
Dan Gohman6183f782007-07-05 20:12:34 +00001112}
1113
Duncan Sandsb988bac2008-02-11 20:58:28 +00001114/// getCopyToParts - Create a series of nodes that contain the specified value
1115/// split into legal parts. If the parts contain more bits than Val, then, for
1116/// integers, ExtendKind can be used to specify how to generate the extra bits.
Dan Gohman6183f782007-07-05 20:12:34 +00001117static void getCopyToParts(SelectionDAG &DAG,
Dan Gohman475871a2008-07-27 21:46:04 +00001118 SDValue Val,
1119 SDValue *Parts,
Dan Gohman6183f782007-07-05 20:12:34 +00001120 unsigned NumParts,
Duncan Sands83ec4b62008-06-06 12:08:01 +00001121 MVT PartVT,
Duncan Sandsb988bac2008-02-11 20:58:28 +00001122 ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
Dan Gohman25ac7e82007-08-10 14:59:38 +00001123 TargetLowering &TLI = DAG.getTargetLoweringInfo();
Duncan Sands83ec4b62008-06-06 12:08:01 +00001124 MVT PtrVT = TLI.getPointerTy();
1125 MVT ValueVT = Val.getValueType();
1126 unsigned PartBits = PartVT.getSizeInBits();
Duncan Sands014e04a2008-02-12 20:46:31 +00001127 assert(TLI.isTypeLegal(PartVT) && "Copying to an illegal type!");
Dan Gohman6183f782007-07-05 20:12:34 +00001128
Duncan Sands014e04a2008-02-12 20:46:31 +00001129 if (!NumParts)
1130 return;
1131
Duncan Sands83ec4b62008-06-06 12:08:01 +00001132 if (!ValueVT.isVector()) {
Duncan Sands014e04a2008-02-12 20:46:31 +00001133 if (PartVT == ValueVT) {
1134 assert(NumParts == 1 && "No-op copy with multiple parts!");
1135 Parts[0] = Val;
Dan Gohman6183f782007-07-05 20:12:34 +00001136 return;
1137 }
1138
Duncan Sands83ec4b62008-06-06 12:08:01 +00001139 if (NumParts * PartBits > ValueVT.getSizeInBits()) {
Duncan Sands014e04a2008-02-12 20:46:31 +00001140 // If the parts cover more bits than the value has, promote the value.
Duncan Sands83ec4b62008-06-06 12:08:01 +00001141 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
Duncan Sands014e04a2008-02-12 20:46:31 +00001142 assert(NumParts == 1 && "Do not know what to promote to!");
Dan Gohman6183f782007-07-05 20:12:34 +00001143 Val = DAG.getNode(ISD::FP_EXTEND, PartVT, Val);
Duncan Sands83ec4b62008-06-06 12:08:01 +00001144 } else if (PartVT.isInteger() && ValueVT.isInteger()) {
1145 ValueVT = MVT::getIntegerVT(NumParts * PartBits);
Duncan Sands014e04a2008-02-12 20:46:31 +00001146 Val = DAG.getNode(ExtendKind, ValueVT, Val);
1147 } else {
1148 assert(0 && "Unknown mismatch!");
1149 }
Duncan Sands83ec4b62008-06-06 12:08:01 +00001150 } else if (PartBits == ValueVT.getSizeInBits()) {
Duncan Sands014e04a2008-02-12 20:46:31 +00001151 // Different types of the same size.
1152 assert(NumParts == 1 && PartVT != ValueVT);
1153 Val = DAG.getNode(ISD::BIT_CONVERT, PartVT, Val);
Duncan Sands83ec4b62008-06-06 12:08:01 +00001154 } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
Duncan Sands014e04a2008-02-12 20:46:31 +00001155 // If the parts cover less bits than value has, truncate the value.
Duncan Sands83ec4b62008-06-06 12:08:01 +00001156 if (PartVT.isInteger() && ValueVT.isInteger()) {
1157 ValueVT = MVT::getIntegerVT(NumParts * PartBits);
Duncan Sands014e04a2008-02-12 20:46:31 +00001158 Val = DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
Dan Gohman6183f782007-07-05 20:12:34 +00001159 } else {
1160 assert(0 && "Unknown mismatch!");
1161 }
1162 }
Duncan Sands014e04a2008-02-12 20:46:31 +00001163
1164 // The value may have changed - recompute ValueVT.
1165 ValueVT = Val.getValueType();
Duncan Sands83ec4b62008-06-06 12:08:01 +00001166 assert(NumParts * PartBits == ValueVT.getSizeInBits() &&
Duncan Sands014e04a2008-02-12 20:46:31 +00001167 "Failed to tile the value with PartVT!");
1168
1169 if (NumParts == 1) {
1170 assert(PartVT == ValueVT && "Type conversion failed!");
1171 Parts[0] = Val;
1172 return;
1173 }
1174
1175 // Expand the value into multiple parts.
1176 if (NumParts & (NumParts - 1)) {
1177 // The number of parts is not a power of 2. Split off and copy the tail.
Duncan Sands83ec4b62008-06-06 12:08:01 +00001178 assert(PartVT.isInteger() && ValueVT.isInteger() &&
Duncan Sands014e04a2008-02-12 20:46:31 +00001179 "Do not know what to expand to!");
1180 unsigned RoundParts = 1 << Log2_32(NumParts);
1181 unsigned RoundBits = RoundParts * PartBits;
1182 unsigned OddParts = NumParts - RoundParts;
Dan Gohman475871a2008-07-27 21:46:04 +00001183 SDValue OddVal = DAG.getNode(ISD::SRL, ValueVT, Val,
Duncan Sands014e04a2008-02-12 20:46:31 +00001184 DAG.getConstant(RoundBits,
1185 TLI.getShiftAmountTy()));
1186 getCopyToParts(DAG, OddVal, Parts + RoundParts, OddParts, PartVT);
1187 if (TLI.isBigEndian())
1188 // The odd parts were reversed by getCopyToParts - unreverse them.
1189 std::reverse(Parts + RoundParts, Parts + NumParts);
1190 NumParts = RoundParts;
Duncan Sands83ec4b62008-06-06 12:08:01 +00001191 ValueVT = MVT::getIntegerVT(NumParts * PartBits);
Duncan Sands014e04a2008-02-12 20:46:31 +00001192 Val = DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
1193 }
1194
1195 // The number of parts is a power of 2. Repeatedly bisect the value using
1196 // EXTRACT_ELEMENT.
Duncan Sands25eb0432008-03-12 20:30:08 +00001197 Parts[0] = DAG.getNode(ISD::BIT_CONVERT,
Duncan Sands83ec4b62008-06-06 12:08:01 +00001198 MVT::getIntegerVT(ValueVT.getSizeInBits()),
Duncan Sands25eb0432008-03-12 20:30:08 +00001199 Val);
Duncan Sands014e04a2008-02-12 20:46:31 +00001200 for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
1201 for (unsigned i = 0; i < NumParts; i += StepSize) {
1202 unsigned ThisBits = StepSize * PartBits / 2;
Duncan Sands83ec4b62008-06-06 12:08:01 +00001203 MVT ThisVT = MVT::getIntegerVT (ThisBits);
Dan Gohman475871a2008-07-27 21:46:04 +00001204 SDValue &Part0 = Parts[i];
1205 SDValue &Part1 = Parts[i+StepSize/2];
Duncan Sands014e04a2008-02-12 20:46:31 +00001206
Duncan Sands25eb0432008-03-12 20:30:08 +00001207 Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, ThisVT, Part0,
1208 DAG.getConstant(1, PtrVT));
1209 Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, ThisVT, Part0,
1210 DAG.getConstant(0, PtrVT));
1211
1212 if (ThisBits == PartBits && ThisVT != PartVT) {
1213 Part0 = DAG.getNode(ISD::BIT_CONVERT, PartVT, Part0);
1214 Part1 = DAG.getNode(ISD::BIT_CONVERT, PartVT, Part1);
1215 }
Duncan Sands014e04a2008-02-12 20:46:31 +00001216 }
1217 }
1218
1219 if (TLI.isBigEndian())
1220 std::reverse(Parts, Parts + NumParts);
1221
1222 return;
1223 }
1224
1225 // Vector ValueVT.
1226 if (NumParts == 1) {
1227 if (PartVT != ValueVT) {
Duncan Sands83ec4b62008-06-06 12:08:01 +00001228 if (PartVT.isVector()) {
Duncan Sands014e04a2008-02-12 20:46:31 +00001229 Val = DAG.getNode(ISD::BIT_CONVERT, PartVT, Val);
1230 } else {
Duncan Sands83ec4b62008-06-06 12:08:01 +00001231 assert(ValueVT.getVectorElementType() == PartVT &&
1232 ValueVT.getVectorNumElements() == 1 &&
Duncan Sands014e04a2008-02-12 20:46:31 +00001233 "Only trivial vector-to-scalar conversions should get here!");
1234 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, PartVT, Val,
1235 DAG.getConstant(0, PtrVT));
1236 }
1237 }
1238
Dan Gohman6183f782007-07-05 20:12:34 +00001239 Parts[0] = Val;
1240 return;
1241 }
1242
1243 // Handle a multi-element vector.
Duncan Sands83ec4b62008-06-06 12:08:01 +00001244 MVT IntermediateVT, RegisterVT;
Dan Gohman6183f782007-07-05 20:12:34 +00001245 unsigned NumIntermediates;
1246 unsigned NumRegs =
1247 DAG.getTargetLoweringInfo()
1248 .getVectorTypeBreakdown(ValueVT, IntermediateVT, NumIntermediates,
1249 RegisterVT);
Duncan Sands83ec4b62008-06-06 12:08:01 +00001250 unsigned NumElements = ValueVT.getVectorNumElements();
Dan Gohman6183f782007-07-05 20:12:34 +00001251
1252 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
Evan Cheng35213342008-05-14 20:29:30 +00001253 NumParts = NumRegs; // Silence a compiler warning.
Dan Gohman6183f782007-07-05 20:12:34 +00001254 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
1255
1256 // Split the vector into intermediate operands.
Dan Gohman475871a2008-07-27 21:46:04 +00001257 SmallVector<SDValue, 8> Ops(NumIntermediates);
Dan Gohman6183f782007-07-05 20:12:34 +00001258 for (unsigned i = 0; i != NumIntermediates; ++i)
Duncan Sands83ec4b62008-06-06 12:08:01 +00001259 if (IntermediateVT.isVector())
Dan Gohman6183f782007-07-05 20:12:34 +00001260 Ops[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR,
1261 IntermediateVT, Val,
1262 DAG.getConstant(i * (NumElements / NumIntermediates),
Dan Gohman25ac7e82007-08-10 14:59:38 +00001263 PtrVT));
Dan Gohman6183f782007-07-05 20:12:34 +00001264 else
1265 Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
1266 IntermediateVT, Val,
Dan Gohman25ac7e82007-08-10 14:59:38 +00001267 DAG.getConstant(i, PtrVT));
Dan Gohman6183f782007-07-05 20:12:34 +00001268
1269 // Split the intermediate operands into legal parts.
1270 if (NumParts == NumIntermediates) {
1271 // If the register was not expanded, promote or copy the value,
1272 // as appropriate.
1273 for (unsigned i = 0; i != NumParts; ++i)
Dan Gohman532dc2e2007-07-09 20:59:04 +00001274 getCopyToParts(DAG, Ops[i], &Parts[i], 1, PartVT);
Dan Gohman6183f782007-07-05 20:12:34 +00001275 } else if (NumParts > 0) {
1276 // If the intermediate type was expanded, split each the value into
1277 // legal parts.
1278 assert(NumParts % NumIntermediates == 0 &&
1279 "Must expand into a divisible number of parts!");
1280 unsigned Factor = NumParts / NumIntermediates;
1281 for (unsigned i = 0; i != NumIntermediates; ++i)
Dan Gohman532dc2e2007-07-09 20:59:04 +00001282 getCopyToParts(DAG, Ops[i], &Parts[i * Factor], Factor, PartVT);
Dan Gohman6183f782007-07-05 20:12:34 +00001283 }
1284}
1285
1286
Dan Gohman475871a2008-07-27 21:46:04 +00001287SDValue SelectionDAGLowering::getValue(const Value *V) {
1288 SDValue &N = NodeMap[V];
Gabor Greifba36cb52008-08-28 21:40:38 +00001289 if (N.getNode()) return N;
Chris Lattner199862b2006-03-16 19:57:50 +00001290
Chris Lattner199862b2006-03-16 19:57:50 +00001291 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V))) {
Duncan Sands83ec4b62008-06-06 12:08:01 +00001292 MVT VT = TLI.getValueType(V->getType(), true);
Chris Lattnerb606dba2008-04-28 06:44:42 +00001293
1294 if (ConstantInt *CI = dyn_cast<ConstantInt>(C))
1295 return N = DAG.getConstant(CI->getValue(), VT);
1296
1297 if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
Chris Lattner199862b2006-03-16 19:57:50 +00001298 return N = DAG.getGlobalAddress(GV, VT);
Chris Lattnerb606dba2008-04-28 06:44:42 +00001299
1300 if (isa<ConstantPointerNull>(C))
Chris Lattner199862b2006-03-16 19:57:50 +00001301 return N = DAG.getConstant(0, TLI.getPointerTy());
Chris Lattnerb606dba2008-04-28 06:44:42 +00001302
1303 if (ConstantFP *CFP = dyn_cast<ConstantFP>(C))
1304 return N = DAG.getConstantFP(CFP->getValueAPF(), VT);
1305
Dan Gohman1d685a42008-06-07 02:02:36 +00001306 if (isa<UndefValue>(C) && !isa<VectorType>(V->getType()) &&
1307 !V->getType()->isAggregateType())
Chris Lattner6833b062008-04-28 07:16:35 +00001308 return N = DAG.getNode(ISD::UNDEF, VT);
Chris Lattnerb606dba2008-04-28 06:44:42 +00001309
1310 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
1311 visit(CE->getOpcode(), *CE);
Dan Gohman475871a2008-07-27 21:46:04 +00001312 SDValue N1 = NodeMap[V];
Gabor Greifba36cb52008-08-28 21:40:38 +00001313 assert(N1.getNode() && "visit didn't populate the ValueMap!");
Chris Lattnerb606dba2008-04-28 06:44:42 +00001314 return N1;
1315 }
1316
Dan Gohman1d685a42008-06-07 02:02:36 +00001317 if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
Dan Gohman475871a2008-07-27 21:46:04 +00001318 SmallVector<SDValue, 4> Constants;
Dan Gohman1d685a42008-06-07 02:02:36 +00001319 for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end();
1320 OI != OE; ++OI) {
Gabor Greifba36cb52008-08-28 21:40:38 +00001321 SDNode *Val = getValue(*OI).getNode();
Duncan Sands4bdcb612008-07-02 17:40:58 +00001322 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
Dan Gohman475871a2008-07-27 21:46:04 +00001323 Constants.push_back(SDValue(Val, i));
Dan Gohman1d685a42008-06-07 02:02:36 +00001324 }
Duncan Sands4bdcb612008-07-02 17:40:58 +00001325 return DAG.getMergeValues(&Constants[0], Constants.size());
Dan Gohman1d685a42008-06-07 02:02:36 +00001326 }
1327
Dan Gohman1f565bc2008-08-04 23:30:41 +00001328 if (isa<StructType>(C->getType()) || isa<ArrayType>(C->getType())) {
Dan Gohman1d685a42008-06-07 02:02:36 +00001329 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
Dan Gohman1f565bc2008-08-04 23:30:41 +00001330 "Unknown struct or array constant!");
Dan Gohman1d685a42008-06-07 02:02:36 +00001331
Dan Gohman1f565bc2008-08-04 23:30:41 +00001332 SmallVector<MVT, 4> ValueVTs;
1333 ComputeValueVTs(TLI, C->getType(), ValueVTs);
1334 unsigned NumElts = ValueVTs.size();
Dan Gohman8a6ccb52008-06-09 15:21:47 +00001335 if (NumElts == 0)
Dan Gohman475871a2008-07-27 21:46:04 +00001336 return SDValue(); // empty struct
1337 SmallVector<SDValue, 4> Constants(NumElts);
Dan Gohman1f565bc2008-08-04 23:30:41 +00001338 for (unsigned i = 0; i != NumElts; ++i) {
1339 MVT EltVT = ValueVTs[i];
Dan Gohman1d685a42008-06-07 02:02:36 +00001340 if (isa<UndefValue>(C))
1341 Constants[i] = DAG.getNode(ISD::UNDEF, EltVT);
1342 else if (EltVT.isFloatingPoint())
1343 Constants[i] = DAG.getConstantFP(0, EltVT);
1344 else
1345 Constants[i] = DAG.getConstant(0, EltVT);
1346 }
Dan Gohman1f565bc2008-08-04 23:30:41 +00001347 return DAG.getMergeValues(&Constants[0], NumElts);
Dan Gohman1d685a42008-06-07 02:02:36 +00001348 }
1349
Chris Lattner6833b062008-04-28 07:16:35 +00001350 const VectorType *VecTy = cast<VectorType>(V->getType());
Chris Lattnerb606dba2008-04-28 06:44:42 +00001351 unsigned NumElements = VecTy->getNumElements();
Chris Lattnerb606dba2008-04-28 06:44:42 +00001352
Chris Lattner6833b062008-04-28 07:16:35 +00001353 // Now that we know the number and type of the elements, get that number of
1354 // elements into the Ops array based on what kind of constant it is.
Dan Gohman475871a2008-07-27 21:46:04 +00001355 SmallVector<SDValue, 16> Ops;
Chris Lattnerb606dba2008-04-28 06:44:42 +00001356 if (ConstantVector *CP = dyn_cast<ConstantVector>(C)) {
1357 for (unsigned i = 0; i != NumElements; ++i)
1358 Ops.push_back(getValue(CP->getOperand(i)));
1359 } else {
Chris Lattner6833b062008-04-28 07:16:35 +00001360 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
1361 "Unknown vector constant!");
Duncan Sands83ec4b62008-06-06 12:08:01 +00001362 MVT EltVT = TLI.getValueType(VecTy->getElementType());
Chris Lattner6833b062008-04-28 07:16:35 +00001363
Dan Gohman475871a2008-07-27 21:46:04 +00001364 SDValue Op;
Chris Lattner6833b062008-04-28 07:16:35 +00001365 if (isa<UndefValue>(C))
1366 Op = DAG.getNode(ISD::UNDEF, EltVT);
Duncan Sands83ec4b62008-06-06 12:08:01 +00001367 else if (EltVT.isFloatingPoint())
Chris Lattner6833b062008-04-28 07:16:35 +00001368 Op = DAG.getConstantFP(0, EltVT);
Chris Lattnerb606dba2008-04-28 06:44:42 +00001369 else
Chris Lattner6833b062008-04-28 07:16:35 +00001370 Op = DAG.getConstant(0, EltVT);
Chris Lattnerb606dba2008-04-28 06:44:42 +00001371 Ops.assign(NumElements, Op);
1372 }
1373
1374 // Create a BUILD_VECTOR node.
1375 return NodeMap[V] = DAG.getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
Chris Lattner199862b2006-03-16 19:57:50 +00001376 }
1377
Chris Lattnerb606dba2008-04-28 06:44:42 +00001378 // If this is a static alloca, generate it as the frameindex instead of
1379 // computation.
Chris Lattner199862b2006-03-16 19:57:50 +00001380 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
Dan Gohman6ecf5092008-08-23 02:44:46 +00001381 DenseMap<const AllocaInst*, int>::iterator SI =
Chris Lattnerb606dba2008-04-28 06:44:42 +00001382 FuncInfo.StaticAllocaMap.find(AI);
Chris Lattner199862b2006-03-16 19:57:50 +00001383 if (SI != FuncInfo.StaticAllocaMap.end())
1384 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
1385 }
1386
Chris Lattner251db182007-02-25 18:40:32 +00001387 unsigned InReg = FuncInfo.ValueMap[V];
1388 assert(InReg && "Value not in map!");
Chris Lattner199862b2006-03-16 19:57:50 +00001389
Chris Lattner6833b062008-04-28 07:16:35 +00001390 RegsForValue RFV(TLI, InReg, V->getType());
Dan Gohman475871a2008-07-27 21:46:04 +00001391 SDValue Chain = DAG.getEntryNode();
Dan Gohmanb6f5b002007-06-28 23:29:44 +00001392 return RFV.getCopyFromRegs(DAG, Chain, NULL);
Chris Lattner199862b2006-03-16 19:57:50 +00001393}
1394
1395
Chris Lattner1c08c712005-01-07 07:47:53 +00001396void SelectionDAGLowering::visitRet(ReturnInst &I) {
1397 if (I.getNumOperands() == 0) {
Dan Gohman86e1ebf2008-03-27 19:56:19 +00001398 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getControlRoot()));
Chris Lattner1c08c712005-01-07 07:47:53 +00001399 return;
1400 }
Chris Lattnerb606dba2008-04-28 06:44:42 +00001401
Dan Gohman475871a2008-07-27 21:46:04 +00001402 SmallVector<SDValue, 8> NewValues;
Dan Gohman86e1ebf2008-03-27 19:56:19 +00001403 NewValues.push_back(getControlRoot());
1404 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
Dan Gohman475871a2008-07-27 21:46:04 +00001405 SDValue RetOp = getValue(I.getOperand(i));
Duncan Sandsb988bac2008-02-11 20:58:28 +00001406
Dan Gohmanab8ec0a2008-06-20 01:29:26 +00001407 SmallVector<MVT, 4> ValueVTs;
1408 ComputeValueVTs(TLI, I.getOperand(i)->getType(), ValueVTs);
1409 for (unsigned j = 0, f = ValueVTs.size(); j != f; ++j) {
1410 MVT VT = ValueVTs[j];
Duncan Sandsb988bac2008-02-11 20:58:28 +00001411
Dan Gohmanab8ec0a2008-06-20 01:29:26 +00001412 // FIXME: C calling convention requires the return type to be promoted to
1413 // at least 32-bit. But this is not necessary for non-C calling conventions.
1414 if (VT.isInteger()) {
1415 MVT MinVT = TLI.getRegisterType(MVT::i32);
1416 if (VT.bitsLT(MinVT))
1417 VT = MinVT;
1418 }
Duncan Sandsb988bac2008-02-11 20:58:28 +00001419
Dan Gohmanab8ec0a2008-06-20 01:29:26 +00001420 unsigned NumParts = TLI.getNumRegisters(VT);
1421 MVT PartVT = TLI.getRegisterType(VT);
Dan Gohman475871a2008-07-27 21:46:04 +00001422 SmallVector<SDValue, 4> Parts(NumParts);
Dan Gohmanab8ec0a2008-06-20 01:29:26 +00001423 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
1424
1425 const Function *F = I.getParent()->getParent();
1426 if (F->paramHasAttr(0, ParamAttr::SExt))
1427 ExtendKind = ISD::SIGN_EXTEND;
1428 else if (F->paramHasAttr(0, ParamAttr::ZExt))
1429 ExtendKind = ISD::ZERO_EXTEND;
Duncan Sandsb988bac2008-02-11 20:58:28 +00001430
Gabor Greifba36cb52008-08-28 21:40:38 +00001431 getCopyToParts(DAG, SDValue(RetOp.getNode(), RetOp.getResNo() + j),
Dan Gohmanab8ec0a2008-06-20 01:29:26 +00001432 &Parts[0], NumParts, PartVT, ExtendKind);
Duncan Sandsb988bac2008-02-11 20:58:28 +00001433
Dan Gohmanab8ec0a2008-06-20 01:29:26 +00001434 for (unsigned i = 0; i < NumParts; ++i) {
1435 NewValues.push_back(Parts[i]);
1436 NewValues.push_back(DAG.getArgFlags(ISD::ArgFlagsTy()));
1437 }
Nate Begemanee625572006-01-27 21:09:22 +00001438 }
Chris Lattner1c08c712005-01-07 07:47:53 +00001439 }
Chris Lattnerbd564bf2006-08-08 02:23:42 +00001440 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other,
1441 &NewValues[0], NewValues.size()));
Chris Lattner1c08c712005-01-07 07:47:53 +00001442}
1443
Chris Lattner571e4342006-10-27 21:36:01 +00001444/// ExportFromCurrentBlock - If this condition isn't known to be exported from
1445/// the current basic block, add it to ValueMap now so that we'll get a
1446/// CopyTo/FromReg.
1447void SelectionDAGLowering::ExportFromCurrentBlock(Value *V) {
1448 // No need to export constants.
1449 if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
1450
1451 // Already exported?
1452 if (FuncInfo.isExportedInst(V)) return;
1453
1454 unsigned Reg = FuncInfo.InitializeRegForValue(V);
Dan Gohman86e1ebf2008-03-27 19:56:19 +00001455 CopyValueToVirtualRegister(V, Reg);
Chris Lattner571e4342006-10-27 21:36:01 +00001456}
1457
Chris Lattner8c494ab2006-10-27 23:50:33 +00001458bool SelectionDAGLowering::isExportableFromCurrentBlock(Value *V,
1459 const BasicBlock *FromBB) {
1460 // The operands of the setcc have to be in this block. We don't know
1461 // how to export them from some other block.
1462 if (Instruction *VI = dyn_cast<Instruction>(V)) {
1463 // Can export from current BB.
1464 if (VI->getParent() == FromBB)
1465 return true;
1466
1467 // Is already exported, noop.
1468 return FuncInfo.isExportedInst(V);
1469 }
1470
1471 // If this is an argument, we can export it if the BB is the entry block or
1472 // if it is already exported.
1473 if (isa<Argument>(V)) {
1474 if (FromBB == &FromBB->getParent()->getEntryBlock())
1475 return true;
1476
1477 // Otherwise, can only export this if it is already exported.
1478 return FuncInfo.isExportedInst(V);
1479 }
1480
1481 // Otherwise, constants can always be exported.
1482 return true;
1483}
1484
Chris Lattner6a586c82006-10-29 21:01:20 +00001485static bool InBlock(const Value *V, const BasicBlock *BB) {
1486 if (const Instruction *I = dyn_cast<Instruction>(V))
1487 return I->getParent() == BB;
1488 return true;
1489}
1490
Chris Lattner571e4342006-10-27 21:36:01 +00001491/// FindMergedConditions - If Cond is an expression like
1492void SelectionDAGLowering::FindMergedConditions(Value *Cond,
1493 MachineBasicBlock *TBB,
1494 MachineBasicBlock *FBB,
1495 MachineBasicBlock *CurBB,
1496 unsigned Opc) {
Chris Lattner571e4342006-10-27 21:36:01 +00001497 // If this node is not part of the or/and tree, emit it as a branch.
Reid Spencere4d87aa2006-12-23 06:05:41 +00001498 Instruction *BOp = dyn_cast<Instruction>(Cond);
Chris Lattner571e4342006-10-27 21:36:01 +00001499
Reid Spencere4d87aa2006-12-23 06:05:41 +00001500 if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
1501 (unsigned)BOp->getOpcode() != Opc || !BOp->hasOneUse() ||
Chris Lattner6a586c82006-10-29 21:01:20 +00001502 BOp->getParent() != CurBB->getBasicBlock() ||
1503 !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
1504 !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
Chris Lattner571e4342006-10-27 21:36:01 +00001505 const BasicBlock *BB = CurBB->getBasicBlock();
1506
Reid Spencere4d87aa2006-12-23 06:05:41 +00001507 // If the leaf of the tree is a comparison, merge the condition into
1508 // the caseblock.
1509 if ((isa<ICmpInst>(Cond) || isa<FCmpInst>(Cond)) &&
1510 // The operands of the cmp have to be in this block. We don't know
Chris Lattner5a145f02006-10-29 18:23:37 +00001511 // how to export them from some other block. If this is the first block
1512 // of the sequence, no exporting is needed.
1513 (CurBB == CurMBB ||
1514 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
1515 isExportableFromCurrentBlock(BOp->getOperand(1), BB)))) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00001516 BOp = cast<Instruction>(Cond);
1517 ISD::CondCode Condition;
1518 if (ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
1519 switch (IC->getPredicate()) {
1520 default: assert(0 && "Unknown icmp predicate opcode!");
1521 case ICmpInst::ICMP_EQ: Condition = ISD::SETEQ; break;
1522 case ICmpInst::ICMP_NE: Condition = ISD::SETNE; break;
1523 case ICmpInst::ICMP_SLE: Condition = ISD::SETLE; break;
1524 case ICmpInst::ICMP_ULE: Condition = ISD::SETULE; break;
1525 case ICmpInst::ICMP_SGE: Condition = ISD::SETGE; break;
1526 case ICmpInst::ICMP_UGE: Condition = ISD::SETUGE; break;
1527 case ICmpInst::ICMP_SLT: Condition = ISD::SETLT; break;
1528 case ICmpInst::ICMP_ULT: Condition = ISD::SETULT; break;
1529 case ICmpInst::ICMP_SGT: Condition = ISD::SETGT; break;
1530 case ICmpInst::ICMP_UGT: Condition = ISD::SETUGT; break;
1531 }
1532 } else if (FCmpInst *FC = dyn_cast<FCmpInst>(Cond)) {
1533 ISD::CondCode FPC, FOC;
1534 switch (FC->getPredicate()) {
1535 default: assert(0 && "Unknown fcmp predicate opcode!");
1536 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
1537 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
1538 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
1539 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
1540 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
1541 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
1542 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
Chris Lattner6bf30ab2008-05-01 07:26:11 +00001543 case FCmpInst::FCMP_ORD: FOC = FPC = ISD::SETO; break;
1544 case FCmpInst::FCMP_UNO: FOC = FPC = ISD::SETUO; break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00001545 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
1546 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
1547 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
1548 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
1549 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
1550 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
1551 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
1552 }
1553 if (FiniteOnlyFPMath())
1554 Condition = FOC;
1555 else
1556 Condition = FPC;
1557 } else {
Chris Lattner0da331f2007-02-04 01:31:47 +00001558 Condition = ISD::SETEQ; // silence warning.
Reid Spencere4d87aa2006-12-23 06:05:41 +00001559 assert(0 && "Unknown compare instruction");
Chris Lattner571e4342006-10-27 21:36:01 +00001560 }
1561
Dan Gohman7c3234c2008-08-27 23:52:12 +00001562 CaseBlock CB(Condition, BOp->getOperand(0),
1563 BOp->getOperand(1), NULL, TBB, FBB, CurBB);
Chris Lattner571e4342006-10-27 21:36:01 +00001564 SwitchCases.push_back(CB);
1565 return;
1566 }
1567
1568 // Create a CaseBlock record representing this branch.
Dan Gohman7c3234c2008-08-27 23:52:12 +00001569 CaseBlock CB(ISD::SETEQ, Cond, ConstantInt::getTrue(),
1570 NULL, TBB, FBB, CurBB);
Chris Lattner571e4342006-10-27 21:36:01 +00001571 SwitchCases.push_back(CB);
Chris Lattner571e4342006-10-27 21:36:01 +00001572 return;
1573 }
1574
Chris Lattnerd2f9ee92006-10-27 21:54:23 +00001575
1576 // Create TmpBB after CurBB.
Chris Lattner571e4342006-10-27 21:36:01 +00001577 MachineFunction::iterator BBI = CurBB;
Dan Gohman0e5f1302008-07-07 23:02:41 +00001578 MachineFunction &MF = DAG.getMachineFunction();
1579 MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
1580 CurBB->getParent()->insert(++BBI, TmpBB);
Chris Lattner571e4342006-10-27 21:36:01 +00001581
Chris Lattnerd2f9ee92006-10-27 21:54:23 +00001582 if (Opc == Instruction::Or) {
1583 // Codegen X | Y as:
1584 // jmp_if_X TBB
1585 // jmp TmpBB
1586 // TmpBB:
1587 // jmp_if_Y TBB
1588 // jmp FBB
1589 //
Chris Lattner571e4342006-10-27 21:36:01 +00001590
Chris Lattnerd2f9ee92006-10-27 21:54:23 +00001591 // Emit the LHS condition.
1592 FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, Opc);
1593
1594 // Emit the RHS condition into TmpBB.
1595 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
1596 } else {
1597 assert(Opc == Instruction::And && "Unknown merge op!");
1598 // Codegen X & Y as:
1599 // jmp_if_X TmpBB
1600 // jmp FBB
1601 // TmpBB:
1602 // jmp_if_Y TBB
1603 // jmp FBB
1604 //
1605 // This requires creation of TmpBB after CurBB.
1606
1607 // Emit the LHS condition.
1608 FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, Opc);
1609
1610 // Emit the RHS condition into TmpBB.
1611 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
1612 }
Chris Lattner571e4342006-10-27 21:36:01 +00001613}
1614
Chris Lattnerdf19f272006-10-31 22:37:42 +00001615/// If the set of cases should be emitted as a series of branches, return true.
1616/// If we should emit this as a bunch of and/or'd together conditions, return
1617/// false.
Dan Gohman9ffd8b52008-08-28 20:38:18 +00001618bool
1619SelectionDAGLowering::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases){
Chris Lattnerdf19f272006-10-31 22:37:42 +00001620 if (Cases.size() != 2) return true;
1621
Chris Lattner0ccb5002006-10-31 23:06:00 +00001622 // If this is two comparisons of the same values or'd or and'd together, they
1623 // will get folded into a single comparison, so don't emit two blocks.
1624 if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
1625 Cases[0].CmpRHS == Cases[1].CmpRHS) ||
1626 (Cases[0].CmpRHS == Cases[1].CmpLHS &&
1627 Cases[0].CmpLHS == Cases[1].CmpRHS)) {
1628 return false;
1629 }
1630
Chris Lattnerdf19f272006-10-31 22:37:42 +00001631 return true;
1632}
1633
Chris Lattner1c08c712005-01-07 07:47:53 +00001634void SelectionDAGLowering::visitBr(BranchInst &I) {
1635 // Update machine-CFG edges.
1636 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
Chris Lattner1c08c712005-01-07 07:47:53 +00001637
1638 // Figure out which block is immediately after the current one.
1639 MachineBasicBlock *NextBlock = 0;
1640 MachineFunction::iterator BBI = CurMBB;
1641 if (++BBI != CurMBB->getParent()->end())
1642 NextBlock = BBI;
1643
1644 if (I.isUnconditional()) {
Owen Anderson2d389e82008-06-07 00:00:23 +00001645 // Update machine-CFG edges.
1646 CurMBB->addSuccessor(Succ0MBB);
1647
Chris Lattner1c08c712005-01-07 07:47:53 +00001648 // If this is not a fall-through branch, emit the branch.
1649 if (Succ0MBB != NextBlock)
Dan Gohman86e1ebf2008-03-27 19:56:19 +00001650 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getControlRoot(),
Misha Brukmandedf2bd2005-04-22 04:01:18 +00001651 DAG.getBasicBlock(Succ0MBB)));
Chris Lattner57ab6592006-10-24 17:57:59 +00001652 return;
1653 }
1654
1655 // If this condition is one of the special cases we handle, do special stuff
1656 // now.
1657 Value *CondVal = I.getCondition();
Chris Lattner57ab6592006-10-24 17:57:59 +00001658 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
Chris Lattner571e4342006-10-27 21:36:01 +00001659
1660 // If this is a series of conditions that are or'd or and'd together, emit
1661 // this as a sequence of branches instead of setcc's with and/or operations.
1662 // For example, instead of something like:
1663 // cmp A, B
1664 // C = seteq
1665 // cmp D, E
1666 // F = setle
1667 // or C, F
1668 // jnz foo
1669 // Emit:
1670 // cmp A, B
1671 // je foo
1672 // cmp D, E
1673 // jle foo
1674 //
1675 if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
1676 if (BOp->hasOneUse() &&
Chris Lattnerd2f9ee92006-10-27 21:54:23 +00001677 (BOp->getOpcode() == Instruction::And ||
Chris Lattner571e4342006-10-27 21:36:01 +00001678 BOp->getOpcode() == Instruction::Or)) {
1679 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, CurMBB, BOp->getOpcode());
Chris Lattner0ccb5002006-10-31 23:06:00 +00001680 // If the compares in later blocks need to use values not currently
1681 // exported from this block, export them now. This block should always
1682 // be the first entry.
1683 assert(SwitchCases[0].ThisBB == CurMBB && "Unexpected lowering!");
1684
Chris Lattnerdf19f272006-10-31 22:37:42 +00001685 // Allow some cases to be rejected.
1686 if (ShouldEmitAsBranches(SwitchCases)) {
Chris Lattnerdf19f272006-10-31 22:37:42 +00001687 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
1688 ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
1689 ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
1690 }
1691
1692 // Emit the branch for this block.
1693 visitSwitchCase(SwitchCases[0]);
1694 SwitchCases.erase(SwitchCases.begin());
1695 return;
Chris Lattner5a145f02006-10-29 18:23:37 +00001696 }
1697
Chris Lattner0ccb5002006-10-31 23:06:00 +00001698 // Okay, we decided not to do this, remove any inserted MBB's and clear
1699 // SwitchCases.
1700 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
Dan Gohman0e5f1302008-07-07 23:02:41 +00001701 CurMBB->getParent()->erase(SwitchCases[i].ThisBB);
Chris Lattner0ccb5002006-10-31 23:06:00 +00001702
Chris Lattnerdf19f272006-10-31 22:37:42 +00001703 SwitchCases.clear();
Chris Lattner571e4342006-10-27 21:36:01 +00001704 }
1705 }
Chris Lattner24525952006-10-24 18:07:37 +00001706
1707 // Create a CaseBlock record representing this branch.
Dan Gohman7c3234c2008-08-27 23:52:12 +00001708 CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(),
1709 NULL, Succ0MBB, Succ1MBB, CurMBB);
Chris Lattner24525952006-10-24 18:07:37 +00001710 // Use visitSwitchCase to actually insert the fast branch sequence for this
1711 // cond branch.
1712 visitSwitchCase(CB);
Chris Lattner1c08c712005-01-07 07:47:53 +00001713}
1714
Nate Begemanf15485a2006-03-27 01:32:24 +00001715/// visitSwitchCase - Emits the necessary code to represent a single node in
1716/// the binary search tree resulting from lowering a switch instruction.
Dan Gohman7c3234c2008-08-27 23:52:12 +00001717void SelectionDAGLowering::visitSwitchCase(CaseBlock &CB) {
Dan Gohman475871a2008-07-27 21:46:04 +00001718 SDValue Cond;
1719 SDValue CondLHS = getValue(CB.CmpLHS);
Chris Lattner57ab6592006-10-24 17:57:59 +00001720
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001721 // Build the setcc now.
1722 if (CB.CmpMHS == NULL) {
1723 // Fold "(X == true)" to X and "(X == false)" to !X to
1724 // handle common cases produced by branch lowering.
1725 if (CB.CmpRHS == ConstantInt::getTrue() && CB.CC == ISD::SETEQ)
1726 Cond = CondLHS;
1727 else if (CB.CmpRHS == ConstantInt::getFalse() && CB.CC == ISD::SETEQ) {
Dan Gohman475871a2008-07-27 21:46:04 +00001728 SDValue True = DAG.getConstant(1, CondLHS.getValueType());
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001729 Cond = DAG.getNode(ISD::XOR, CondLHS.getValueType(), CondLHS, True);
1730 } else
1731 Cond = DAG.getSetCC(MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
1732 } else {
1733 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001734
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001735 uint64_t Low = cast<ConstantInt>(CB.CmpLHS)->getSExtValue();
1736 uint64_t High = cast<ConstantInt>(CB.CmpRHS)->getSExtValue();
1737
Dan Gohman475871a2008-07-27 21:46:04 +00001738 SDValue CmpOp = getValue(CB.CmpMHS);
Duncan Sands83ec4b62008-06-06 12:08:01 +00001739 MVT VT = CmpOp.getValueType();
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001740
1741 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
1742 Cond = DAG.getSetCC(MVT::i1, CmpOp, DAG.getConstant(High, VT), ISD::SETLE);
1743 } else {
Dan Gohman475871a2008-07-27 21:46:04 +00001744 SDValue SUB = DAG.getNode(ISD::SUB, VT, CmpOp, DAG.getConstant(Low, VT));
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001745 Cond = DAG.getSetCC(MVT::i1, SUB,
1746 DAG.getConstant(High-Low, VT), ISD::SETULE);
1747 }
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001748 }
1749
Owen Anderson2d389e82008-06-07 00:00:23 +00001750 // Update successor info
1751 CurMBB->addSuccessor(CB.TrueBB);
1752 CurMBB->addSuccessor(CB.FalseBB);
1753
Nate Begemanf15485a2006-03-27 01:32:24 +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 // If the lhs block is the next block, invert the condition so that we can
1762 // fall through to the lhs instead of the rhs block.
Chris Lattner57ab6592006-10-24 17:57:59 +00001763 if (CB.TrueBB == NextBlock) {
1764 std::swap(CB.TrueBB, CB.FalseBB);
Dan Gohman475871a2008-07-27 21:46:04 +00001765 SDValue True = DAG.getConstant(1, Cond.getValueType());
Nate Begemanf15485a2006-03-27 01:32:24 +00001766 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
1767 }
Dan Gohman475871a2008-07-27 21:46:04 +00001768 SDValue BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, getControlRoot(), Cond,
Chris Lattner57ab6592006-10-24 17:57:59 +00001769 DAG.getBasicBlock(CB.TrueBB));
Owen Andersonbd3ba462008-08-04 23:54:43 +00001770
1771 // If the branch was constant folded, fix up the CFG.
1772 if (BrCond.getOpcode() == ISD::BR) {
Owen Anderson3bc9c6f2008-08-05 18:27:54 +00001773 CurMBB->removeSuccessor(CB.FalseBB);
Nate Begemanf15485a2006-03-27 01:32:24 +00001774 DAG.setRoot(BrCond);
Owen Andersonbd3ba462008-08-04 23:54:43 +00001775 } else {
1776 // Otherwise, go ahead and insert the false branch.
1777 if (BrCond == getControlRoot())
Owen Anderson3bc9c6f2008-08-05 18:27:54 +00001778 CurMBB->removeSuccessor(CB.TrueBB);
Owen Andersonbd3ba462008-08-04 23:54:43 +00001779
1780 if (CB.FalseBB == NextBlock)
1781 DAG.setRoot(BrCond);
1782 else
1783 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond,
1784 DAG.getBasicBlock(CB.FalseBB)));
1785 }
Nate Begemanf15485a2006-03-27 01:32:24 +00001786}
1787
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001788/// visitJumpTable - Emit JumpTable node in the current MBB
Dan Gohman7c3234c2008-08-27 23:52:12 +00001789void SelectionDAGLowering::visitJumpTable(JumpTable &JT) {
Nate Begeman37efe672006-04-22 18:53:45 +00001790 // Emit the code for the jump table
Scott Michelf147a8d2007-04-24 01:24:20 +00001791 assert(JT.Reg != -1U && "Should lower JT Header first!");
Duncan Sands83ec4b62008-06-06 12:08:01 +00001792 MVT PTy = TLI.getPointerTy();
Dan Gohman475871a2008-07-27 21:46:04 +00001793 SDValue Index = DAG.getCopyFromReg(getControlRoot(), JT.Reg, PTy);
1794 SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
Evan Cheng3d4ce112006-10-30 08:00:44 +00001795 DAG.setRoot(DAG.getNode(ISD::BR_JT, MVT::Other, Index.getValue(1),
1796 Table, Index));
1797 return;
Nate Begeman37efe672006-04-22 18:53:45 +00001798}
1799
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001800/// visitJumpTableHeader - This function emits necessary code to produce index
1801/// in the JumpTable from switch case.
Dan Gohman7c3234c2008-08-27 23:52:12 +00001802void SelectionDAGLowering::visitJumpTableHeader(JumpTable &JT,
1803 JumpTableHeader &JTH) {
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001804 // Subtract the lowest switch case value from the value being switched on
1805 // and conditional branch to default mbb if the result is greater than the
1806 // difference between smallest and largest cases.
Dan Gohman475871a2008-07-27 21:46:04 +00001807 SDValue SwitchOp = getValue(JTH.SValue);
Duncan Sands83ec4b62008-06-06 12:08:01 +00001808 MVT VT = SwitchOp.getValueType();
Dan Gohman475871a2008-07-27 21:46:04 +00001809 SDValue SUB = DAG.getNode(ISD::SUB, VT, SwitchOp,
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001810 DAG.getConstant(JTH.First, VT));
1811
1812 // The SDNode we just created, which holds the value being switched on
1813 // minus the the smallest case value, needs to be copied to a virtual
1814 // register so it can be used as an index into the jump table in a
1815 // subsequent basic block. This value may be smaller or larger than the
1816 // target's pointer type, and therefore require extension or truncating.
Duncan Sands8e4eb092008-06-08 20:54:56 +00001817 if (VT.bitsGT(TLI.getPointerTy()))
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001818 SwitchOp = DAG.getNode(ISD::TRUNCATE, TLI.getPointerTy(), SUB);
1819 else
1820 SwitchOp = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(), SUB);
1821
1822 unsigned JumpTableReg = FuncInfo.MakeReg(TLI.getPointerTy());
Dan Gohman475871a2008-07-27 21:46:04 +00001823 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), JumpTableReg, SwitchOp);
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001824 JT.Reg = JumpTableReg;
1825
1826 // Emit the range check for the jump table, and branch to the default
1827 // block for the switch statement if the value being switched on exceeds
1828 // the largest case in the switch.
Dan Gohman475871a2008-07-27 21:46:04 +00001829 SDValue CMP = DAG.getSetCC(TLI.getSetCCResultType(SUB), SUB,
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001830 DAG.getConstant(JTH.Last-JTH.First,VT),
1831 ISD::SETUGT);
1832
1833 // Set NextBlock to be the MBB immediately after the current one, if any.
1834 // This is used to avoid emitting unnecessary branches to the next block.
1835 MachineBasicBlock *NextBlock = 0;
1836 MachineFunction::iterator BBI = CurMBB;
1837 if (++BBI != CurMBB->getParent()->end())
1838 NextBlock = BBI;
1839
Dan Gohman475871a2008-07-27 21:46:04 +00001840 SDValue BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, CopyTo, CMP,
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001841 DAG.getBasicBlock(JT.Default));
1842
1843 if (JT.MBB == NextBlock)
1844 DAG.setRoot(BrCond);
1845 else
1846 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond,
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001847 DAG.getBasicBlock(JT.MBB)));
1848
1849 return;
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001850}
1851
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001852/// visitBitTestHeader - This function emits necessary code to produce value
1853/// suitable for "bit tests"
Dan Gohman7c3234c2008-08-27 23:52:12 +00001854void SelectionDAGLowering::visitBitTestHeader(BitTestBlock &B) {
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001855 // Subtract the minimum value
Dan Gohman475871a2008-07-27 21:46:04 +00001856 SDValue SwitchOp = getValue(B.SValue);
Duncan Sands83ec4b62008-06-06 12:08:01 +00001857 MVT VT = SwitchOp.getValueType();
Dan Gohman475871a2008-07-27 21:46:04 +00001858 SDValue SUB = DAG.getNode(ISD::SUB, VT, SwitchOp,
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001859 DAG.getConstant(B.First, VT));
1860
1861 // Check range
Dan Gohman475871a2008-07-27 21:46:04 +00001862 SDValue RangeCmp = DAG.getSetCC(TLI.getSetCCResultType(SUB), SUB,
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001863 DAG.getConstant(B.Range, VT),
1864 ISD::SETUGT);
1865
Dan Gohman475871a2008-07-27 21:46:04 +00001866 SDValue ShiftOp;
Duncan Sands8e4eb092008-06-08 20:54:56 +00001867 if (VT.bitsGT(TLI.getShiftAmountTy()))
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001868 ShiftOp = DAG.getNode(ISD::TRUNCATE, TLI.getShiftAmountTy(), SUB);
1869 else
1870 ShiftOp = DAG.getNode(ISD::ZERO_EXTEND, TLI.getShiftAmountTy(), SUB);
1871
1872 // Make desired shift
Dan Gohman475871a2008-07-27 21:46:04 +00001873 SDValue SwitchVal = DAG.getNode(ISD::SHL, TLI.getPointerTy(),
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001874 DAG.getConstant(1, TLI.getPointerTy()),
1875 ShiftOp);
1876
1877 unsigned SwitchReg = FuncInfo.MakeReg(TLI.getPointerTy());
Dan Gohman475871a2008-07-27 21:46:04 +00001878 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), SwitchReg, SwitchVal);
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001879 B.Reg = SwitchReg;
1880
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001881 // Set NextBlock to be the MBB immediately after the current one, if any.
1882 // This is used to avoid emitting unnecessary branches to the next block.
1883 MachineBasicBlock *NextBlock = 0;
1884 MachineFunction::iterator BBI = CurMBB;
1885 if (++BBI != CurMBB->getParent()->end())
1886 NextBlock = BBI;
1887
1888 MachineBasicBlock* MBB = B.Cases[0].ThisBB;
Owen Anderson2d389e82008-06-07 00:00:23 +00001889
1890 CurMBB->addSuccessor(B.Default);
1891 CurMBB->addSuccessor(MBB);
1892
Dan Gohman475871a2008-07-27 21:46:04 +00001893 SDValue BrRange = DAG.getNode(ISD::BRCOND, MVT::Other, CopyTo, RangeCmp,
Owen Anderson2d389e82008-06-07 00:00:23 +00001894 DAG.getBasicBlock(B.Default));
1895
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001896 if (MBB == NextBlock)
1897 DAG.setRoot(BrRange);
1898 else
1899 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, CopyTo,
1900 DAG.getBasicBlock(MBB)));
1901
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001902 return;
1903}
1904
1905/// visitBitTestCase - this function produces one "bit test"
1906void SelectionDAGLowering::visitBitTestCase(MachineBasicBlock* NextMBB,
1907 unsigned Reg,
Dan Gohman7c3234c2008-08-27 23:52:12 +00001908 BitTestCase &B) {
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001909 // Emit bit tests and jumps
Dan Gohman475871a2008-07-27 21:46:04 +00001910 SDValue SwitchVal = DAG.getCopyFromReg(getControlRoot(), Reg,
Chris Lattneread0d882008-06-17 06:09:18 +00001911 TLI.getPointerTy());
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001912
Dan Gohman475871a2008-07-27 21:46:04 +00001913 SDValue AndOp = DAG.getNode(ISD::AND, TLI.getPointerTy(), SwitchVal,
Chris Lattneread0d882008-06-17 06:09:18 +00001914 DAG.getConstant(B.Mask, TLI.getPointerTy()));
Dan Gohman475871a2008-07-27 21:46:04 +00001915 SDValue AndCmp = DAG.getSetCC(TLI.getSetCCResultType(AndOp), AndOp,
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001916 DAG.getConstant(0, TLI.getPointerTy()),
1917 ISD::SETNE);
Owen Anderson2d389e82008-06-07 00:00:23 +00001918
1919 CurMBB->addSuccessor(B.TargetBB);
1920 CurMBB->addSuccessor(NextMBB);
1921
Dan Gohman475871a2008-07-27 21:46:04 +00001922 SDValue BrAnd = DAG.getNode(ISD::BRCOND, MVT::Other, getControlRoot(),
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001923 AndCmp, DAG.getBasicBlock(B.TargetBB));
1924
1925 // Set NextBlock to be the MBB immediately after the current one, if any.
1926 // This is used to avoid emitting unnecessary branches to the next block.
1927 MachineBasicBlock *NextBlock = 0;
1928 MachineFunction::iterator BBI = CurMBB;
1929 if (++BBI != CurMBB->getParent()->end())
1930 NextBlock = BBI;
1931
1932 if (NextMBB == NextBlock)
1933 DAG.setRoot(BrAnd);
1934 else
1935 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrAnd,
1936 DAG.getBasicBlock(NextMBB)));
1937
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001938 return;
1939}
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001940
Jim Laskeyb180aa12007-02-21 22:53:45 +00001941void SelectionDAGLowering::visitInvoke(InvokeInst &I) {
1942 // Retrieve successors.
1943 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
Duncan Sandsf19f6bb2007-06-13 05:51:31 +00001944 MachineBasicBlock *LandingPad = FuncInfo.MBBMap[I.getSuccessor(1)];
Duncan Sands9fac0b52007-06-06 10:05:18 +00001945
Duncan Sandsfd7b3262007-12-17 18:08:19 +00001946 if (isa<InlineAsm>(I.getCalledValue()))
1947 visitInlineAsm(&I);
1948 else
Duncan Sands6f74b482007-12-19 09:48:52 +00001949 LowerCallTo(&I, getValue(I.getOperand(0)), false, LandingPad);
Duncan Sands9fac0b52007-06-06 10:05:18 +00001950
Duncan Sandsf19f6bb2007-06-13 05:51:31 +00001951 // If the value of the invoke is used outside of its defining block, make it
1952 // available as a virtual register.
1953 if (!I.use_empty()) {
1954 DenseMap<const Value*, unsigned>::iterator VMI = FuncInfo.ValueMap.find(&I);
1955 if (VMI != FuncInfo.ValueMap.end())
Dan Gohman86e1ebf2008-03-27 19:56:19 +00001956 CopyValueToVirtualRegister(&I, VMI->second);
Jim Laskey183f47f2007-02-25 21:43:59 +00001957 }
Duncan Sandsf19f6bb2007-06-13 05:51:31 +00001958
Duncan Sandsf19f6bb2007-06-13 05:51:31 +00001959 // Update successor info
1960 CurMBB->addSuccessor(Return);
1961 CurMBB->addSuccessor(LandingPad);
Owen Anderson2d389e82008-06-07 00:00:23 +00001962
1963 // Drop into normal successor.
1964 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getControlRoot(),
1965 DAG.getBasicBlock(Return)));
Jim Laskeyb180aa12007-02-21 22:53:45 +00001966}
1967
1968void SelectionDAGLowering::visitUnwind(UnwindInst &I) {
1969}
1970
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001971/// handleSmallSwitchCaseRange - Emit a series of specific tests (suitable for
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001972/// small case ranges).
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001973bool SelectionDAGLowering::handleSmallSwitchRange(CaseRec& CR,
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001974 CaseRecVector& WorkList,
1975 Value* SV,
1976 MachineBasicBlock* Default) {
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001977 Case& BackCase = *(CR.Range.second-1);
1978
1979 // Size is the number of Cases represented by this range.
1980 unsigned Size = CR.Range.second - CR.Range.first;
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001981 if (Size > 3)
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001982 return false;
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001983
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001984 // Get the MachineFunction which holds the current MBB. This is used when
1985 // inserting any additional MBBs necessary to represent the switch.
1986 MachineFunction *CurMF = CurMBB->getParent();
1987
1988 // Figure out which block is immediately after the current one.
1989 MachineBasicBlock *NextBlock = 0;
1990 MachineFunction::iterator BBI = CR.CaseBB;
1991
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001992 if (++BBI != CurMBB->getParent()->end())
1993 NextBlock = BBI;
1994
1995 // TODO: If any two of the cases has the same destination, and if one value
1996 // is the same as the other, but has one bit unset that the other has set,
1997 // use bit manipulation to do two compares at once. For example:
1998 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
1999
2000 // Rearrange the case blocks so that the last one falls through if possible.
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002001 if (NextBlock && Default != NextBlock && BackCase.BB != NextBlock) {
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00002002 // The last case block won't fall through into 'NextBlock' if we emit the
2003 // branches in this order. See if rearranging a case value would help.
2004 for (CaseItr I = CR.Range.first, E = CR.Range.second-1; I != E; ++I) {
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002005 if (I->BB == NextBlock) {
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00002006 std::swap(*I, BackCase);
2007 break;
2008 }
2009 }
2010 }
2011
2012 // Create a CaseBlock record representing a conditional branch to
2013 // the Case's target mbb if the value being switched on SV is equal
2014 // to C.
2015 MachineBasicBlock *CurBlock = CR.CaseBB;
2016 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I) {
2017 MachineBasicBlock *FallThrough;
2018 if (I != E-1) {
Dan Gohman0e5f1302008-07-07 23:02:41 +00002019 FallThrough = CurMF->CreateMachineBasicBlock(CurBlock->getBasicBlock());
2020 CurMF->insert(BBI, FallThrough);
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00002021 } else {
2022 // If the last case doesn't match, go to the default block.
2023 FallThrough = Default;
2024 }
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002025
2026 Value *RHS, *LHS, *MHS;
2027 ISD::CondCode CC;
2028 if (I->High == I->Low) {
2029 // This is just small small case range :) containing exactly 1 case
2030 CC = ISD::SETEQ;
2031 LHS = SV; RHS = I->High; MHS = NULL;
2032 } else {
2033 CC = ISD::SETLE;
2034 LHS = I->Low; MHS = SV; RHS = I->High;
2035 }
Dan Gohman7c3234c2008-08-27 23:52:12 +00002036 CaseBlock CB(CC, LHS, RHS, MHS, I->BB, FallThrough, CurBlock);
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00002037
2038 // If emitting the first comparison, just call visitSwitchCase to emit the
2039 // code into the current block. Otherwise, push the CaseBlock onto the
2040 // vector to be later processed by SDISel, and insert the node's MBB
2041 // before the next MBB.
2042 if (CurBlock == CurMBB)
2043 visitSwitchCase(CB);
2044 else
2045 SwitchCases.push_back(CB);
2046
2047 CurBlock = FallThrough;
2048 }
Anton Korobeynikovdd433212007-03-27 12:05:48 +00002049
2050 return true;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00002051}
2052
Anton Korobeynikov7294b582007-05-09 20:07:08 +00002053static inline bool areJTsAllowed(const TargetLowering &TLI) {
Dale Johannesen72324642008-07-31 18:13:12 +00002054 return !DisableJumpTables &&
2055 (TLI.isOperationLegal(ISD::BR_JT, MVT::Other) ||
2056 TLI.isOperationLegal(ISD::BRIND, MVT::Other));
Anton Korobeynikov7294b582007-05-09 20:07:08 +00002057}
2058
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00002059/// handleJTSwitchCase - Emit jumptable for current switch case range
Anton Korobeynikovdd433212007-03-27 12:05:48 +00002060bool SelectionDAGLowering::handleJTSwitchCase(CaseRec& CR,
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00002061 CaseRecVector& WorkList,
2062 Value* SV,
2063 MachineBasicBlock* Default) {
Anton Korobeynikovdd433212007-03-27 12:05:48 +00002064 Case& FrontCase = *CR.Range.first;
2065 Case& BackCase = *(CR.Range.second-1);
2066
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002067 int64_t First = cast<ConstantInt>(FrontCase.Low)->getSExtValue();
2068 int64_t Last = cast<ConstantInt>(BackCase.High)->getSExtValue();
2069
2070 uint64_t TSize = 0;
2071 for (CaseItr I = CR.Range.first, E = CR.Range.second;
2072 I!=E; ++I)
2073 TSize += I->size();
Anton Korobeynikovdd433212007-03-27 12:05:48 +00002074
Anton Korobeynikov7294b582007-05-09 20:07:08 +00002075 if (!areJTsAllowed(TLI) || TSize <= 3)
Anton Korobeynikovdd433212007-03-27 12:05:48 +00002076 return false;
2077
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002078 double Density = (double)TSize / (double)((Last - First) + 1ULL);
2079 if (Density < 0.4)
Anton Korobeynikovdd433212007-03-27 12:05:48 +00002080 return false;
2081
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002082 DOUT << "Lowering jump table\n"
2083 << "First entry: " << First << ". Last entry: " << Last << "\n"
Anton Korobeynikov4198c582007-04-09 12:31:58 +00002084 << "Size: " << TSize << ". Density: " << Density << "\n\n";
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002085
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00002086 // Get the MachineFunction which holds the current MBB. This is used when
2087 // inserting any additional MBBs necessary to represent the switch.
Anton Korobeynikovdd433212007-03-27 12:05:48 +00002088 MachineFunction *CurMF = CurMBB->getParent();
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00002089
2090 // Figure out which block is immediately after the current one.
2091 MachineBasicBlock *NextBlock = 0;
2092 MachineFunction::iterator BBI = CR.CaseBB;
2093
2094 if (++BBI != CurMBB->getParent()->end())
2095 NextBlock = BBI;
2096
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00002097 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
2098
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00002099 // Create a new basic block to hold the code for loading the address
2100 // of the jump table, and jumping to it. Update successor information;
2101 // we will either branch to the default case for the switch, or the jump
2102 // table.
Dan Gohman0e5f1302008-07-07 23:02:41 +00002103 MachineBasicBlock *JumpTableBB = CurMF->CreateMachineBasicBlock(LLVMBB);
2104 CurMF->insert(BBI, JumpTableBB);
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00002105 CR.CaseBB->addSuccessor(Default);
2106 CR.CaseBB->addSuccessor(JumpTableBB);
2107
2108 // Build a vector of destination BBs, corresponding to each target
Anton Korobeynikov4198c582007-04-09 12:31:58 +00002109 // of the jump table. If the value of the jump table slot corresponds to
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00002110 // a case statement, push the case's BB onto the vector, otherwise, push
2111 // the default BB.
2112 std::vector<MachineBasicBlock*> DestBBs;
2113 int64_t TEI = First;
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002114 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++TEI) {
2115 int64_t Low = cast<ConstantInt>(I->Low)->getSExtValue();
2116 int64_t High = cast<ConstantInt>(I->High)->getSExtValue();
2117
2118 if ((Low <= TEI) && (TEI <= High)) {
2119 DestBBs.push_back(I->BB);
2120 if (TEI==High)
2121 ++I;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00002122 } else {
2123 DestBBs.push_back(Default);
2124 }
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002125 }
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00002126
2127 // Update successor info. Add one edge to each unique successor.
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002128 BitVector SuccsHandled(CR.CaseBB->getParent()->getNumBlockIDs());
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00002129 for (std::vector<MachineBasicBlock*>::iterator I = DestBBs.begin(),
2130 E = DestBBs.end(); I != E; ++I) {
2131 if (!SuccsHandled[(*I)->getNumber()]) {
2132 SuccsHandled[(*I)->getNumber()] = true;
2133 JumpTableBB->addSuccessor(*I);
2134 }
2135 }
2136
2137 // Create a jump table index for this jump table, or return an existing
2138 // one.
2139 unsigned JTI = CurMF->getJumpTableInfo()->getJumpTableIndex(DestBBs);
2140
2141 // Set the jump table information so that we can codegen it as a second
2142 // MachineBasicBlock
Dan Gohman7c3234c2008-08-27 23:52:12 +00002143 JumpTable JT(-1U, JTI, JumpTableBB, Default);
2144 JumpTableHeader JTH(First, Last, SV, CR.CaseBB, (CR.CaseBB == CurMBB));
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00002145 if (CR.CaseBB == CurMBB)
2146 visitJumpTableHeader(JT, JTH);
2147
Dan Gohman7c3234c2008-08-27 23:52:12 +00002148 JTCases.push_back(JumpTableBlock(JTH, JT));
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00002149
Anton Korobeynikovdd433212007-03-27 12:05:48 +00002150 return true;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00002151}
2152
2153/// handleBTSplitSwitchCase - emit comparison and split binary search tree into
2154/// 2 subtrees.
Anton Korobeynikovdd433212007-03-27 12:05:48 +00002155bool SelectionDAGLowering::handleBTSplitSwitchCase(CaseRec& CR,
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00002156 CaseRecVector& WorkList,
2157 Value* SV,
2158 MachineBasicBlock* Default) {
2159 // Get the MachineFunction which holds the current MBB. This is used when
2160 // inserting any additional MBBs necessary to represent the switch.
2161 MachineFunction *CurMF = CurMBB->getParent();
2162
2163 // Figure out which block is immediately after the current one.
2164 MachineBasicBlock *NextBlock = 0;
2165 MachineFunction::iterator BBI = CR.CaseBB;
2166
2167 if (++BBI != CurMBB->getParent()->end())
2168 NextBlock = BBI;
2169
2170 Case& FrontCase = *CR.Range.first;
2171 Case& BackCase = *(CR.Range.second-1);
2172 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
2173
2174 // Size is the number of Cases represented by this range.
2175 unsigned Size = CR.Range.second - CR.Range.first;
2176
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002177 int64_t First = cast<ConstantInt>(FrontCase.Low)->getSExtValue();
2178 int64_t Last = cast<ConstantInt>(BackCase.High)->getSExtValue();
Anton Korobeynikov4198c582007-04-09 12:31:58 +00002179 double FMetric = 0;
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002180 CaseItr Pivot = CR.Range.first + Size/2;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00002181
2182 // Select optimal pivot, maximizing sum density of LHS and RHS. This will
2183 // (heuristically) allow us to emit JumpTable's later.
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002184 uint64_t TSize = 0;
2185 for (CaseItr I = CR.Range.first, E = CR.Range.second;
2186 I!=E; ++I)
2187 TSize += I->size();
2188
2189 uint64_t LSize = FrontCase.size();
2190 uint64_t RSize = TSize-LSize;
Anton Korobeynikov4198c582007-04-09 12:31:58 +00002191 DOUT << "Selecting best pivot: \n"
2192 << "First: " << First << ", Last: " << Last <<"\n"
2193 << "LSize: " << LSize << ", RSize: " << RSize << "\n";
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00002194 for (CaseItr I = CR.Range.first, J=I+1, E = CR.Range.second;
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002195 J!=E; ++I, ++J) {
2196 int64_t LEnd = cast<ConstantInt>(I->High)->getSExtValue();
2197 int64_t RBegin = cast<ConstantInt>(J->Low)->getSExtValue();
Anton Korobeynikov4198c582007-04-09 12:31:58 +00002198 assert((RBegin-LEnd>=1) && "Invalid case distance");
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00002199 double LDensity = (double)LSize / (double)((LEnd - First) + 1ULL);
2200 double RDensity = (double)RSize / (double)((Last - RBegin) + 1ULL);
Anton Korobeynikov54e2b142007-04-09 21:57:03 +00002201 double Metric = Log2_64(RBegin-LEnd)*(LDensity+RDensity);
Anton Korobeynikov4198c582007-04-09 12:31:58 +00002202 // Should always split in some non-trivial place
2203 DOUT <<"=>Step\n"
2204 << "LEnd: " << LEnd << ", RBegin: " << RBegin << "\n"
2205 << "LDensity: " << LDensity << ", RDensity: " << RDensity << "\n"
2206 << "Metric: " << Metric << "\n";
2207 if (FMetric < Metric) {
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00002208 Pivot = J;
Anton Korobeynikov4198c582007-04-09 12:31:58 +00002209 FMetric = Metric;
2210 DOUT << "Current metric set to: " << FMetric << "\n";
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00002211 }
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002212
2213 LSize += J->size();
2214 RSize -= J->size();
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00002215 }
Anton Korobeynikov7294b582007-05-09 20:07:08 +00002216 if (areJTsAllowed(TLI)) {
2217 // If our case is dense we *really* should handle it earlier!
2218 assert((FMetric > 0) && "Should handle dense range earlier!");
2219 } else {
2220 Pivot = CR.Range.first + Size/2;
2221 }
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00002222
2223 CaseRange LHSR(CR.Range.first, Pivot);
2224 CaseRange RHSR(Pivot, CR.Range.second);
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002225 Constant *C = Pivot->Low;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00002226 MachineBasicBlock *FalseBB = 0, *TrueBB = 0;
2227
2228 // We know that we branch to the LHS if the Value being switched on is
2229 // less than the Pivot value, C. We use this to optimize our binary
2230 // tree a bit, by recognizing that if SV is greater than or equal to the
2231 // LHS's Case Value, and that Case Value is exactly one less than the
2232 // Pivot's Value, then we can branch directly to the LHS's Target,
2233 // rather than creating a leaf node for it.
2234 if ((LHSR.second - LHSR.first) == 1 &&
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002235 LHSR.first->High == CR.GE &&
2236 cast<ConstantInt>(C)->getSExtValue() ==
2237 (cast<ConstantInt>(CR.GE)->getSExtValue() + 1LL)) {
2238 TrueBB = LHSR.first->BB;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00002239 } else {
Dan Gohman0e5f1302008-07-07 23:02:41 +00002240 TrueBB = CurMF->CreateMachineBasicBlock(LLVMBB);
2241 CurMF->insert(BBI, TrueBB);
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00002242 WorkList.push_back(CaseRec(TrueBB, C, CR.GE, LHSR));
2243 }
2244
2245 // Similar to the optimization above, if the Value being switched on is
2246 // known to be less than the Constant CR.LT, and the current Case Value
2247 // is CR.LT - 1, then we can branch directly to the target block for
2248 // the current Case Value, rather than emitting a RHS leaf node for it.
2249 if ((RHSR.second - RHSR.first) == 1 && CR.LT &&
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002250 cast<ConstantInt>(RHSR.first->Low)->getSExtValue() ==
2251 (cast<ConstantInt>(CR.LT)->getSExtValue() - 1LL)) {
2252 FalseBB = RHSR.first->BB;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00002253 } else {
Dan Gohman0e5f1302008-07-07 23:02:41 +00002254 FalseBB = CurMF->CreateMachineBasicBlock(LLVMBB);
2255 CurMF->insert(BBI, FalseBB);
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00002256 WorkList.push_back(CaseRec(FalseBB,CR.LT,C,RHSR));
2257 }
2258
2259 // Create a CaseBlock record representing a conditional branch to
2260 // the LHS node if the value being switched on SV is less than C.
2261 // Otherwise, branch to LHS.
Dan Gohman7c3234c2008-08-27 23:52:12 +00002262 CaseBlock CB(ISD::SETLT, SV, C, NULL, TrueBB, FalseBB, CR.CaseBB);
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00002263
2264 if (CR.CaseBB == CurMBB)
2265 visitSwitchCase(CB);
2266 else
2267 SwitchCases.push_back(CB);
Anton Korobeynikovdd433212007-03-27 12:05:48 +00002268
2269 return true;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00002270}
2271
Anton Korobeynikov4198c582007-04-09 12:31:58 +00002272/// handleBitTestsSwitchCase - if current case range has few destination and
2273/// range span less, than machine word bitwidth, encode case range into series
2274/// of masks and emit bit tests with these masks.
2275bool SelectionDAGLowering::handleBitTestsSwitchCase(CaseRec& CR,
2276 CaseRecVector& WorkList,
2277 Value* SV,
Chris Lattner3ff98172007-04-14 02:26:56 +00002278 MachineBasicBlock* Default){
Duncan Sands83ec4b62008-06-06 12:08:01 +00002279 unsigned IntPtrBits = TLI.getPointerTy().getSizeInBits();
Anton Korobeynikov4198c582007-04-09 12:31:58 +00002280
2281 Case& FrontCase = *CR.Range.first;
2282 Case& BackCase = *(CR.Range.second-1);
2283
2284 // Get the MachineFunction which holds the current MBB. This is used when
2285 // inserting any additional MBBs necessary to represent the switch.
2286 MachineFunction *CurMF = CurMBB->getParent();
2287
2288 unsigned numCmps = 0;
2289 for (CaseItr I = CR.Range.first, E = CR.Range.second;
2290 I!=E; ++I) {
2291 // Single case counts one, case range - two.
2292 if (I->Low == I->High)
2293 numCmps +=1;
2294 else
2295 numCmps +=2;
2296 }
2297
2298 // Count unique destinations
2299 SmallSet<MachineBasicBlock*, 4> Dests;
2300 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
2301 Dests.insert(I->BB);
2302 if (Dests.size() > 3)
2303 // Don't bother the code below, if there are too much unique destinations
2304 return false;
2305 }
2306 DOUT << "Total number of unique destinations: " << Dests.size() << "\n"
2307 << "Total number of comparisons: " << numCmps << "\n";
2308
2309 // Compute span of values.
2310 Constant* minValue = FrontCase.Low;
2311 Constant* maxValue = BackCase.High;
2312 uint64_t range = cast<ConstantInt>(maxValue)->getSExtValue() -
2313 cast<ConstantInt>(minValue)->getSExtValue();
2314 DOUT << "Compare range: " << range << "\n"
2315 << "Low bound: " << cast<ConstantInt>(minValue)->getSExtValue() << "\n"
2316 << "High bound: " << cast<ConstantInt>(maxValue)->getSExtValue() << "\n";
2317
Anton Korobeynikovab8fd402007-04-26 20:44:04 +00002318 if (range>=IntPtrBits ||
Anton Korobeynikov4198c582007-04-09 12:31:58 +00002319 (!(Dests.size() == 1 && numCmps >= 3) &&
2320 !(Dests.size() == 2 && numCmps >= 5) &&
2321 !(Dests.size() >= 3 && numCmps >= 6)))
2322 return false;
2323
2324 DOUT << "Emitting bit tests\n";
2325 int64_t lowBound = 0;
2326
2327 // Optimize the case where all the case values fit in a
2328 // word without having to subtract minValue. In this case,
2329 // we can optimize away the subtraction.
2330 if (cast<ConstantInt>(minValue)->getSExtValue() >= 0 &&
Anton Korobeynikove01017b2007-04-14 13:25:55 +00002331 cast<ConstantInt>(maxValue)->getSExtValue() < IntPtrBits) {
Anton Korobeynikov4198c582007-04-09 12:31:58 +00002332 range = cast<ConstantInt>(maxValue)->getSExtValue();
2333 } else {
2334 lowBound = cast<ConstantInt>(minValue)->getSExtValue();
2335 }
2336
2337 CaseBitsVector CasesBits;
2338 unsigned i, count = 0;
2339
2340 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
2341 MachineBasicBlock* Dest = I->BB;
2342 for (i = 0; i < count; ++i)
2343 if (Dest == CasesBits[i].BB)
2344 break;
2345
2346 if (i == count) {
2347 assert((count < 3) && "Too much destinations to test!");
2348 CasesBits.push_back(CaseBits(0, Dest, 0));
2349 count++;
2350 }
2351
2352 uint64_t lo = cast<ConstantInt>(I->Low)->getSExtValue() - lowBound;
2353 uint64_t hi = cast<ConstantInt>(I->High)->getSExtValue() - lowBound;
2354
2355 for (uint64_t j = lo; j <= hi; j++) {
Anton Korobeynikove01017b2007-04-14 13:25:55 +00002356 CasesBits[i].Mask |= 1ULL << j;
Anton Korobeynikov4198c582007-04-09 12:31:58 +00002357 CasesBits[i].Bits++;
2358 }
2359
2360 }
2361 std::sort(CasesBits.begin(), CasesBits.end(), CaseBitsCmp());
2362
Dan Gohman7c3234c2008-08-27 23:52:12 +00002363 BitTestInfo BTC;
Anton Korobeynikov4198c582007-04-09 12:31:58 +00002364
2365 // Figure out which block is immediately after the current one.
2366 MachineFunction::iterator BBI = CR.CaseBB;
2367 ++BBI;
2368
2369 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
2370
2371 DOUT << "Cases:\n";
2372 for (unsigned i = 0, e = CasesBits.size(); i!=e; ++i) {
2373 DOUT << "Mask: " << CasesBits[i].Mask << ", Bits: " << CasesBits[i].Bits
2374 << ", BB: " << CasesBits[i].BB << "\n";
2375
Dan Gohman0e5f1302008-07-07 23:02:41 +00002376 MachineBasicBlock *CaseBB = CurMF->CreateMachineBasicBlock(LLVMBB);
2377 CurMF->insert(BBI, CaseBB);
Dan Gohman7c3234c2008-08-27 23:52:12 +00002378 BTC.push_back(BitTestCase(CasesBits[i].Mask,
2379 CaseBB,
2380 CasesBits[i].BB));
Anton Korobeynikov4198c582007-04-09 12:31:58 +00002381 }
2382
Dan Gohman7c3234c2008-08-27 23:52:12 +00002383 BitTestBlock BTB(lowBound, range, SV,
2384 -1U, (CR.CaseBB == CurMBB),
2385 CR.CaseBB, Default, BTC);
Anton Korobeynikov4198c582007-04-09 12:31:58 +00002386
2387 if (CR.CaseBB == CurMBB)
2388 visitBitTestHeader(BTB);
2389
2390 BitTestCases.push_back(BTB);
2391
2392 return true;
2393}
2394
2395
Dan Gohman86e1ebf2008-03-27 19:56:19 +00002396/// Clusterify - Transform simple list of Cases into list of CaseRange's
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002397unsigned SelectionDAGLowering::Clusterify(CaseVector& Cases,
2398 const SwitchInst& SI) {
2399 unsigned numCmps = 0;
2400
2401 // Start with "simple" cases
2402 for (unsigned i = 1; i < SI.getNumSuccessors(); ++i) {
2403 MachineBasicBlock *SMBB = FuncInfo.MBBMap[SI.getSuccessor(i)];
2404 Cases.push_back(Case(SI.getSuccessorValue(i),
2405 SI.getSuccessorValue(i),
2406 SMBB));
2407 }
Chris Lattnerb3d9cdb2007-11-27 06:14:32 +00002408 std::sort(Cases.begin(), Cases.end(), CaseCmp());
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002409
2410 // Merge case into clusters
2411 if (Cases.size()>=2)
David Greenea2a48852007-06-29 03:42:23 +00002412 // Must recompute end() each iteration because it may be
2413 // invalidated by erase if we hold on to it
Chris Lattner27a6c732007-11-24 07:07:01 +00002414 for (CaseItr I=Cases.begin(), J=++(Cases.begin()); J!=Cases.end(); ) {
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002415 int64_t nextValue = cast<ConstantInt>(J->Low)->getSExtValue();
2416 int64_t currentValue = cast<ConstantInt>(I->High)->getSExtValue();
2417 MachineBasicBlock* nextBB = J->BB;
2418 MachineBasicBlock* currentBB = I->BB;
2419
2420 // If the two neighboring cases go to the same destination, merge them
2421 // into a single case.
2422 if ((nextValue-currentValue==1) && (currentBB == nextBB)) {
2423 I->High = J->High;
2424 J = Cases.erase(J);
2425 } else {
2426 I = J++;
2427 }
2428 }
2429
2430 for (CaseItr I=Cases.begin(), E=Cases.end(); I!=E; ++I, ++numCmps) {
2431 if (I->Low != I->High)
2432 // A range counts double, since it requires two compares.
2433 ++numCmps;
2434 }
2435
2436 return numCmps;
2437}
2438
2439void SelectionDAGLowering::visitSwitch(SwitchInst &SI) {
Nate Begemanf15485a2006-03-27 01:32:24 +00002440 // Figure out which block is immediately after the current one.
2441 MachineBasicBlock *NextBlock = 0;
2442 MachineFunction::iterator BBI = CurMBB;
Bill Wendlingc70ddad2006-10-19 21:46:38 +00002443
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002444 MachineBasicBlock *Default = FuncInfo.MBBMap[SI.getDefaultDest()];
Chris Lattnerd2c1d222006-10-22 21:36:53 +00002445
Nate Begemanf15485a2006-03-27 01:32:24 +00002446 // If there is only the default destination, branch to it if it is not the
2447 // next basic block. Otherwise, just fall through.
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002448 if (SI.getNumOperands() == 2) {
Nate Begemanf15485a2006-03-27 01:32:24 +00002449 // Update machine-CFG edges.
Bill Wendlingc70ddad2006-10-19 21:46:38 +00002450
Nate Begemanf15485a2006-03-27 01:32:24 +00002451 // If this is not a fall-through branch, emit the branch.
Owen Anderson2d389e82008-06-07 00:00:23 +00002452 CurMBB->addSuccessor(Default);
Chris Lattnerd2c1d222006-10-22 21:36:53 +00002453 if (Default != NextBlock)
Dan Gohman86e1ebf2008-03-27 19:56:19 +00002454 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getControlRoot(),
Chris Lattnerd2c1d222006-10-22 21:36:53 +00002455 DAG.getBasicBlock(Default)));
Owen Anderson2d389e82008-06-07 00:00:23 +00002456
Nate Begemanf15485a2006-03-27 01:32:24 +00002457 return;
2458 }
2459
2460 // If there are any non-default case statements, create a vector of Cases
2461 // representing each one, and sort the vector so that we can efficiently
2462 // create a binary search tree from them.
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002463 CaseVector Cases;
2464 unsigned numCmps = Clusterify(Cases, SI);
2465 DOUT << "Clusterify finished. Total clusters: " << Cases.size()
2466 << ". Total compares: " << numCmps << "\n";
Bill Wendlingc70ddad2006-10-19 21:46:38 +00002467
Nate Begemanf15485a2006-03-27 01:32:24 +00002468 // Get the Value to be switched on and default basic blocks, which will be
2469 // inserted into CaseBlock records, representing basic blocks in the binary
2470 // search tree.
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002471 Value *SV = SI.getOperand(0);
Nate Begeman37efe672006-04-22 18:53:45 +00002472
Nate Begemanf15485a2006-03-27 01:32:24 +00002473 // Push the initial CaseRec onto the worklist
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00002474 CaseRecVector WorkList;
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00002475 WorkList.push_back(CaseRec(CurMBB,0,0,CaseRange(Cases.begin(),Cases.end())));
2476
2477 while (!WorkList.empty()) {
Nate Begemanf15485a2006-03-27 01:32:24 +00002478 // Grab a record representing a case range to process off the worklist
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00002479 CaseRec CR = WorkList.back();
2480 WorkList.pop_back();
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00002481
Anton Korobeynikov4198c582007-04-09 12:31:58 +00002482 if (handleBitTestsSwitchCase(CR, WorkList, SV, Default))
2483 continue;
2484
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00002485 // If the range has few cases (two or less) emit a series of specific
2486 // tests.
Anton Korobeynikovdd433212007-03-27 12:05:48 +00002487 if (handleSmallSwitchRange(CR, WorkList, SV, Default))
2488 continue;
2489
Anton Korobeynikov4198c582007-04-09 12:31:58 +00002490 // If the switch has more than 5 blocks, and at least 40% dense, and the
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00002491 // target supports indirect branches, then emit a jump table rather than
2492 // lowering the switch to a binary tree of conditional branches.
Anton Korobeynikovdd433212007-03-27 12:05:48 +00002493 if (handleJTSwitchCase(CR, WorkList, SV, Default))
2494 continue;
2495
2496 // Emit binary tree. We need to pick a pivot, and push left and right ranges
2497 // onto the worklist. Leafs are handled via handleSmallSwitchRange() call.
2498 handleBTSplitSwitchCase(CR, WorkList, SV, Default);
Nate Begemanf15485a2006-03-27 01:32:24 +00002499 }
2500}
2501
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00002502
Chris Lattnerb9fccc42005-04-02 05:04:50 +00002503void SelectionDAGLowering::visitSub(User &I) {
2504 // -0.0 - X --> fneg
Reid Spencer24d6da52007-01-21 00:29:26 +00002505 const Type *Ty = I.getType();
Reid Spencer9d6565a2007-02-15 02:26:10 +00002506 if (isa<VectorType>(Ty)) {
Dan Gohman7f321562007-06-25 16:23:39 +00002507 if (ConstantVector *CV = dyn_cast<ConstantVector>(I.getOperand(0))) {
2508 const VectorType *DestTy = cast<VectorType>(I.getType());
2509 const Type *ElTy = DestTy->getElementType();
Evan Chengc45453f2007-06-29 21:44:35 +00002510 if (ElTy->isFloatingPoint()) {
2511 unsigned VL = DestTy->getNumElements();
Dale Johannesen9e3d3ab2007-09-14 22:26:36 +00002512 std::vector<Constant*> NZ(VL, ConstantFP::getNegativeZero(ElTy));
Evan Chengc45453f2007-06-29 21:44:35 +00002513 Constant *CNZ = ConstantVector::get(&NZ[0], NZ.size());
2514 if (CV == CNZ) {
Dan Gohman475871a2008-07-27 21:46:04 +00002515 SDValue Op2 = getValue(I.getOperand(1));
Evan Chengc45453f2007-06-29 21:44:35 +00002516 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
2517 return;
2518 }
Dan Gohman7f321562007-06-25 16:23:39 +00002519 }
2520 }
2521 }
2522 if (Ty->isFloatingPoint()) {
Chris Lattner01b3d732005-09-28 22:28:18 +00002523 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
Dale Johannesen9e3d3ab2007-09-14 22:26:36 +00002524 if (CFP->isExactlyValue(ConstantFP::getNegativeZero(Ty)->getValueAPF())) {
Dan Gohman475871a2008-07-27 21:46:04 +00002525 SDValue Op2 = getValue(I.getOperand(1));
Chris Lattner01b3d732005-09-28 22:28:18 +00002526 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
2527 return;
2528 }
Dan Gohman7f321562007-06-25 16:23:39 +00002529 }
2530
2531 visitBinary(I, Ty->isFPOrFPVector() ? ISD::FSUB : ISD::SUB);
Chris Lattnerb9fccc42005-04-02 05:04:50 +00002532}
2533
Dan Gohman7f321562007-06-25 16:23:39 +00002534void SelectionDAGLowering::visitBinary(User &I, unsigned OpCode) {
Dan Gohman475871a2008-07-27 21:46:04 +00002535 SDValue Op1 = getValue(I.getOperand(0));
2536 SDValue Op2 = getValue(I.getOperand(1));
Reid Spencer24d6da52007-01-21 00:29:26 +00002537
2538 setValue(&I, DAG.getNode(OpCode, Op1.getValueType(), Op1, Op2));
Reid Spencer1628cec2006-10-26 06:15:43 +00002539}
2540
Nate Begemane21ea612005-11-18 07:42:56 +00002541void SelectionDAGLowering::visitShift(User &I, unsigned Opcode) {
Dan Gohman475871a2008-07-27 21:46:04 +00002542 SDValue Op1 = getValue(I.getOperand(0));
2543 SDValue Op2 = getValue(I.getOperand(1));
Nate Begeman5bc1ea02008-07-29 15:49:41 +00002544 if (!isa<VectorType>(I.getType())) {
2545 if (TLI.getShiftAmountTy().bitsLT(Op2.getValueType()))
2546 Op2 = DAG.getNode(ISD::TRUNCATE, TLI.getShiftAmountTy(), Op2);
2547 else if (TLI.getShiftAmountTy().bitsGT(Op2.getValueType()))
2548 Op2 = DAG.getNode(ISD::ANY_EXTEND, TLI.getShiftAmountTy(), Op2);
2549 }
Nate Begemane21ea612005-11-18 07:42:56 +00002550
Chris Lattner1c08c712005-01-07 07:47:53 +00002551 setValue(&I, DAG.getNode(Opcode, Op1.getValueType(), Op1, Op2));
2552}
2553
Reid Spencer45fb3f32006-11-20 01:22:35 +00002554void SelectionDAGLowering::visitICmp(User &I) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002555 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
2556 if (ICmpInst *IC = dyn_cast<ICmpInst>(&I))
2557 predicate = IC->getPredicate();
2558 else if (ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
2559 predicate = ICmpInst::Predicate(IC->getPredicate());
Dan Gohman475871a2008-07-27 21:46:04 +00002560 SDValue Op1 = getValue(I.getOperand(0));
2561 SDValue Op2 = getValue(I.getOperand(1));
Reid Spencer45fb3f32006-11-20 01:22:35 +00002562 ISD::CondCode Opcode;
Reid Spencere4d87aa2006-12-23 06:05:41 +00002563 switch (predicate) {
Reid Spencer45fb3f32006-11-20 01:22:35 +00002564 case ICmpInst::ICMP_EQ : Opcode = ISD::SETEQ; break;
2565 case ICmpInst::ICMP_NE : Opcode = ISD::SETNE; break;
2566 case ICmpInst::ICMP_UGT : Opcode = ISD::SETUGT; break;
2567 case ICmpInst::ICMP_UGE : Opcode = ISD::SETUGE; break;
2568 case ICmpInst::ICMP_ULT : Opcode = ISD::SETULT; break;
2569 case ICmpInst::ICMP_ULE : Opcode = ISD::SETULE; break;
2570 case ICmpInst::ICMP_SGT : Opcode = ISD::SETGT; break;
2571 case ICmpInst::ICMP_SGE : Opcode = ISD::SETGE; break;
2572 case ICmpInst::ICMP_SLT : Opcode = ISD::SETLT; break;
2573 case ICmpInst::ICMP_SLE : Opcode = ISD::SETLE; break;
2574 default:
2575 assert(!"Invalid ICmp predicate value");
2576 Opcode = ISD::SETEQ;
2577 break;
2578 }
2579 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Opcode));
2580}
2581
2582void SelectionDAGLowering::visitFCmp(User &I) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002583 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
2584 if (FCmpInst *FC = dyn_cast<FCmpInst>(&I))
2585 predicate = FC->getPredicate();
2586 else if (ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
2587 predicate = FCmpInst::Predicate(FC->getPredicate());
Dan Gohman475871a2008-07-27 21:46:04 +00002588 SDValue Op1 = getValue(I.getOperand(0));
2589 SDValue Op2 = getValue(I.getOperand(1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00002590 ISD::CondCode Condition, FOC, FPC;
2591 switch (predicate) {
2592 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
2593 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
2594 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
2595 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
2596 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
2597 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
2598 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
Dan Gohmancba3b442008-05-01 23:40:44 +00002599 case FCmpInst::FCMP_ORD: FOC = FPC = ISD::SETO; break;
2600 case FCmpInst::FCMP_UNO: FOC = FPC = ISD::SETUO; break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00002601 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
2602 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
2603 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
2604 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
2605 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
2606 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
2607 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
2608 default:
2609 assert(!"Invalid FCmp predicate value");
2610 FOC = FPC = ISD::SETFALSE;
2611 break;
2612 }
2613 if (FiniteOnlyFPMath())
2614 Condition = FOC;
2615 else
2616 Condition = FPC;
2617 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Condition));
Chris Lattner1c08c712005-01-07 07:47:53 +00002618}
2619
Nate Begemanb43e9c12008-05-12 19:40:03 +00002620void SelectionDAGLowering::visitVICmp(User &I) {
2621 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
2622 if (VICmpInst *IC = dyn_cast<VICmpInst>(&I))
2623 predicate = IC->getPredicate();
2624 else if (ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
2625 predicate = ICmpInst::Predicate(IC->getPredicate());
Dan Gohman475871a2008-07-27 21:46:04 +00002626 SDValue Op1 = getValue(I.getOperand(0));
2627 SDValue Op2 = getValue(I.getOperand(1));
Nate Begemanb43e9c12008-05-12 19:40:03 +00002628 ISD::CondCode Opcode;
2629 switch (predicate) {
2630 case ICmpInst::ICMP_EQ : Opcode = ISD::SETEQ; break;
2631 case ICmpInst::ICMP_NE : Opcode = ISD::SETNE; break;
2632 case ICmpInst::ICMP_UGT : Opcode = ISD::SETUGT; break;
2633 case ICmpInst::ICMP_UGE : Opcode = ISD::SETUGE; break;
2634 case ICmpInst::ICMP_ULT : Opcode = ISD::SETULT; break;
2635 case ICmpInst::ICMP_ULE : Opcode = ISD::SETULE; break;
2636 case ICmpInst::ICMP_SGT : Opcode = ISD::SETGT; break;
2637 case ICmpInst::ICMP_SGE : Opcode = ISD::SETGE; break;
2638 case ICmpInst::ICMP_SLT : Opcode = ISD::SETLT; break;
2639 case ICmpInst::ICMP_SLE : Opcode = ISD::SETLE; break;
2640 default:
2641 assert(!"Invalid ICmp predicate value");
2642 Opcode = ISD::SETEQ;
2643 break;
2644 }
2645 setValue(&I, DAG.getVSetCC(Op1.getValueType(), Op1, Op2, Opcode));
2646}
2647
2648void SelectionDAGLowering::visitVFCmp(User &I) {
2649 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
2650 if (VFCmpInst *FC = dyn_cast<VFCmpInst>(&I))
2651 predicate = FC->getPredicate();
2652 else if (ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
2653 predicate = FCmpInst::Predicate(FC->getPredicate());
Dan Gohman475871a2008-07-27 21:46:04 +00002654 SDValue Op1 = getValue(I.getOperand(0));
2655 SDValue Op2 = getValue(I.getOperand(1));
Nate Begemanb43e9c12008-05-12 19:40:03 +00002656 ISD::CondCode Condition, FOC, FPC;
2657 switch (predicate) {
2658 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
2659 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
2660 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
2661 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
2662 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
2663 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
2664 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
2665 case FCmpInst::FCMP_ORD: FOC = FPC = ISD::SETO; break;
2666 case FCmpInst::FCMP_UNO: FOC = FPC = ISD::SETUO; break;
2667 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
2668 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
2669 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
2670 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
2671 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
2672 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
2673 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
2674 default:
2675 assert(!"Invalid VFCmp predicate value");
2676 FOC = FPC = ISD::SETFALSE;
2677 break;
2678 }
2679 if (FiniteOnlyFPMath())
2680 Condition = FOC;
2681 else
2682 Condition = FPC;
2683
Duncan Sands83ec4b62008-06-06 12:08:01 +00002684 MVT DestVT = TLI.getValueType(I.getType());
Nate Begemanb43e9c12008-05-12 19:40:03 +00002685
2686 setValue(&I, DAG.getVSetCC(DestVT, Op1, Op2, Condition));
2687}
2688
Chris Lattner1c08c712005-01-07 07:47:53 +00002689void SelectionDAGLowering::visitSelect(User &I) {
Dan Gohman475871a2008-07-27 21:46:04 +00002690 SDValue Cond = getValue(I.getOperand(0));
2691 SDValue TrueVal = getValue(I.getOperand(1));
2692 SDValue FalseVal = getValue(I.getOperand(2));
Dan Gohman7f321562007-06-25 16:23:39 +00002693 setValue(&I, DAG.getNode(ISD::SELECT, TrueVal.getValueType(), Cond,
2694 TrueVal, FalseVal));
Chris Lattner1c08c712005-01-07 07:47:53 +00002695}
2696
Reid Spencer3da59db2006-11-27 01:05:10 +00002697
2698void SelectionDAGLowering::visitTrunc(User &I) {
2699 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
Dan Gohman475871a2008-07-27 21:46:04 +00002700 SDValue N = getValue(I.getOperand(0));
Duncan Sands83ec4b62008-06-06 12:08:01 +00002701 MVT DestVT = TLI.getValueType(I.getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00002702 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
2703}
2704
2705void SelectionDAGLowering::visitZExt(User &I) {
2706 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2707 // ZExt also can't be a cast to bool for same reason. So, nothing much to do
Dan Gohman475871a2008-07-27 21:46:04 +00002708 SDValue N = getValue(I.getOperand(0));
Duncan Sands83ec4b62008-06-06 12:08:01 +00002709 MVT DestVT = TLI.getValueType(I.getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00002710 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
2711}
2712
2713void SelectionDAGLowering::visitSExt(User &I) {
2714 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2715 // SExt also can't be a cast to bool for same reason. So, nothing much to do
Dan Gohman475871a2008-07-27 21:46:04 +00002716 SDValue N = getValue(I.getOperand(0));
Duncan Sands83ec4b62008-06-06 12:08:01 +00002717 MVT DestVT = TLI.getValueType(I.getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00002718 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, DestVT, N));
2719}
2720
2721void SelectionDAGLowering::visitFPTrunc(User &I) {
2722 // FPTrunc is never a no-op cast, no need to check
Dan Gohman475871a2008-07-27 21:46:04 +00002723 SDValue N = getValue(I.getOperand(0));
Duncan Sands83ec4b62008-06-06 12:08:01 +00002724 MVT DestVT = TLI.getValueType(I.getType());
Chris Lattner0bd48932008-01-17 07:00:52 +00002725 setValue(&I, DAG.getNode(ISD::FP_ROUND, DestVT, N, DAG.getIntPtrConstant(0)));
Reid Spencer3da59db2006-11-27 01:05:10 +00002726}
2727
2728void SelectionDAGLowering::visitFPExt(User &I){
2729 // FPTrunc is never a no-op cast, no need to check
Dan Gohman475871a2008-07-27 21:46:04 +00002730 SDValue N = getValue(I.getOperand(0));
Duncan Sands83ec4b62008-06-06 12:08:01 +00002731 MVT DestVT = TLI.getValueType(I.getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00002732 setValue(&I, DAG.getNode(ISD::FP_EXTEND, DestVT, N));
2733}
2734
2735void SelectionDAGLowering::visitFPToUI(User &I) {
2736 // FPToUI is never a no-op cast, no need to check
Dan Gohman475871a2008-07-27 21:46:04 +00002737 SDValue N = getValue(I.getOperand(0));
Duncan Sands83ec4b62008-06-06 12:08:01 +00002738 MVT DestVT = TLI.getValueType(I.getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00002739 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, DestVT, N));
2740}
2741
2742void SelectionDAGLowering::visitFPToSI(User &I) {
2743 // FPToSI is never a no-op cast, no need to check
Dan Gohman475871a2008-07-27 21:46:04 +00002744 SDValue N = getValue(I.getOperand(0));
Duncan Sands83ec4b62008-06-06 12:08:01 +00002745 MVT DestVT = TLI.getValueType(I.getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00002746 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, DestVT, N));
2747}
2748
2749void SelectionDAGLowering::visitUIToFP(User &I) {
2750 // UIToFP is never a no-op cast, no need to check
Dan Gohman475871a2008-07-27 21:46:04 +00002751 SDValue N = getValue(I.getOperand(0));
Duncan Sands83ec4b62008-06-06 12:08:01 +00002752 MVT DestVT = TLI.getValueType(I.getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00002753 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, DestVT, N));
2754}
2755
2756void SelectionDAGLowering::visitSIToFP(User &I){
2757 // UIToFP is never a no-op cast, no need to check
Dan Gohman475871a2008-07-27 21:46:04 +00002758 SDValue N = getValue(I.getOperand(0));
Duncan Sands83ec4b62008-06-06 12:08:01 +00002759 MVT DestVT = TLI.getValueType(I.getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00002760 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, DestVT, N));
2761}
2762
2763void SelectionDAGLowering::visitPtrToInt(User &I) {
2764 // What to do depends on the size of the integer and the size of the pointer.
2765 // We can either truncate, zero extend, or no-op, accordingly.
Dan Gohman475871a2008-07-27 21:46:04 +00002766 SDValue N = getValue(I.getOperand(0));
Duncan Sands83ec4b62008-06-06 12:08:01 +00002767 MVT SrcVT = N.getValueType();
2768 MVT DestVT = TLI.getValueType(I.getType());
Dan Gohman475871a2008-07-27 21:46:04 +00002769 SDValue Result;
Duncan Sands8e4eb092008-06-08 20:54:56 +00002770 if (DestVT.bitsLT(SrcVT))
Reid Spencer3da59db2006-11-27 01:05:10 +00002771 Result = DAG.getNode(ISD::TRUNCATE, DestVT, N);
2772 else
2773 // Note: ZERO_EXTEND can handle cases where the sizes are equal too
2774 Result = DAG.getNode(ISD::ZERO_EXTEND, DestVT, N);
2775 setValue(&I, Result);
2776}
Chris Lattner1c08c712005-01-07 07:47:53 +00002777
Reid Spencer3da59db2006-11-27 01:05:10 +00002778void SelectionDAGLowering::visitIntToPtr(User &I) {
2779 // What to do depends on the size of the integer and the size of the pointer.
2780 // We can either truncate, zero extend, or no-op, accordingly.
Dan Gohman475871a2008-07-27 21:46:04 +00002781 SDValue N = getValue(I.getOperand(0));
Duncan Sands83ec4b62008-06-06 12:08:01 +00002782 MVT SrcVT = N.getValueType();
2783 MVT DestVT = TLI.getValueType(I.getType());
Duncan Sands8e4eb092008-06-08 20:54:56 +00002784 if (DestVT.bitsLT(SrcVT))
Reid Spencer3da59db2006-11-27 01:05:10 +00002785 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
2786 else
2787 // Note: ZERO_EXTEND can handle cases where the sizes are equal too
2788 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
2789}
2790
2791void SelectionDAGLowering::visitBitCast(User &I) {
Dan Gohman475871a2008-07-27 21:46:04 +00002792 SDValue N = getValue(I.getOperand(0));
Duncan Sands83ec4b62008-06-06 12:08:01 +00002793 MVT DestVT = TLI.getValueType(I.getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00002794
2795 // BitCast assures us that source and destination are the same size so this
2796 // is either a BIT_CONVERT or a no-op.
2797 if (DestVT != N.getValueType())
2798 setValue(&I, DAG.getNode(ISD::BIT_CONVERT, DestVT, N)); // convert types
2799 else
2800 setValue(&I, N); // noop cast.
Chris Lattner1c08c712005-01-07 07:47:53 +00002801}
2802
Chris Lattner2bbd8102006-03-29 00:11:43 +00002803void SelectionDAGLowering::visitInsertElement(User &I) {
Dan Gohman475871a2008-07-27 21:46:04 +00002804 SDValue InVec = getValue(I.getOperand(0));
2805 SDValue InVal = getValue(I.getOperand(1));
2806 SDValue InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
Chris Lattnerc7029802006-03-18 01:44:44 +00002807 getValue(I.getOperand(2)));
2808
Dan Gohman7f321562007-06-25 16:23:39 +00002809 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT,
2810 TLI.getValueType(I.getType()),
2811 InVec, InVal, InIdx));
Chris Lattnerc7029802006-03-18 01:44:44 +00002812}
2813
Chris Lattner2bbd8102006-03-29 00:11:43 +00002814void SelectionDAGLowering::visitExtractElement(User &I) {
Dan Gohman475871a2008-07-27 21:46:04 +00002815 SDValue InVec = getValue(I.getOperand(0));
2816 SDValue InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
Chris Lattner384504c2006-03-21 20:44:12 +00002817 getValue(I.getOperand(1)));
Dan Gohman7f321562007-06-25 16:23:39 +00002818 setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
Chris Lattner384504c2006-03-21 20:44:12 +00002819 TLI.getValueType(I.getType()), InVec, InIdx));
2820}
Chris Lattnerc7029802006-03-18 01:44:44 +00002821
Chris Lattner3e104b12006-04-08 04:15:24 +00002822void SelectionDAGLowering::visitShuffleVector(User &I) {
Dan Gohman475871a2008-07-27 21:46:04 +00002823 SDValue V1 = getValue(I.getOperand(0));
2824 SDValue V2 = getValue(I.getOperand(1));
2825 SDValue Mask = getValue(I.getOperand(2));
Chris Lattner3e104b12006-04-08 04:15:24 +00002826
Dan Gohman7f321562007-06-25 16:23:39 +00002827 setValue(&I, DAG.getNode(ISD::VECTOR_SHUFFLE,
2828 TLI.getValueType(I.getType()),
2829 V1, V2, Mask));
Chris Lattner3e104b12006-04-08 04:15:24 +00002830}
2831
Dan Gohman1d685a42008-06-07 02:02:36 +00002832void SelectionDAGLowering::visitInsertValue(InsertValueInst &I) {
2833 const Value *Op0 = I.getOperand(0);
2834 const Value *Op1 = I.getOperand(1);
2835 const Type *AggTy = I.getType();
2836 const Type *ValTy = Op1->getType();
2837 bool IntoUndef = isa<UndefValue>(Op0);
2838 bool FromUndef = isa<UndefValue>(Op1);
2839
2840 unsigned LinearIndex = ComputeLinearIndex(TLI, AggTy,
2841 I.idx_begin(), I.idx_end());
2842
2843 SmallVector<MVT, 4> AggValueVTs;
2844 ComputeValueVTs(TLI, AggTy, AggValueVTs);
2845 SmallVector<MVT, 4> ValValueVTs;
2846 ComputeValueVTs(TLI, ValTy, ValValueVTs);
2847
2848 unsigned NumAggValues = AggValueVTs.size();
2849 unsigned NumValValues = ValValueVTs.size();
Dan Gohman475871a2008-07-27 21:46:04 +00002850 SmallVector<SDValue, 4> Values(NumAggValues);
Dan Gohman1d685a42008-06-07 02:02:36 +00002851
Dan Gohman475871a2008-07-27 21:46:04 +00002852 SDValue Agg = getValue(Op0);
2853 SDValue Val = getValue(Op1);
Dan Gohman1d685a42008-06-07 02:02:36 +00002854 unsigned i = 0;
2855 // Copy the beginning value(s) from the original aggregate.
2856 for (; i != LinearIndex; ++i)
2857 Values[i] = IntoUndef ? DAG.getNode(ISD::UNDEF, AggValueVTs[i]) :
Gabor Greifba36cb52008-08-28 21:40:38 +00002858 SDValue(Agg.getNode(), Agg.getResNo() + i);
Dan Gohman1d685a42008-06-07 02:02:36 +00002859 // Copy values from the inserted value(s).
2860 for (; i != LinearIndex + NumValValues; ++i)
2861 Values[i] = FromUndef ? DAG.getNode(ISD::UNDEF, AggValueVTs[i]) :
Gabor Greifba36cb52008-08-28 21:40:38 +00002862 SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
Dan Gohman1d685a42008-06-07 02:02:36 +00002863 // Copy remaining value(s) from the original aggregate.
2864 for (; i != NumAggValues; ++i)
2865 Values[i] = IntoUndef ? DAG.getNode(ISD::UNDEF, AggValueVTs[i]) :
Gabor Greifba36cb52008-08-28 21:40:38 +00002866 SDValue(Agg.getNode(), Agg.getResNo() + i);
Dan Gohman1d685a42008-06-07 02:02:36 +00002867
Duncan Sandsf9516202008-06-30 10:19:09 +00002868 setValue(&I, DAG.getMergeValues(DAG.getVTList(&AggValueVTs[0], NumAggValues),
2869 &Values[0], NumAggValues));
Dan Gohman041e2eb2008-05-15 19:50:34 +00002870}
2871
Dan Gohman1d685a42008-06-07 02:02:36 +00002872void SelectionDAGLowering::visitExtractValue(ExtractValueInst &I) {
2873 const Value *Op0 = I.getOperand(0);
2874 const Type *AggTy = Op0->getType();
2875 const Type *ValTy = I.getType();
2876 bool OutOfUndef = isa<UndefValue>(Op0);
2877
2878 unsigned LinearIndex = ComputeLinearIndex(TLI, AggTy,
2879 I.idx_begin(), I.idx_end());
2880
2881 SmallVector<MVT, 4> ValValueVTs;
2882 ComputeValueVTs(TLI, ValTy, ValValueVTs);
2883
2884 unsigned NumValValues = ValValueVTs.size();
Dan Gohman475871a2008-07-27 21:46:04 +00002885 SmallVector<SDValue, 4> Values(NumValValues);
Dan Gohman1d685a42008-06-07 02:02:36 +00002886
Dan Gohman475871a2008-07-27 21:46:04 +00002887 SDValue Agg = getValue(Op0);
Dan Gohman1d685a42008-06-07 02:02:36 +00002888 // Copy out the selected value(s).
2889 for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
2890 Values[i - LinearIndex] =
Gabor Greifba36cb52008-08-28 21:40:38 +00002891 OutOfUndef ? DAG.getNode(ISD::UNDEF, Agg.getNode()->getValueType(Agg.getResNo() + i)) :
2892 SDValue(Agg.getNode(), Agg.getResNo() + i);
Dan Gohman1d685a42008-06-07 02:02:36 +00002893
Duncan Sandsf9516202008-06-30 10:19:09 +00002894 setValue(&I, DAG.getMergeValues(DAG.getVTList(&ValValueVTs[0], NumValValues),
2895 &Values[0], NumValValues));
Dan Gohman041e2eb2008-05-15 19:50:34 +00002896}
2897
Chris Lattner3e104b12006-04-08 04:15:24 +00002898
Chris Lattner1c08c712005-01-07 07:47:53 +00002899void SelectionDAGLowering::visitGetElementPtr(User &I) {
Dan Gohman475871a2008-07-27 21:46:04 +00002900 SDValue N = getValue(I.getOperand(0));
Chris Lattner1c08c712005-01-07 07:47:53 +00002901 const Type *Ty = I.getOperand(0)->getType();
Chris Lattner1c08c712005-01-07 07:47:53 +00002902
2903 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
2904 OI != E; ++OI) {
2905 Value *Idx = *OI;
Chris Lattnerc88d8e92005-12-05 07:10:48 +00002906 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002907 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
Chris Lattner1c08c712005-01-07 07:47:53 +00002908 if (Field) {
2909 // N = N + Offset
Chris Lattnerb1919e22007-02-10 19:55:17 +00002910 uint64_t Offset = TD->getStructLayout(StTy)->getElementOffset(Field);
Chris Lattner1c08c712005-01-07 07:47:53 +00002911 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
Chris Lattner0bd48932008-01-17 07:00:52 +00002912 DAG.getIntPtrConstant(Offset));
Chris Lattner1c08c712005-01-07 07:47:53 +00002913 }
2914 Ty = StTy->getElementType(Field);
2915 } else {
2916 Ty = cast<SequentialType>(Ty)->getElementType();
Chris Lattner7cc47772005-01-07 21:56:57 +00002917
Chris Lattner7c0104b2005-11-09 04:45:33 +00002918 // If this is a constant subscript, handle it quickly.
2919 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002920 if (CI->getZExtValue() == 0) continue;
Reid Spencer47857812006-12-31 05:55:36 +00002921 uint64_t Offs =
Dale Johannesena7ac2bd2007-10-01 23:08:35 +00002922 TD->getABITypeSize(Ty)*cast<ConstantInt>(CI)->getSExtValue();
Chris Lattner0bd48932008-01-17 07:00:52 +00002923 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
2924 DAG.getIntPtrConstant(Offs));
Chris Lattner7c0104b2005-11-09 04:45:33 +00002925 continue;
Chris Lattner1c08c712005-01-07 07:47:53 +00002926 }
Chris Lattner7c0104b2005-11-09 04:45:33 +00002927
2928 // N = N + Idx * ElementSize;
Dale Johannesena7ac2bd2007-10-01 23:08:35 +00002929 uint64_t ElementSize = TD->getABITypeSize(Ty);
Dan Gohman475871a2008-07-27 21:46:04 +00002930 SDValue IdxN = getValue(Idx);
Chris Lattner7c0104b2005-11-09 04:45:33 +00002931
2932 // If the index is smaller or larger than intptr_t, truncate or extend
2933 // it.
Evan Cheng83785c82008-08-20 22:45:34 +00002934 if (IdxN.getValueType().bitsLT(N.getValueType()))
Reid Spencer47857812006-12-31 05:55:36 +00002935 IdxN = DAG.getNode(ISD::SIGN_EXTEND, N.getValueType(), IdxN);
Evan Cheng83785c82008-08-20 22:45:34 +00002936 else if (IdxN.getValueType().bitsGT(N.getValueType()))
Chris Lattner7c0104b2005-11-09 04:45:33 +00002937 IdxN = DAG.getNode(ISD::TRUNCATE, N.getValueType(), IdxN);
2938
2939 // If this is a multiply by a power of two, turn it into a shl
2940 // immediately. This is a very common case.
Dan Gohman66799062008-08-23 01:06:51 +00002941 if (ElementSize != 1) {
2942 if (isPowerOf2_64(ElementSize)) {
2943 unsigned Amt = Log2_64(ElementSize);
2944 IdxN = DAG.getNode(ISD::SHL, N.getValueType(), IdxN,
2945 DAG.getConstant(Amt, TLI.getShiftAmountTy()));
2946 } else {
2947 SDValue Scale = DAG.getIntPtrConstant(ElementSize);
2948 IdxN = DAG.getNode(ISD::MUL, N.getValueType(), IdxN, Scale);
2949 }
Chris Lattner7c0104b2005-11-09 04:45:33 +00002950 }
Dan Gohman66799062008-08-23 01:06:51 +00002951
Chris Lattner7c0104b2005-11-09 04:45:33 +00002952 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
Chris Lattner1c08c712005-01-07 07:47:53 +00002953 }
2954 }
2955 setValue(&I, N);
2956}
2957
2958void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
2959 // If this is a fixed sized alloca in the entry block of the function,
2960 // allocate it statically on the stack.
2961 if (FuncInfo.StaticAllocaMap.count(&I))
2962 return; // getValue will auto-populate this.
2963
2964 const Type *Ty = I.getAllocatedType();
Duncan Sands514ab342007-11-01 20:53:16 +00002965 uint64_t TySize = TLI.getTargetData()->getABITypeSize(Ty);
Chris Lattner58092e32007-01-20 22:35:55 +00002966 unsigned Align =
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00002967 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
Chris Lattner58092e32007-01-20 22:35:55 +00002968 I.getAlignment());
Chris Lattner1c08c712005-01-07 07:47:53 +00002969
Dan Gohman475871a2008-07-27 21:46:04 +00002970 SDValue AllocSize = getValue(I.getArraySize());
Duncan Sands83ec4b62008-06-06 12:08:01 +00002971 MVT IntPtr = TLI.getPointerTy();
Duncan Sands8e4eb092008-06-08 20:54:56 +00002972 if (IntPtr.bitsLT(AllocSize.getValueType()))
Chris Lattner68cd65e2005-01-22 23:04:37 +00002973 AllocSize = DAG.getNode(ISD::TRUNCATE, IntPtr, AllocSize);
Duncan Sands8e4eb092008-06-08 20:54:56 +00002974 else if (IntPtr.bitsGT(AllocSize.getValueType()))
Chris Lattner68cd65e2005-01-22 23:04:37 +00002975 AllocSize = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, AllocSize);
Chris Lattner1c08c712005-01-07 07:47:53 +00002976
Chris Lattner68cd65e2005-01-22 23:04:37 +00002977 AllocSize = DAG.getNode(ISD::MUL, IntPtr, AllocSize,
Chris Lattner0bd48932008-01-17 07:00:52 +00002978 DAG.getIntPtrConstant(TySize));
Chris Lattner1c08c712005-01-07 07:47:53 +00002979
Evan Cheng45157792007-08-16 23:46:29 +00002980 // Handle alignment. If the requested alignment is less than or equal to
2981 // the stack alignment, ignore it. If the size is greater than or equal to
2982 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
Chris Lattner1c08c712005-01-07 07:47:53 +00002983 unsigned StackAlign =
2984 TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
Evan Cheng45157792007-08-16 23:46:29 +00002985 if (Align <= StackAlign)
Chris Lattner1c08c712005-01-07 07:47:53 +00002986 Align = 0;
Evan Cheng45157792007-08-16 23:46:29 +00002987
2988 // Round the size of the allocation up to the stack alignment size
2989 // by add SA-1 to the size.
2990 AllocSize = DAG.getNode(ISD::ADD, AllocSize.getValueType(), AllocSize,
Chris Lattner0bd48932008-01-17 07:00:52 +00002991 DAG.getIntPtrConstant(StackAlign-1));
Evan Cheng45157792007-08-16 23:46:29 +00002992 // Mask out the low bits for alignment purposes.
2993 AllocSize = DAG.getNode(ISD::AND, AllocSize.getValueType(), AllocSize,
Chris Lattner0bd48932008-01-17 07:00:52 +00002994 DAG.getIntPtrConstant(~(uint64_t)(StackAlign-1)));
Chris Lattner1c08c712005-01-07 07:47:53 +00002995
Dan Gohman475871a2008-07-27 21:46:04 +00002996 SDValue Ops[] = { getRoot(), AllocSize, DAG.getIntPtrConstant(Align) };
Duncan Sands83ec4b62008-06-06 12:08:01 +00002997 const MVT *VTs = DAG.getNodeValueTypes(AllocSize.getValueType(),
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00002998 MVT::Other);
Dan Gohman475871a2008-07-27 21:46:04 +00002999 SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, VTs, 2, Ops, 3);
Chris Lattner0da331f2007-02-04 01:31:47 +00003000 setValue(&I, DSA);
3001 DAG.setRoot(DSA.getValue(1));
Chris Lattner1c08c712005-01-07 07:47:53 +00003002
3003 // Inform the Frame Information that we have just allocated a variable-sized
3004 // object.
3005 CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
3006}
3007
Chris Lattner1c08c712005-01-07 07:47:53 +00003008void SelectionDAGLowering::visitLoad(LoadInst &I) {
Dan Gohman8a6ccb52008-06-09 15:21:47 +00003009 const Value *SV = I.getOperand(0);
Dan Gohman475871a2008-07-27 21:46:04 +00003010 SDValue Ptr = getValue(SV);
Dan Gohman8a6ccb52008-06-09 15:21:47 +00003011
3012 const Type *Ty = I.getType();
3013 bool isVolatile = I.isVolatile();
3014 unsigned Alignment = I.getAlignment();
3015
3016 SmallVector<MVT, 4> ValueVTs;
3017 SmallVector<uint64_t, 4> Offsets;
3018 ComputeValueVTs(TLI, Ty, ValueVTs, &Offsets);
3019 unsigned NumValues = ValueVTs.size();
3020 if (NumValues == 0)
3021 return;
Misha Brukmanedf128a2005-04-21 22:36:52 +00003022
Dan Gohman475871a2008-07-27 21:46:04 +00003023 SDValue Root;
Dan Gohman8b4588f2008-07-25 00:04:14 +00003024 bool ConstantMemory = false;
Chris Lattnerd3948112005-01-17 22:19:26 +00003025 if (I.isVolatile())
Dan Gohman8b4588f2008-07-25 00:04:14 +00003026 // Serialize volatile loads with other side effects.
Chris Lattnerd3948112005-01-17 22:19:26 +00003027 Root = getRoot();
Dan Gohman7c3234c2008-08-27 23:52:12 +00003028 else if (AA->pointsToConstantMemory(SV)) {
Dan Gohman8b4588f2008-07-25 00:04:14 +00003029 // Do not serialize (non-volatile) loads of constant memory with anything.
3030 Root = DAG.getEntryNode();
3031 ConstantMemory = true;
3032 } else {
Chris Lattnerd3948112005-01-17 22:19:26 +00003033 // Do not serialize non-volatile loads against each other.
3034 Root = DAG.getRoot();
3035 }
Chris Lattner28b5b1c2006-03-15 22:19:46 +00003036
Dan Gohman475871a2008-07-27 21:46:04 +00003037 SmallVector<SDValue, 4> Values(NumValues);
3038 SmallVector<SDValue, 4> Chains(NumValues);
Dan Gohman1d685a42008-06-07 02:02:36 +00003039 MVT PtrVT = Ptr.getValueType();
3040 for (unsigned i = 0; i != NumValues; ++i) {
Dan Gohman475871a2008-07-27 21:46:04 +00003041 SDValue L = DAG.getLoad(ValueVTs[i], Root,
Dan Gohman1d685a42008-06-07 02:02:36 +00003042 DAG.getNode(ISD::ADD, PtrVT, Ptr,
3043 DAG.getConstant(Offsets[i], PtrVT)),
3044 SV, Offsets[i],
3045 isVolatile, Alignment);
3046 Values[i] = L;
3047 Chains[i] = L.getValue(1);
3048 }
Chris Lattner28b5b1c2006-03-15 22:19:46 +00003049
Dan Gohman8b4588f2008-07-25 00:04:14 +00003050 if (!ConstantMemory) {
Dan Gohman475871a2008-07-27 21:46:04 +00003051 SDValue Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
Dan Gohman8b4588f2008-07-25 00:04:14 +00003052 &Chains[0], NumValues);
3053 if (isVolatile)
3054 DAG.setRoot(Chain);
3055 else
3056 PendingLoads.push_back(Chain);
3057 }
Dan Gohman1d685a42008-06-07 02:02:36 +00003058
Duncan Sandsf9516202008-06-30 10:19:09 +00003059 setValue(&I, DAG.getMergeValues(DAG.getVTList(&ValueVTs[0], NumValues),
3060 &Values[0], NumValues));
Chris Lattner1c08c712005-01-07 07:47:53 +00003061}
3062
3063
3064void SelectionDAGLowering::visitStore(StoreInst &I) {
3065 Value *SrcV = I.getOperand(0);
Dan Gohman1d685a42008-06-07 02:02:36 +00003066 Value *PtrV = I.getOperand(1);
Dan Gohman1d685a42008-06-07 02:02:36 +00003067
3068 SmallVector<MVT, 4> ValueVTs;
3069 SmallVector<uint64_t, 4> Offsets;
3070 ComputeValueVTs(TLI, SrcV->getType(), ValueVTs, &Offsets);
3071 unsigned NumValues = ValueVTs.size();
Dan Gohman8a6ccb52008-06-09 15:21:47 +00003072 if (NumValues == 0)
3073 return;
Dan Gohman1d685a42008-06-07 02:02:36 +00003074
Dan Gohman90d33ee2008-07-30 18:36:51 +00003075 // Get the lowered operands. Note that we do this after
3076 // checking if NumResults is zero, because with zero results
3077 // the operands won't have values in the map.
3078 SDValue Src = getValue(SrcV);
3079 SDValue Ptr = getValue(PtrV);
3080
Dan Gohman475871a2008-07-27 21:46:04 +00003081 SDValue Root = getRoot();
3082 SmallVector<SDValue, 4> Chains(NumValues);
Dan Gohman1d685a42008-06-07 02:02:36 +00003083 MVT PtrVT = Ptr.getValueType();
3084 bool isVolatile = I.isVolatile();
3085 unsigned Alignment = I.getAlignment();
3086 for (unsigned i = 0; i != NumValues; ++i)
Gabor Greifba36cb52008-08-28 21:40:38 +00003087 Chains[i] = DAG.getStore(Root, SDValue(Src.getNode(), Src.getResNo() + i),
Dan Gohman1d685a42008-06-07 02:02:36 +00003088 DAG.getNode(ISD::ADD, PtrVT, Ptr,
3089 DAG.getConstant(Offsets[i], PtrVT)),
3090 PtrV, Offsets[i],
3091 isVolatile, Alignment);
3092
3093 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other, &Chains[0], NumValues));
Chris Lattner1c08c712005-01-07 07:47:53 +00003094}
3095
Chris Lattner0eade312006-03-24 02:22:33 +00003096/// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
3097/// node.
3098void SelectionDAGLowering::visitTargetIntrinsic(CallInst &I,
3099 unsigned Intrinsic) {
Duncan Sandsa3355ff2007-12-03 20:06:50 +00003100 bool HasChain = !I.doesNotAccessMemory();
3101 bool OnlyLoad = HasChain && I.onlyReadsMemory();
3102
Chris Lattner0eade312006-03-24 02:22:33 +00003103 // Build the operand list.
Dan Gohman475871a2008-07-27 21:46:04 +00003104 SmallVector<SDValue, 8> Ops;
Chris Lattnere58a7802006-04-02 03:41:14 +00003105 if (HasChain) { // If this intrinsic has side-effects, chainify it.
3106 if (OnlyLoad) {
3107 // We don't need to serialize loads against other loads.
3108 Ops.push_back(DAG.getRoot());
3109 } else {
3110 Ops.push_back(getRoot());
3111 }
3112 }
Chris Lattner0eade312006-03-24 02:22:33 +00003113
3114 // Add the intrinsic ID as an integer operand.
3115 Ops.push_back(DAG.getConstant(Intrinsic, TLI.getPointerTy()));
3116
3117 // Add all operands of the call to the operand list.
3118 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
Dan Gohman475871a2008-07-27 21:46:04 +00003119 SDValue Op = getValue(I.getOperand(i));
Chris Lattner0eade312006-03-24 02:22:33 +00003120 assert(TLI.isTypeLegal(Op.getValueType()) &&
3121 "Intrinsic uses a non-legal type?");
3122 Ops.push_back(Op);
3123 }
3124
Duncan Sands83ec4b62008-06-06 12:08:01 +00003125 std::vector<MVT> VTs;
Chris Lattner0eade312006-03-24 02:22:33 +00003126 if (I.getType() != Type::VoidTy) {
Duncan Sands83ec4b62008-06-06 12:08:01 +00003127 MVT VT = TLI.getValueType(I.getType());
3128 if (VT.isVector()) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00003129 const VectorType *DestTy = cast<VectorType>(I.getType());
Duncan Sands83ec4b62008-06-06 12:08:01 +00003130 MVT EltVT = TLI.getValueType(DestTy->getElementType());
Chris Lattner0eade312006-03-24 02:22:33 +00003131
Duncan Sands83ec4b62008-06-06 12:08:01 +00003132 VT = MVT::getVectorVT(EltVT, DestTy->getNumElements());
Chris Lattner0eade312006-03-24 02:22:33 +00003133 assert(VT != MVT::Other && "Intrinsic uses a non-legal type?");
3134 }
3135
3136 assert(TLI.isTypeLegal(VT) && "Intrinsic uses a non-legal type?");
3137 VTs.push_back(VT);
3138 }
3139 if (HasChain)
3140 VTs.push_back(MVT::Other);
3141
Duncan Sands83ec4b62008-06-06 12:08:01 +00003142 const MVT *VTList = DAG.getNodeValueTypes(VTs);
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00003143
Chris Lattner0eade312006-03-24 02:22:33 +00003144 // Create the node.
Dan Gohman475871a2008-07-27 21:46:04 +00003145 SDValue Result;
Chris Lattner48b61a72006-03-28 00:40:33 +00003146 if (!HasChain)
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00003147 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VTList, VTs.size(),
3148 &Ops[0], Ops.size());
Chris Lattner48b61a72006-03-28 00:40:33 +00003149 else if (I.getType() != Type::VoidTy)
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00003150 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, VTList, VTs.size(),
3151 &Ops[0], Ops.size());
Chris Lattner48b61a72006-03-28 00:40:33 +00003152 else
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00003153 Result = DAG.getNode(ISD::INTRINSIC_VOID, VTList, VTs.size(),
3154 &Ops[0], Ops.size());
Chris Lattner48b61a72006-03-28 00:40:33 +00003155
Chris Lattnere58a7802006-04-02 03:41:14 +00003156 if (HasChain) {
Gabor Greifba36cb52008-08-28 21:40:38 +00003157 SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
Chris Lattnere58a7802006-04-02 03:41:14 +00003158 if (OnlyLoad)
3159 PendingLoads.push_back(Chain);
3160 else
3161 DAG.setRoot(Chain);
3162 }
Chris Lattner0eade312006-03-24 02:22:33 +00003163 if (I.getType() != Type::VoidTy) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00003164 if (const VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
Duncan Sands83ec4b62008-06-06 12:08:01 +00003165 MVT VT = TLI.getValueType(PTy);
Dan Gohman7f321562007-06-25 16:23:39 +00003166 Result = DAG.getNode(ISD::BIT_CONVERT, VT, Result);
Chris Lattner0eade312006-03-24 02:22:33 +00003167 }
3168 setValue(&I, Result);
3169 }
3170}
3171
Duncan Sandsb4fd45e2007-07-06 09:10:03 +00003172/// ExtractTypeInfo - Returns the type info, possibly bitcast, encoded in V.
Duncan Sandscf26d7c2007-07-04 20:52:51 +00003173static GlobalVariable *ExtractTypeInfo (Value *V) {
Anton Korobeynikov0b12ecf2008-05-07 22:54:15 +00003174 V = V->stripPointerCasts();
Duncan Sandsb4fd45e2007-07-06 09:10:03 +00003175 GlobalVariable *GV = dyn_cast<GlobalVariable>(V);
Anton Korobeynikov4c71dfe2008-02-20 11:10:28 +00003176 assert ((GV || isa<ConstantPointerNull>(V)) &&
Duncan Sandscf26d7c2007-07-04 20:52:51 +00003177 "TypeInfo must be a global variable or NULL");
3178 return GV;
3179}
3180
Duncan Sandsf4070822007-06-15 19:04:19 +00003181/// addCatchInfo - Extract the personality and type infos from an eh.selector
Duncan Sandscf26d7c2007-07-04 20:52:51 +00003182/// call, and add them to the specified machine basic block.
Duncan Sandsf4070822007-06-15 19:04:19 +00003183static void addCatchInfo(CallInst &I, MachineModuleInfo *MMI,
3184 MachineBasicBlock *MBB) {
3185 // Inform the MachineModuleInfo of the personality for this landing pad.
3186 ConstantExpr *CE = cast<ConstantExpr>(I.getOperand(2));
3187 assert(CE->getOpcode() == Instruction::BitCast &&
3188 isa<Function>(CE->getOperand(0)) &&
3189 "Personality should be a function");
3190 MMI->addPersonality(MBB, cast<Function>(CE->getOperand(0)));
3191
3192 // Gather all the type infos for this landing pad and pass them along to
3193 // MachineModuleInfo.
3194 std::vector<GlobalVariable *> TyInfo;
Duncan Sandscf26d7c2007-07-04 20:52:51 +00003195 unsigned N = I.getNumOperands();
3196
3197 for (unsigned i = N - 1; i > 2; --i) {
3198 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(i))) {
3199 unsigned FilterLength = CI->getZExtValue();
Duncan Sands6590b042007-08-27 15:47:50 +00003200 unsigned FirstCatch = i + FilterLength + !FilterLength;
Duncan Sandscf26d7c2007-07-04 20:52:51 +00003201 assert (FirstCatch <= N && "Invalid filter length");
3202
3203 if (FirstCatch < N) {
3204 TyInfo.reserve(N - FirstCatch);
3205 for (unsigned j = FirstCatch; j < N; ++j)
3206 TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
3207 MMI->addCatchTypeInfo(MBB, TyInfo);
3208 TyInfo.clear();
3209 }
3210
Duncan Sands6590b042007-08-27 15:47:50 +00003211 if (!FilterLength) {
3212 // Cleanup.
3213 MMI->addCleanup(MBB);
3214 } else {
3215 // Filter.
3216 TyInfo.reserve(FilterLength - 1);
3217 for (unsigned j = i + 1; j < FirstCatch; ++j)
3218 TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
3219 MMI->addFilterTypeInfo(MBB, TyInfo);
3220 TyInfo.clear();
3221 }
Duncan Sandscf26d7c2007-07-04 20:52:51 +00003222
3223 N = i;
3224 }
Duncan Sandsf4070822007-06-15 19:04:19 +00003225 }
Duncan Sandscf26d7c2007-07-04 20:52:51 +00003226
3227 if (N > 3) {
3228 TyInfo.reserve(N - 3);
3229 for (unsigned j = 3; j < N; ++j)
3230 TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
Duncan Sandsf4070822007-06-15 19:04:19 +00003231 MMI->addCatchTypeInfo(MBB, TyInfo);
Duncan Sandscf26d7c2007-07-04 20:52:51 +00003232 }
Duncan Sandsf4070822007-06-15 19:04:19 +00003233}
3234
Mon P Wang63307c32008-05-05 19:05:59 +00003235
3236/// Inlined utility function to implement binary input atomic intrinsics for
3237// visitIntrinsicCall: I is a call instruction
3238// Op is the associated NodeType for I
3239const char *
3240SelectionDAGLowering::implVisitBinaryAtomic(CallInst& I, ISD::NodeType Op) {
Dan Gohman475871a2008-07-27 21:46:04 +00003241 SDValue Root = getRoot();
3242 SDValue L = DAG.getAtomic(Op, Root,
Mon P Wang63307c32008-05-05 19:05:59 +00003243 getValue(I.getOperand(1)),
Dan Gohmanfd4418f2008-06-25 16:07:49 +00003244 getValue(I.getOperand(2)),
Mon P Wang28873102008-06-25 08:15:39 +00003245 I.getOperand(1));
Mon P Wang63307c32008-05-05 19:05:59 +00003246 setValue(&I, L);
3247 DAG.setRoot(L.getValue(1));
3248 return 0;
3249}
3250
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003251/// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
3252/// we want to emit this as a call to a named external function, return the name
3253/// otherwise lower it and return null.
3254const char *
3255SelectionDAGLowering::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
3256 switch (Intrinsic) {
Chris Lattner0eade312006-03-24 02:22:33 +00003257 default:
3258 // By default, turn this into a target intrinsic node.
3259 visitTargetIntrinsic(I, Intrinsic);
3260 return 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003261 case Intrinsic::vastart: visitVAStart(I); return 0;
3262 case Intrinsic::vaend: visitVAEnd(I); return 0;
3263 case Intrinsic::vacopy: visitVACopy(I); return 0;
Nate Begemanbcc5f362007-01-29 22:58:52 +00003264 case Intrinsic::returnaddress:
3265 setValue(&I, DAG.getNode(ISD::RETURNADDR, TLI.getPointerTy(),
3266 getValue(I.getOperand(1))));
3267 return 0;
3268 case Intrinsic::frameaddress:
3269 setValue(&I, DAG.getNode(ISD::FRAMEADDR, TLI.getPointerTy(),
3270 getValue(I.getOperand(1))));
3271 return 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003272 case Intrinsic::setjmp:
Anton Korobeynikovd27a2582006-12-10 23:12:42 +00003273 return "_setjmp"+!TLI.usesUnderscoreSetJmp();
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003274 break;
3275 case Intrinsic::longjmp:
Anton Korobeynikovd27a2582006-12-10 23:12:42 +00003276 return "_longjmp"+!TLI.usesUnderscoreLongJmp();
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003277 break;
Chris Lattner03dd4652006-03-03 00:00:25 +00003278 case Intrinsic::memcpy_i32:
Dan Gohman707e0182008-04-12 04:36:06 +00003279 case Intrinsic::memcpy_i64: {
Dan Gohman475871a2008-07-27 21:46:04 +00003280 SDValue Op1 = getValue(I.getOperand(1));
3281 SDValue Op2 = getValue(I.getOperand(2));
3282 SDValue Op3 = getValue(I.getOperand(3));
Dan Gohman707e0182008-04-12 04:36:06 +00003283 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
3284 DAG.setRoot(DAG.getMemcpy(getRoot(), Op1, Op2, Op3, Align, false,
3285 I.getOperand(1), 0, I.getOperand(2), 0));
Chris Lattner03dd4652006-03-03 00:00:25 +00003286 return 0;
Dan Gohman707e0182008-04-12 04:36:06 +00003287 }
Chris Lattner03dd4652006-03-03 00:00:25 +00003288 case Intrinsic::memset_i32:
Dan Gohman707e0182008-04-12 04:36:06 +00003289 case Intrinsic::memset_i64: {
Dan Gohman475871a2008-07-27 21:46:04 +00003290 SDValue Op1 = getValue(I.getOperand(1));
3291 SDValue Op2 = getValue(I.getOperand(2));
3292 SDValue Op3 = getValue(I.getOperand(3));
Dan Gohman707e0182008-04-12 04:36:06 +00003293 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
3294 DAG.setRoot(DAG.getMemset(getRoot(), Op1, Op2, Op3, Align,
3295 I.getOperand(1), 0));
Chris Lattner03dd4652006-03-03 00:00:25 +00003296 return 0;
Dan Gohman707e0182008-04-12 04:36:06 +00003297 }
Chris Lattner03dd4652006-03-03 00:00:25 +00003298 case Intrinsic::memmove_i32:
Dan Gohman707e0182008-04-12 04:36:06 +00003299 case Intrinsic::memmove_i64: {
Dan Gohman475871a2008-07-27 21:46:04 +00003300 SDValue Op1 = getValue(I.getOperand(1));
3301 SDValue Op2 = getValue(I.getOperand(2));
3302 SDValue Op3 = getValue(I.getOperand(3));
Dan Gohman707e0182008-04-12 04:36:06 +00003303 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
3304
3305 // If the source and destination are known to not be aliases, we can
3306 // lower memmove as memcpy.
3307 uint64_t Size = -1ULL;
3308 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op3))
3309 Size = C->getValue();
Dan Gohman7c3234c2008-08-27 23:52:12 +00003310 if (AA->alias(I.getOperand(1), Size, I.getOperand(2), Size) ==
Dan Gohman707e0182008-04-12 04:36:06 +00003311 AliasAnalysis::NoAlias) {
3312 DAG.setRoot(DAG.getMemcpy(getRoot(), Op1, Op2, Op3, Align, false,
3313 I.getOperand(1), 0, I.getOperand(2), 0));
3314 return 0;
3315 }
3316
3317 DAG.setRoot(DAG.getMemmove(getRoot(), Op1, Op2, Op3, Align,
3318 I.getOperand(1), 0, I.getOperand(2), 0));
Chris Lattner03dd4652006-03-03 00:00:25 +00003319 return 0;
Dan Gohman707e0182008-04-12 04:36:06 +00003320 }
Chris Lattner86cb6432005-12-13 17:40:33 +00003321 case Intrinsic::dbg_stoppoint: {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00003322 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskey43970fe2006-03-23 18:06:46 +00003323 DbgStopPointInst &SPI = cast<DbgStopPointInst>(I);
Jim Laskey44c3b9f2007-01-26 21:22:28 +00003324 if (MMI && SPI.getContext() && MMI->Verify(SPI.getContext())) {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00003325 DebugInfoDesc *DD = MMI->getDescFor(SPI.getContext());
Jim Laskeyce72b172006-02-11 01:01:30 +00003326 assert(DD && "Not a debug information descriptor");
Dan Gohman7f460202008-06-30 20:59:49 +00003327 DAG.setRoot(DAG.getDbgStopPoint(getRoot(),
3328 SPI.getLine(),
3329 SPI.getColumn(),
3330 cast<CompileUnitDesc>(DD)));
Chris Lattner86cb6432005-12-13 17:40:33 +00003331 }
Jim Laskey43970fe2006-03-23 18:06:46 +00003332
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +00003333 return 0;
Chris Lattner36ce6912005-11-29 06:21:05 +00003334 }
Jim Laskey43970fe2006-03-23 18:06:46 +00003335 case Intrinsic::dbg_region_start: {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00003336 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskey43970fe2006-03-23 18:06:46 +00003337 DbgRegionStartInst &RSI = cast<DbgRegionStartInst>(I);
Jim Laskey44c3b9f2007-01-26 21:22:28 +00003338 if (MMI && RSI.getContext() && MMI->Verify(RSI.getContext())) {
3339 unsigned LabelID = MMI->RecordRegionStart(RSI.getContext());
Dan Gohman44066042008-07-01 00:05:16 +00003340 DAG.setRoot(DAG.getLabel(ISD::DBG_LABEL, getRoot(), LabelID));
Jim Laskey43970fe2006-03-23 18:06:46 +00003341 }
3342
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +00003343 return 0;
Jim Laskey43970fe2006-03-23 18:06:46 +00003344 }
3345 case Intrinsic::dbg_region_end: {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00003346 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskey43970fe2006-03-23 18:06:46 +00003347 DbgRegionEndInst &REI = cast<DbgRegionEndInst>(I);
Jim Laskey44c3b9f2007-01-26 21:22:28 +00003348 if (MMI && REI.getContext() && MMI->Verify(REI.getContext())) {
3349 unsigned LabelID = MMI->RecordRegionEnd(REI.getContext());
Dan Gohman44066042008-07-01 00:05:16 +00003350 DAG.setRoot(DAG.getLabel(ISD::DBG_LABEL, getRoot(), LabelID));
Jim Laskey43970fe2006-03-23 18:06:46 +00003351 }
3352
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +00003353 return 0;
Jim Laskey43970fe2006-03-23 18:06:46 +00003354 }
3355 case Intrinsic::dbg_func_start: {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00003356 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Evan Cheng1b08bbc2008-02-01 09:10:45 +00003357 if (!MMI) return 0;
Jim Laskey43970fe2006-03-23 18:06:46 +00003358 DbgFuncStartInst &FSI = cast<DbgFuncStartInst>(I);
Evan Cheng1b08bbc2008-02-01 09:10:45 +00003359 Value *SP = FSI.getSubprogram();
3360 if (SP && MMI->Verify(SP)) {
3361 // llvm.dbg.func.start implicitly defines a dbg_stoppoint which is
3362 // what (most?) gdb expects.
3363 DebugInfoDesc *DD = MMI->getDescFor(SP);
3364 assert(DD && "Not a debug information descriptor");
3365 SubprogramDesc *Subprogram = cast<SubprogramDesc>(DD);
3366 const CompileUnitDesc *CompileUnit = Subprogram->getFile();
Dan Gohman99fe47b2008-06-30 22:21:03 +00003367 unsigned SrcFile = MMI->RecordSource(CompileUnit);
Evan Cheng1b08bbc2008-02-01 09:10:45 +00003368 // Record the source line but does create a label. It will be emitted
3369 // at asm emission time.
3370 MMI->RecordSourceLine(Subprogram->getLine(), 0, SrcFile);
Jim Laskey43970fe2006-03-23 18:06:46 +00003371 }
3372
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +00003373 return 0;
Jim Laskey43970fe2006-03-23 18:06:46 +00003374 }
3375 case Intrinsic::dbg_declare: {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00003376 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskey43970fe2006-03-23 18:06:46 +00003377 DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
Evan Chenga844bde2008-02-02 04:07:54 +00003378 Value *Variable = DI.getVariable();
3379 if (MMI && Variable && MMI->Verify(Variable))
3380 DAG.setRoot(DAG.getNode(ISD::DECLARE, MVT::Other, getRoot(),
3381 getValue(DI.getAddress()), getValue(Variable)));
Jim Laskey43970fe2006-03-23 18:06:46 +00003382 return 0;
3383 }
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003384
Jim Laskeyb180aa12007-02-21 22:53:45 +00003385 case Intrinsic::eh_exception: {
Dale Johannesen1532f3d2008-04-02 00:25:04 +00003386 if (!CurMBB->isLandingPad()) {
3387 // FIXME: Mark exception register as live in. Hack for PR1508.
3388 unsigned Reg = TLI.getExceptionAddressRegister();
3389 if (Reg) CurMBB->addLiveIn(Reg);
Jim Laskey735b6f82007-02-22 15:38:06 +00003390 }
Dale Johannesen1532f3d2008-04-02 00:25:04 +00003391 // Insert the EXCEPTIONADDR instruction.
3392 SDVTList VTs = DAG.getVTList(TLI.getPointerTy(), MVT::Other);
Dan Gohman475871a2008-07-27 21:46:04 +00003393 SDValue Ops[1];
Dale Johannesen1532f3d2008-04-02 00:25:04 +00003394 Ops[0] = DAG.getRoot();
Dan Gohman475871a2008-07-27 21:46:04 +00003395 SDValue Op = DAG.getNode(ISD::EXCEPTIONADDR, VTs, Ops, 1);
Dale Johannesen1532f3d2008-04-02 00:25:04 +00003396 setValue(&I, Op);
3397 DAG.setRoot(Op.getValue(1));
Jim Laskeyb180aa12007-02-21 22:53:45 +00003398 return 0;
3399 }
3400
Anton Korobeynikov8806c7b2007-09-07 11:39:35 +00003401 case Intrinsic::eh_selector_i32:
3402 case Intrinsic::eh_selector_i64: {
Jim Laskeyb180aa12007-02-21 22:53:45 +00003403 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Duncan Sands83ec4b62008-06-06 12:08:01 +00003404 MVT VT = (Intrinsic == Intrinsic::eh_selector_i32 ?
Anton Korobeynikov8806c7b2007-09-07 11:39:35 +00003405 MVT::i32 : MVT::i64);
3406
Dale Johannesen1532f3d2008-04-02 00:25:04 +00003407 if (MMI) {
Duncan Sandsf4070822007-06-15 19:04:19 +00003408 if (CurMBB->isLandingPad())
3409 addCatchInfo(I, MMI, CurMBB);
Evan Chenge47c3332007-06-27 18:45:32 +00003410 else {
Duncan Sandsf4070822007-06-15 19:04:19 +00003411#ifndef NDEBUG
Duncan Sandsf4070822007-06-15 19:04:19 +00003412 FuncInfo.CatchInfoLost.insert(&I);
3413#endif
Duncan Sands90291952007-07-06 09:18:59 +00003414 // FIXME: Mark exception selector register as live in. Hack for PR1508.
3415 unsigned Reg = TLI.getExceptionSelectorRegister();
3416 if (Reg) CurMBB->addLiveIn(Reg);
Evan Chenge47c3332007-06-27 18:45:32 +00003417 }
Jim Laskey735b6f82007-02-22 15:38:06 +00003418
3419 // Insert the EHSELECTION instruction.
Anton Korobeynikov8806c7b2007-09-07 11:39:35 +00003420 SDVTList VTs = DAG.getVTList(VT, MVT::Other);
Dan Gohman475871a2008-07-27 21:46:04 +00003421 SDValue Ops[2];
Jim Laskey735b6f82007-02-22 15:38:06 +00003422 Ops[0] = getValue(I.getOperand(1));
3423 Ops[1] = getRoot();
Dan Gohman475871a2008-07-27 21:46:04 +00003424 SDValue Op = DAG.getNode(ISD::EHSELECTION, VTs, Ops, 2);
Jim Laskey735b6f82007-02-22 15:38:06 +00003425 setValue(&I, Op);
3426 DAG.setRoot(Op.getValue(1));
Jim Laskey7a1de982007-02-24 09:45:44 +00003427 } else {
Anton Korobeynikov8806c7b2007-09-07 11:39:35 +00003428 setValue(&I, DAG.getConstant(0, VT));
Jim Laskey735b6f82007-02-22 15:38:06 +00003429 }
Jim Laskeyb180aa12007-02-21 22:53:45 +00003430
3431 return 0;
3432 }
Anton Korobeynikov8806c7b2007-09-07 11:39:35 +00003433
3434 case Intrinsic::eh_typeid_for_i32:
3435 case Intrinsic::eh_typeid_for_i64: {
Jim Laskeyb180aa12007-02-21 22:53:45 +00003436 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Duncan Sands83ec4b62008-06-06 12:08:01 +00003437 MVT VT = (Intrinsic == Intrinsic::eh_typeid_for_i32 ?
Anton Korobeynikov8806c7b2007-09-07 11:39:35 +00003438 MVT::i32 : MVT::i64);
Jim Laskeyb180aa12007-02-21 22:53:45 +00003439
Jim Laskey735b6f82007-02-22 15:38:06 +00003440 if (MMI) {
3441 // Find the type id for the given typeinfo.
Duncan Sandscf26d7c2007-07-04 20:52:51 +00003442 GlobalVariable *GV = ExtractTypeInfo(I.getOperand(1));
Duncan Sands3b346362007-05-04 17:12:26 +00003443
Jim Laskey735b6f82007-02-22 15:38:06 +00003444 unsigned TypeID = MMI->getTypeIDFor(GV);
Anton Korobeynikov8806c7b2007-09-07 11:39:35 +00003445 setValue(&I, DAG.getConstant(TypeID, VT));
Jim Laskey7a1de982007-02-24 09:45:44 +00003446 } else {
Duncan Sandsf664e412007-07-06 14:46:23 +00003447 // Return something different to eh_selector.
Anton Korobeynikov8806c7b2007-09-07 11:39:35 +00003448 setValue(&I, DAG.getConstant(1, VT));
Jim Laskey735b6f82007-02-22 15:38:06 +00003449 }
Jim Laskeyb180aa12007-02-21 22:53:45 +00003450
3451 return 0;
3452 }
3453
Anton Korobeynikov2365f512007-07-14 14:06:15 +00003454 case Intrinsic::eh_return: {
3455 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3456
Dale Johannesen1532f3d2008-04-02 00:25:04 +00003457 if (MMI) {
Anton Korobeynikov2365f512007-07-14 14:06:15 +00003458 MMI->setCallsEHReturn(true);
3459 DAG.setRoot(DAG.getNode(ISD::EH_RETURN,
3460 MVT::Other,
Dan Gohman86e1ebf2008-03-27 19:56:19 +00003461 getControlRoot(),
Anton Korobeynikov2365f512007-07-14 14:06:15 +00003462 getValue(I.getOperand(1)),
3463 getValue(I.getOperand(2))));
3464 } else {
3465 setValue(&I, DAG.getConstant(0, TLI.getPointerTy()));
3466 }
3467
3468 return 0;
3469 }
3470
3471 case Intrinsic::eh_unwind_init: {
3472 if (MachineModuleInfo *MMI = DAG.getMachineModuleInfo()) {
3473 MMI->setCallsUnwindInit(true);
3474 }
3475
3476 return 0;
3477 }
3478
3479 case Intrinsic::eh_dwarf_cfa: {
Duncan Sands83ec4b62008-06-06 12:08:01 +00003480 MVT VT = getValue(I.getOperand(1)).getValueType();
Dan Gohman475871a2008-07-27 21:46:04 +00003481 SDValue CfaArg;
Duncan Sands8e4eb092008-06-08 20:54:56 +00003482 if (VT.bitsGT(TLI.getPointerTy()))
Dale Johannesen1532f3d2008-04-02 00:25:04 +00003483 CfaArg = DAG.getNode(ISD::TRUNCATE,
3484 TLI.getPointerTy(), getValue(I.getOperand(1)));
3485 else
3486 CfaArg = DAG.getNode(ISD::SIGN_EXTEND,
3487 TLI.getPointerTy(), getValue(I.getOperand(1)));
Anton Korobeynikov2365f512007-07-14 14:06:15 +00003488
Dan Gohman475871a2008-07-27 21:46:04 +00003489 SDValue Offset = DAG.getNode(ISD::ADD,
Dale Johannesen1532f3d2008-04-02 00:25:04 +00003490 TLI.getPointerTy(),
3491 DAG.getNode(ISD::FRAME_TO_ARGS_OFFSET,
3492 TLI.getPointerTy()),
3493 CfaArg);
3494 setValue(&I, DAG.getNode(ISD::ADD,
3495 TLI.getPointerTy(),
3496 DAG.getNode(ISD::FRAMEADDR,
3497 TLI.getPointerTy(),
3498 DAG.getConstant(0,
3499 TLI.getPointerTy())),
3500 Offset));
Anton Korobeynikov2365f512007-07-14 14:06:15 +00003501 return 0;
3502 }
3503
Dale Johannesen9ab7fb32007-10-02 17:43:59 +00003504 case Intrinsic::sqrt:
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003505 setValue(&I, DAG.getNode(ISD::FSQRT,
3506 getValue(I.getOperand(1)).getValueType(),
3507 getValue(I.getOperand(1))));
3508 return 0;
Dale Johannesen9ab7fb32007-10-02 17:43:59 +00003509 case Intrinsic::powi:
Chris Lattner6ddf8ed2006-09-09 06:03:30 +00003510 setValue(&I, DAG.getNode(ISD::FPOWI,
3511 getValue(I.getOperand(1)).getValueType(),
3512 getValue(I.getOperand(1)),
3513 getValue(I.getOperand(2))));
3514 return 0;
Dan Gohmanac9385a2007-10-12 00:01:22 +00003515 case Intrinsic::sin:
3516 setValue(&I, DAG.getNode(ISD::FSIN,
3517 getValue(I.getOperand(1)).getValueType(),
3518 getValue(I.getOperand(1))));
3519 return 0;
3520 case Intrinsic::cos:
3521 setValue(&I, DAG.getNode(ISD::FCOS,
3522 getValue(I.getOperand(1)).getValueType(),
3523 getValue(I.getOperand(1))));
3524 return 0;
3525 case Intrinsic::pow:
3526 setValue(&I, DAG.getNode(ISD::FPOW,
3527 getValue(I.getOperand(1)).getValueType(),
3528 getValue(I.getOperand(1)),
3529 getValue(I.getOperand(2))));
3530 return 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003531 case Intrinsic::pcmarker: {
Dan Gohman475871a2008-07-27 21:46:04 +00003532 SDValue Tmp = getValue(I.getOperand(1));
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003533 DAG.setRoot(DAG.getNode(ISD::PCMARKER, MVT::Other, getRoot(), Tmp));
3534 return 0;
3535 }
Andrew Lenharth8b91c772005-11-11 22:48:54 +00003536 case Intrinsic::readcyclecounter: {
Dan Gohman475871a2008-07-27 21:46:04 +00003537 SDValue Op = getRoot();
3538 SDValue Tmp = DAG.getNode(ISD::READCYCLECOUNTER,
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00003539 DAG.getNodeValueTypes(MVT::i64, MVT::Other), 2,
3540 &Op, 1);
Andrew Lenharth8b91c772005-11-11 22:48:54 +00003541 setValue(&I, Tmp);
3542 DAG.setRoot(Tmp.getValue(1));
Andrew Lenharth51b8d542005-11-11 16:47:30 +00003543 return 0;
Andrew Lenharth8b91c772005-11-11 22:48:54 +00003544 }
Chris Lattnerc6eb6d72007-04-10 03:20:39 +00003545 case Intrinsic::part_select: {
Reid Spencer3f108cb2007-04-05 01:20:18 +00003546 // Currently not implemented: just abort
Reid Spencerf75b8742007-04-12 02:48:46 +00003547 assert(0 && "part_select intrinsic not implemented");
3548 abort();
3549 }
3550 case Intrinsic::part_set: {
3551 // Currently not implemented: just abort
3552 assert(0 && "part_set intrinsic not implemented");
Reid Spencer3f108cb2007-04-05 01:20:18 +00003553 abort();
Reid Spenceraddd11d2007-04-04 23:48:25 +00003554 }
Reid Spencera4f9c4d2007-04-01 07:34:11 +00003555 case Intrinsic::bswap:
Nate Begemand88fc032006-01-14 03:14:10 +00003556 setValue(&I, DAG.getNode(ISD::BSWAP,
3557 getValue(I.getOperand(1)).getValueType(),
3558 getValue(I.getOperand(1))));
3559 return 0;
Reid Spencera4f9c4d2007-04-01 07:34:11 +00003560 case Intrinsic::cttz: {
Dan Gohman475871a2008-07-27 21:46:04 +00003561 SDValue Arg = getValue(I.getOperand(1));
Duncan Sands83ec4b62008-06-06 12:08:01 +00003562 MVT Ty = Arg.getValueType();
Dan Gohman475871a2008-07-27 21:46:04 +00003563 SDValue result = DAG.getNode(ISD::CTTZ, Ty, Arg);
Reid Spencera4f9c4d2007-04-01 07:34:11 +00003564 setValue(&I, result);
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003565 return 0;
Reid Spencera4f9c4d2007-04-01 07:34:11 +00003566 }
3567 case Intrinsic::ctlz: {
Dan Gohman475871a2008-07-27 21:46:04 +00003568 SDValue Arg = getValue(I.getOperand(1));
Duncan Sands83ec4b62008-06-06 12:08:01 +00003569 MVT Ty = Arg.getValueType();
Dan Gohman475871a2008-07-27 21:46:04 +00003570 SDValue result = DAG.getNode(ISD::CTLZ, Ty, Arg);
Reid Spencera4f9c4d2007-04-01 07:34:11 +00003571 setValue(&I, result);
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003572 return 0;
Reid Spencera4f9c4d2007-04-01 07:34:11 +00003573 }
3574 case Intrinsic::ctpop: {
Dan Gohman475871a2008-07-27 21:46:04 +00003575 SDValue Arg = getValue(I.getOperand(1));
Duncan Sands83ec4b62008-06-06 12:08:01 +00003576 MVT Ty = Arg.getValueType();
Dan Gohman475871a2008-07-27 21:46:04 +00003577 SDValue result = DAG.getNode(ISD::CTPOP, Ty, Arg);
Reid Spencera4f9c4d2007-04-01 07:34:11 +00003578 setValue(&I, result);
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003579 return 0;
Reid Spencera4f9c4d2007-04-01 07:34:11 +00003580 }
Chris Lattner140d53c2006-01-13 02:50:02 +00003581 case Intrinsic::stacksave: {
Dan Gohman475871a2008-07-27 21:46:04 +00003582 SDValue Op = getRoot();
3583 SDValue Tmp = DAG.getNode(ISD::STACKSAVE,
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00003584 DAG.getNodeValueTypes(TLI.getPointerTy(), MVT::Other), 2, &Op, 1);
Chris Lattner140d53c2006-01-13 02:50:02 +00003585 setValue(&I, Tmp);
3586 DAG.setRoot(Tmp.getValue(1));
3587 return 0;
3588 }
Chris Lattner39a17dd2006-01-23 05:22:07 +00003589 case Intrinsic::stackrestore: {
Dan Gohman475871a2008-07-27 21:46:04 +00003590 SDValue Tmp = getValue(I.getOperand(1));
Chris Lattner39a17dd2006-01-23 05:22:07 +00003591 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, MVT::Other, getRoot(), Tmp));
Chris Lattner140d53c2006-01-13 02:50:02 +00003592 return 0;
Chris Lattner39a17dd2006-01-23 05:22:07 +00003593 }
Tanya Lattner24e5aad2007-06-15 22:26:58 +00003594 case Intrinsic::var_annotation:
3595 // Discard annotate attributes
3596 return 0;
Duncan Sands36397f52007-07-27 12:58:54 +00003597
Duncan Sands36397f52007-07-27 12:58:54 +00003598 case Intrinsic::init_trampoline: {
Anton Korobeynikov0b12ecf2008-05-07 22:54:15 +00003599 const Function *F = cast<Function>(I.getOperand(2)->stripPointerCasts());
Duncan Sands36397f52007-07-27 12:58:54 +00003600
Dan Gohman475871a2008-07-27 21:46:04 +00003601 SDValue Ops[6];
Duncan Sands36397f52007-07-27 12:58:54 +00003602 Ops[0] = getRoot();
3603 Ops[1] = getValue(I.getOperand(1));
3604 Ops[2] = getValue(I.getOperand(2));
3605 Ops[3] = getValue(I.getOperand(3));
3606 Ops[4] = DAG.getSrcValue(I.getOperand(1));
3607 Ops[5] = DAG.getSrcValue(F);
3608
Dan Gohman475871a2008-07-27 21:46:04 +00003609 SDValue Tmp = DAG.getNode(ISD::TRAMPOLINE,
Duncan Sandsf7331b32007-09-11 14:10:23 +00003610 DAG.getNodeValueTypes(TLI.getPointerTy(),
3611 MVT::Other), 2,
3612 Ops, 6);
3613
3614 setValue(&I, Tmp);
3615 DAG.setRoot(Tmp.getValue(1));
Duncan Sands36397f52007-07-27 12:58:54 +00003616 return 0;
3617 }
Gordon Henriksence224772008-01-07 01:30:38 +00003618
3619 case Intrinsic::gcroot:
Gordon Henriksen5eca0752008-08-17 18:44:35 +00003620 if (GFI) {
Gordon Henriksence224772008-01-07 01:30:38 +00003621 Value *Alloca = I.getOperand(1);
3622 Constant *TypeMap = cast<Constant>(I.getOperand(2));
3623
Gabor Greifba36cb52008-08-28 21:40:38 +00003624 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
Gordon Henriksen5eca0752008-08-17 18:44:35 +00003625 GFI->addStackRoot(FI->getIndex(), TypeMap);
Gordon Henriksence224772008-01-07 01:30:38 +00003626 }
3627 return 0;
3628
3629 case Intrinsic::gcread:
3630 case Intrinsic::gcwrite:
Gordon Henriksen5eca0752008-08-17 18:44:35 +00003631 assert(0 && "GC failed to lower gcread/gcwrite intrinsics!");
Gordon Henriksence224772008-01-07 01:30:38 +00003632 return 0;
3633
Anton Korobeynikov917c2a62007-11-15 23:25:33 +00003634 case Intrinsic::flt_rounds: {
Dan Gohman1a024862008-01-31 00:41:03 +00003635 setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, MVT::i32));
Anton Korobeynikov917c2a62007-11-15 23:25:33 +00003636 return 0;
3637 }
Anton Korobeynikov66fac792008-01-15 07:02:33 +00003638
3639 case Intrinsic::trap: {
3640 DAG.setRoot(DAG.getNode(ISD::TRAP, MVT::Other, getRoot()));
3641 return 0;
3642 }
Evan Cheng27b7db52008-03-08 00:58:38 +00003643 case Intrinsic::prefetch: {
Dan Gohman475871a2008-07-27 21:46:04 +00003644 SDValue Ops[4];
Evan Cheng27b7db52008-03-08 00:58:38 +00003645 Ops[0] = getRoot();
3646 Ops[1] = getValue(I.getOperand(1));
3647 Ops[2] = getValue(I.getOperand(2));
3648 Ops[3] = getValue(I.getOperand(3));
3649 DAG.setRoot(DAG.getNode(ISD::PREFETCH, MVT::Other, &Ops[0], 4));
3650 return 0;
3651 }
3652
Andrew Lenharth22c5c1b2008-02-16 01:24:58 +00003653 case Intrinsic::memory_barrier: {
Dan Gohman475871a2008-07-27 21:46:04 +00003654 SDValue Ops[6];
Andrew Lenharth22c5c1b2008-02-16 01:24:58 +00003655 Ops[0] = getRoot();
3656 for (int x = 1; x < 6; ++x)
3657 Ops[x] = getValue(I.getOperand(x));
3658
3659 DAG.setRoot(DAG.getNode(ISD::MEMBARRIER, MVT::Other, &Ops[0], 6));
3660 return 0;
3661 }
Mon P Wang28873102008-06-25 08:15:39 +00003662 case Intrinsic::atomic_cmp_swap: {
Dan Gohman475871a2008-07-27 21:46:04 +00003663 SDValue Root = getRoot();
Dale Johannesene00a8a22008-08-28 02:44:49 +00003664 SDValue L;
3665 switch (getValue(I.getOperand(2)).getValueType().getSimpleVT()) {
3666 case MVT::i8:
3667 L = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP_8, Root,
3668 getValue(I.getOperand(1)),
3669 getValue(I.getOperand(2)),
3670 getValue(I.getOperand(3)),
3671 I.getOperand(1));
3672 break;
3673 case MVT::i16:
3674 L = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP_16, Root,
3675 getValue(I.getOperand(1)),
3676 getValue(I.getOperand(2)),
3677 getValue(I.getOperand(3)),
3678 I.getOperand(1));
3679 break;
3680 case MVT::i32:
3681 L = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP_32, Root,
3682 getValue(I.getOperand(1)),
3683 getValue(I.getOperand(2)),
3684 getValue(I.getOperand(3)),
3685 I.getOperand(1));
3686 break;
3687 case MVT::i64:
3688 L = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP_64, Root,
3689 getValue(I.getOperand(1)),
3690 getValue(I.getOperand(2)),
3691 getValue(I.getOperand(3)),
3692 I.getOperand(1));
3693 break;
3694 default:
3695 assert(0 && "Invalid atomic type");
3696 abort();
3697 }
Andrew Lenharthab0b9492008-02-21 06:45:13 +00003698 setValue(&I, L);
3699 DAG.setRoot(L.getValue(1));
3700 return 0;
3701 }
Mon P Wang28873102008-06-25 08:15:39 +00003702 case Intrinsic::atomic_load_add:
Dale Johannesene00a8a22008-08-28 02:44:49 +00003703 switch (getValue(I.getOperand(2)).getValueType().getSimpleVT()) {
3704 case MVT::i8:
3705 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_ADD_8);
3706 case MVT::i16:
3707 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_ADD_16);
3708 case MVT::i32:
3709 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_ADD_32);
3710 case MVT::i64:
3711 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_ADD_64);
3712 default:
3713 assert(0 && "Invalid atomic type");
3714 abort();
3715 }
Mon P Wang28873102008-06-25 08:15:39 +00003716 case Intrinsic::atomic_load_sub:
Dale Johannesene00a8a22008-08-28 02:44:49 +00003717 switch (getValue(I.getOperand(2)).getValueType().getSimpleVT()) {
3718 case MVT::i8:
3719 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_SUB_8);
3720 case MVT::i16:
3721 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_SUB_16);
3722 case MVT::i32:
3723 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_SUB_32);
3724 case MVT::i64:
3725 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_SUB_64);
3726 default:
3727 assert(0 && "Invalid atomic type");
3728 abort();
3729 }
Mon P Wang63307c32008-05-05 19:05:59 +00003730 case Intrinsic::atomic_load_or:
Dale Johannesene00a8a22008-08-28 02:44:49 +00003731 switch (getValue(I.getOperand(2)).getValueType().getSimpleVT()) {
3732 case MVT::i8:
3733 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_OR_8);
3734 case MVT::i16:
3735 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_OR_16);
3736 case MVT::i32:
3737 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_OR_32);
3738 case MVT::i64:
3739 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_OR_64);
3740 default:
3741 assert(0 && "Invalid atomic type");
3742 abort();
3743 }
Mon P Wang63307c32008-05-05 19:05:59 +00003744 case Intrinsic::atomic_load_xor:
Dale Johannesene00a8a22008-08-28 02:44:49 +00003745 switch (getValue(I.getOperand(2)).getValueType().getSimpleVT()) {
3746 case MVT::i8:
3747 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_XOR_8);
3748 case MVT::i16:
3749 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_XOR_16);
3750 case MVT::i32:
3751 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_XOR_32);
3752 case MVT::i64:
3753 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_XOR_64);
3754 default:
3755 assert(0 && "Invalid atomic type");
3756 abort();
3757 }
3758 case Intrinsic::atomic_load_and:
3759 switch (getValue(I.getOperand(2)).getValueType().getSimpleVT()) {
3760 case MVT::i8:
3761 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_AND_8);
3762 case MVT::i16:
3763 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_AND_16);
3764 case MVT::i32:
3765 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_AND_32);
3766 case MVT::i64:
3767 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_AND_64);
3768 default:
3769 assert(0 && "Invalid atomic type");
3770 abort();
3771 }
Andrew Lenharth507a58a2008-06-14 05:48:15 +00003772 case Intrinsic::atomic_load_nand:
Dale Johannesene00a8a22008-08-28 02:44:49 +00003773 switch (getValue(I.getOperand(2)).getValueType().getSimpleVT()) {
3774 case MVT::i8:
3775 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_NAND_8);
3776 case MVT::i16:
3777 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_NAND_16);
3778 case MVT::i32:
3779 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_NAND_32);
3780 case MVT::i64:
3781 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_NAND_64);
3782 default:
3783 assert(0 && "Invalid atomic type");
3784 abort();
3785 }
Mon P Wang63307c32008-05-05 19:05:59 +00003786 case Intrinsic::atomic_load_max:
Dale Johannesene00a8a22008-08-28 02:44:49 +00003787 switch (getValue(I.getOperand(2)).getValueType().getSimpleVT()) {
3788 case MVT::i8:
3789 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MAX_8);
3790 case MVT::i16:
3791 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MAX_16);
3792 case MVT::i32:
3793 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MAX_32);
3794 case MVT::i64:
3795 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MAX_64);
3796 default:
3797 assert(0 && "Invalid atomic type");
3798 abort();
3799 }
3800 case Intrinsic::atomic_load_min:
3801 switch (getValue(I.getOperand(2)).getValueType().getSimpleVT()) {
3802 case MVT::i8:
3803 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MIN_8);
3804 case MVT::i16:
3805 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MIN_16);
3806 case MVT::i32:
3807 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MIN_32);
3808 case MVT::i64:
3809 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MIN_64);
3810 default:
3811 assert(0 && "Invalid atomic type");
3812 abort();
3813 }
Mon P Wang63307c32008-05-05 19:05:59 +00003814 case Intrinsic::atomic_load_umin:
Dale Johannesene00a8a22008-08-28 02:44:49 +00003815 switch (getValue(I.getOperand(2)).getValueType().getSimpleVT()) {
3816 case MVT::i8:
3817 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMIN_8);
3818 case MVT::i16:
3819 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMIN_16);
3820 case MVT::i32:
3821 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMIN_32);
3822 case MVT::i64:
3823 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMIN_64);
3824 default:
3825 assert(0 && "Invalid atomic type");
3826 abort();
3827 }
Mon P Wang63307c32008-05-05 19:05:59 +00003828 case Intrinsic::atomic_load_umax:
Dale Johannesene00a8a22008-08-28 02:44:49 +00003829 switch (getValue(I.getOperand(2)).getValueType().getSimpleVT()) {
3830 case MVT::i8:
3831 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMAX_8);
3832 case MVT::i16:
3833 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMAX_16);
3834 case MVT::i32:
3835 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMAX_32);
3836 case MVT::i64:
3837 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMAX_64);
3838 default:
3839 assert(0 && "Invalid atomic type");
3840 abort();
3841 }
Mon P Wang63307c32008-05-05 19:05:59 +00003842 case Intrinsic::atomic_swap:
Dale Johannesene00a8a22008-08-28 02:44:49 +00003843 switch (getValue(I.getOperand(2)).getValueType().getSimpleVT()) {
3844 case MVT::i8:
3845 return implVisitBinaryAtomic(I, ISD::ATOMIC_SWAP_8);
3846 case MVT::i16:
3847 return implVisitBinaryAtomic(I, ISD::ATOMIC_SWAP_16);
3848 case MVT::i32:
3849 return implVisitBinaryAtomic(I, ISD::ATOMIC_SWAP_32);
3850 case MVT::i64:
3851 return implVisitBinaryAtomic(I, ISD::ATOMIC_SWAP_64);
3852 default:
3853 assert(0 && "Invalid atomic type");
3854 abort();
3855 }
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003856 }
3857}
3858
3859
Dan Gohman475871a2008-07-27 21:46:04 +00003860void SelectionDAGLowering::LowerCallTo(CallSite CS, SDValue Callee,
Jim Laskey1da20a72007-02-23 21:45:01 +00003861 bool IsTailCall,
Anton Korobeynikov070280e2007-05-23 11:08:31 +00003862 MachineBasicBlock *LandingPad) {
Duncan Sands6f74b482007-12-19 09:48:52 +00003863 const PointerType *PT = cast<PointerType>(CS.getCalledValue()->getType());
Jim Laskey735b6f82007-02-22 15:38:06 +00003864 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
Anton Korobeynikov070280e2007-05-23 11:08:31 +00003865 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3866 unsigned BeginLabel = 0, EndLabel = 0;
Duncan Sands6f74b482007-12-19 09:48:52 +00003867
Jim Laskey735b6f82007-02-22 15:38:06 +00003868 TargetLowering::ArgListTy Args;
3869 TargetLowering::ArgListEntry Entry;
Duncan Sands6f74b482007-12-19 09:48:52 +00003870 Args.reserve(CS.arg_size());
3871 for (CallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
3872 i != e; ++i) {
Dan Gohman475871a2008-07-27 21:46:04 +00003873 SDValue ArgNode = getValue(*i);
Duncan Sands6f74b482007-12-19 09:48:52 +00003874 Entry.Node = ArgNode; Entry.Ty = (*i)->getType();
Duncan Sands4fee7032007-05-07 20:49:28 +00003875
Duncan Sands6f74b482007-12-19 09:48:52 +00003876 unsigned attrInd = i - CS.arg_begin() + 1;
3877 Entry.isSExt = CS.paramHasAttr(attrInd, ParamAttr::SExt);
3878 Entry.isZExt = CS.paramHasAttr(attrInd, ParamAttr::ZExt);
3879 Entry.isInReg = CS.paramHasAttr(attrInd, ParamAttr::InReg);
3880 Entry.isSRet = CS.paramHasAttr(attrInd, ParamAttr::StructRet);
3881 Entry.isNest = CS.paramHasAttr(attrInd, ParamAttr::Nest);
3882 Entry.isByVal = CS.paramHasAttr(attrInd, ParamAttr::ByVal);
Dale Johannesen08e78b12008-02-22 17:49:45 +00003883 Entry.Alignment = CS.getParamAlignment(attrInd);
Jim Laskey735b6f82007-02-22 15:38:06 +00003884 Args.push_back(Entry);
3885 }
3886
Dale Johannesen1532f3d2008-04-02 00:25:04 +00003887 if (LandingPad && MMI) {
Anton Korobeynikov070280e2007-05-23 11:08:31 +00003888 // Insert a label before the invoke call to mark the try range. This can be
3889 // used to detect deletion of the invoke via the MachineModuleInfo.
3890 BeginLabel = MMI->NextLabelID();
Dale Johannesena4091d32008-04-04 23:48:31 +00003891 // Both PendingLoads and PendingExports must be flushed here;
3892 // this call might not return.
3893 (void)getRoot();
Dan Gohman44066042008-07-01 00:05:16 +00003894 DAG.setRoot(DAG.getLabel(ISD::EH_LABEL, getControlRoot(), BeginLabel));
Anton Korobeynikov070280e2007-05-23 11:08:31 +00003895 }
Duncan Sands6f74b482007-12-19 09:48:52 +00003896
Dan Gohman475871a2008-07-27 21:46:04 +00003897 std::pair<SDValue,SDValue> Result =
Duncan Sands6f74b482007-12-19 09:48:52 +00003898 TLI.LowerCallTo(getRoot(), CS.getType(),
3899 CS.paramHasAttr(0, ParamAttr::SExt),
Duncan Sands00fee652008-02-14 17:28:50 +00003900 CS.paramHasAttr(0, ParamAttr::ZExt),
Duncan Sands6f74b482007-12-19 09:48:52 +00003901 FTy->isVarArg(), CS.getCallingConv(), IsTailCall,
Jim Laskey735b6f82007-02-22 15:38:06 +00003902 Callee, Args, DAG);
Duncan Sands6f74b482007-12-19 09:48:52 +00003903 if (CS.getType() != Type::VoidTy)
3904 setValue(CS.getInstruction(), Result.first);
Jim Laskey735b6f82007-02-22 15:38:06 +00003905 DAG.setRoot(Result.second);
Anton Korobeynikov070280e2007-05-23 11:08:31 +00003906
Dale Johannesen1532f3d2008-04-02 00:25:04 +00003907 if (LandingPad && MMI) {
Anton Korobeynikov070280e2007-05-23 11:08:31 +00003908 // Insert a label at the end of the invoke call to mark the try range. This
3909 // can be used to detect deletion of the invoke via the MachineModuleInfo.
3910 EndLabel = MMI->NextLabelID();
Dan Gohman44066042008-07-01 00:05:16 +00003911 DAG.setRoot(DAG.getLabel(ISD::EH_LABEL, getRoot(), EndLabel));
Anton Korobeynikov070280e2007-05-23 11:08:31 +00003912
Duncan Sands6f74b482007-12-19 09:48:52 +00003913 // Inform MachineModuleInfo of range.
Anton Korobeynikov070280e2007-05-23 11:08:31 +00003914 MMI->addInvoke(LandingPad, BeginLabel, EndLabel);
3915 }
Jim Laskey735b6f82007-02-22 15:38:06 +00003916}
3917
3918
Chris Lattner1c08c712005-01-07 07:47:53 +00003919void SelectionDAGLowering::visitCall(CallInst &I) {
Chris Lattner64e14b12005-01-08 22:48:57 +00003920 const char *RenameFn = 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003921 if (Function *F = I.getCalledFunction()) {
Chris Lattner87b51bc2007-09-10 21:15:22 +00003922 if (F->isDeclaration()) {
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003923 if (unsigned IID = F->getIntrinsicID()) {
3924 RenameFn = visitIntrinsicCall(I, IID);
3925 if (!RenameFn)
3926 return;
Chris Lattner87b51bc2007-09-10 21:15:22 +00003927 }
3928 }
3929
3930 // Check for well-known libc/libm calls. If the function is internal, it
3931 // can't be a library call.
3932 unsigned NameLen = F->getNameLen();
3933 if (!F->hasInternalLinkage() && NameLen) {
3934 const char *NameStr = F->getNameStart();
3935 if (NameStr[0] == 'c' &&
3936 ((NameLen == 8 && !strcmp(NameStr, "copysign")) ||
3937 (NameLen == 9 && !strcmp(NameStr, "copysignf")))) {
3938 if (I.getNumOperands() == 3 && // Basic sanity checks.
3939 I.getOperand(1)->getType()->isFloatingPoint() &&
3940 I.getType() == I.getOperand(1)->getType() &&
3941 I.getType() == I.getOperand(2)->getType()) {
Dan Gohman475871a2008-07-27 21:46:04 +00003942 SDValue LHS = getValue(I.getOperand(1));
3943 SDValue RHS = getValue(I.getOperand(2));
Chris Lattner87b51bc2007-09-10 21:15:22 +00003944 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, LHS.getValueType(),
3945 LHS, RHS));
3946 return;
3947 }
3948 } else if (NameStr[0] == 'f' &&
3949 ((NameLen == 4 && !strcmp(NameStr, "fabs")) ||
Dale Johannesen2f429012007-09-26 21:10:55 +00003950 (NameLen == 5 && !strcmp(NameStr, "fabsf")) ||
3951 (NameLen == 5 && !strcmp(NameStr, "fabsl")))) {
Chris Lattner87b51bc2007-09-10 21:15:22 +00003952 if (I.getNumOperands() == 2 && // Basic sanity checks.
3953 I.getOperand(1)->getType()->isFloatingPoint() &&
3954 I.getType() == I.getOperand(1)->getType()) {
Dan Gohman475871a2008-07-27 21:46:04 +00003955 SDValue Tmp = getValue(I.getOperand(1));
Chris Lattner87b51bc2007-09-10 21:15:22 +00003956 setValue(&I, DAG.getNode(ISD::FABS, Tmp.getValueType(), Tmp));
3957 return;
3958 }
3959 } else if (NameStr[0] == 's' &&
3960 ((NameLen == 3 && !strcmp(NameStr, "sin")) ||
Dale Johannesen2f429012007-09-26 21:10:55 +00003961 (NameLen == 4 && !strcmp(NameStr, "sinf")) ||
3962 (NameLen == 4 && !strcmp(NameStr, "sinl")))) {
Chris Lattner87b51bc2007-09-10 21:15:22 +00003963 if (I.getNumOperands() == 2 && // Basic sanity checks.
3964 I.getOperand(1)->getType()->isFloatingPoint() &&
3965 I.getType() == I.getOperand(1)->getType()) {
Dan Gohman475871a2008-07-27 21:46:04 +00003966 SDValue Tmp = getValue(I.getOperand(1));
Chris Lattner87b51bc2007-09-10 21:15:22 +00003967 setValue(&I, DAG.getNode(ISD::FSIN, Tmp.getValueType(), Tmp));
3968 return;
3969 }
3970 } else if (NameStr[0] == 'c' &&
3971 ((NameLen == 3 && !strcmp(NameStr, "cos")) ||
Dale Johannesen2f429012007-09-26 21:10:55 +00003972 (NameLen == 4 && !strcmp(NameStr, "cosf")) ||
3973 (NameLen == 4 && !strcmp(NameStr, "cosl")))) {
Chris Lattner87b51bc2007-09-10 21:15:22 +00003974 if (I.getNumOperands() == 2 && // Basic sanity checks.
3975 I.getOperand(1)->getType()->isFloatingPoint() &&
3976 I.getType() == I.getOperand(1)->getType()) {
Dan Gohman475871a2008-07-27 21:46:04 +00003977 SDValue Tmp = getValue(I.getOperand(1));
Chris Lattner87b51bc2007-09-10 21:15:22 +00003978 setValue(&I, DAG.getNode(ISD::FCOS, Tmp.getValueType(), Tmp));
3979 return;
Chris Lattnerf76e7dc2005-04-30 04:43:14 +00003980 }
Chris Lattner1ca85d52005-05-14 13:56:55 +00003981 }
Chris Lattner87b51bc2007-09-10 21:15:22 +00003982 }
Chris Lattnerce7518c2006-01-26 22:24:51 +00003983 } else if (isa<InlineAsm>(I.getOperand(0))) {
Duncan Sandsfd7b3262007-12-17 18:08:19 +00003984 visitInlineAsm(&I);
Chris Lattnerce7518c2006-01-26 22:24:51 +00003985 return;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003986 }
Misha Brukmanedf128a2005-04-21 22:36:52 +00003987
Dan Gohman475871a2008-07-27 21:46:04 +00003988 SDValue Callee;
Chris Lattner64e14b12005-01-08 22:48:57 +00003989 if (!RenameFn)
3990 Callee = getValue(I.getOperand(0));
3991 else
3992 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
Anton Korobeynikov070280e2007-05-23 11:08:31 +00003993
Duncan Sands6f74b482007-12-19 09:48:52 +00003994 LowerCallTo(&I, Callee, I.isTailCall());
Chris Lattner1c08c712005-01-07 07:47:53 +00003995}
3996
Jim Laskey735b6f82007-02-22 15:38:06 +00003997
Dan Gohmanb6f5b002007-06-28 23:29:44 +00003998/// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
3999/// this value and returns the result as a ValueVT value. This uses
4000/// Chain/Flag as the input and updates them for the output Chain/Flag.
4001/// If the Flag pointer is NULL, no flag is used.
Dan Gohman475871a2008-07-27 21:46:04 +00004002SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
4003 SDValue &Chain,
4004 SDValue *Flag) const {
Dan Gohman23ce5022008-04-25 18:27:55 +00004005 // Assemble the legal parts into the final values.
Dan Gohman475871a2008-07-27 21:46:04 +00004006 SmallVector<SDValue, 4> Values(ValueVTs.size());
4007 SmallVector<SDValue, 8> Parts;
Chris Lattner6833b062008-04-28 07:16:35 +00004008 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
Dan Gohman23ce5022008-04-25 18:27:55 +00004009 // Copy the legal parts from the registers.
Duncan Sands83ec4b62008-06-06 12:08:01 +00004010 MVT ValueVT = ValueVTs[Value];
Dan Gohman23ce5022008-04-25 18:27:55 +00004011 unsigned NumRegs = TLI->getNumRegisters(ValueVT);
Duncan Sands83ec4b62008-06-06 12:08:01 +00004012 MVT RegisterVT = RegVTs[Value];
Dan Gohman23ce5022008-04-25 18:27:55 +00004013
Rafael Espindola91ee5452008-08-28 18:29:58 +00004014 Parts.resize(NumRegs);
Dan Gohman23ce5022008-04-25 18:27:55 +00004015 for (unsigned i = 0; i != NumRegs; ++i) {
Dan Gohman475871a2008-07-27 21:46:04 +00004016 SDValue P;
Chris Lattner6833b062008-04-28 07:16:35 +00004017 if (Flag == 0)
4018 P = DAG.getCopyFromReg(Chain, Regs[Part+i], RegisterVT);
4019 else {
4020 P = DAG.getCopyFromReg(Chain, Regs[Part+i], RegisterVT, *Flag);
Dan Gohman23ce5022008-04-25 18:27:55 +00004021 *Flag = P.getValue(2);
Chris Lattner6833b062008-04-28 07:16:35 +00004022 }
4023 Chain = P.getValue(1);
Chris Lattneread0d882008-06-17 06:09:18 +00004024
4025 // If the source register was virtual and if we know something about it,
4026 // add an assert node.
4027 if (TargetRegisterInfo::isVirtualRegister(Regs[Part+i]) &&
4028 RegisterVT.isInteger() && !RegisterVT.isVector()) {
4029 unsigned SlotNo = Regs[Part+i]-TargetRegisterInfo::FirstVirtualRegister;
4030 FunctionLoweringInfo &FLI = DAG.getFunctionLoweringInfo();
4031 if (FLI.LiveOutRegInfo.size() > SlotNo) {
4032 FunctionLoweringInfo::LiveOutInfo &LOI = FLI.LiveOutRegInfo[SlotNo];
4033
4034 unsigned RegSize = RegisterVT.getSizeInBits();
4035 unsigned NumSignBits = LOI.NumSignBits;
4036 unsigned NumZeroBits = LOI.KnownZero.countLeadingOnes();
4037
4038 // FIXME: We capture more information than the dag can represent. For
4039 // now, just use the tightest assertzext/assertsext possible.
4040 bool isSExt = true;
4041 MVT FromVT(MVT::Other);
4042 if (NumSignBits == RegSize)
4043 isSExt = true, FromVT = MVT::i1; // ASSERT SEXT 1
4044 else if (NumZeroBits >= RegSize-1)
4045 isSExt = false, FromVT = MVT::i1; // ASSERT ZEXT 1
4046 else if (NumSignBits > RegSize-8)
4047 isSExt = true, FromVT = MVT::i8; // ASSERT SEXT 8
4048 else if (NumZeroBits >= RegSize-9)
4049 isSExt = false, FromVT = MVT::i8; // ASSERT ZEXT 8
4050 else if (NumSignBits > RegSize-16)
4051 isSExt = true, FromVT = MVT::i16; // ASSERT SEXT 16
4052 else if (NumZeroBits >= RegSize-17)
4053 isSExt = false, FromVT = MVT::i16; // ASSERT ZEXT 16
4054 else if (NumSignBits > RegSize-32)
4055 isSExt = true, FromVT = MVT::i32; // ASSERT SEXT 32
4056 else if (NumZeroBits >= RegSize-33)
4057 isSExt = false, FromVT = MVT::i32; // ASSERT ZEXT 32
4058
4059 if (FromVT != MVT::Other) {
4060 P = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext,
4061 RegisterVT, P, DAG.getValueType(FromVT));
4062
4063 }
4064 }
4065 }
4066
Rafael Espindola91ee5452008-08-28 18:29:58 +00004067 Parts[i] = P;
Dan Gohman23ce5022008-04-25 18:27:55 +00004068 }
Chris Lattner5df99b32007-03-25 05:00:54 +00004069
Rafael Espindola91ee5452008-08-28 18:29:58 +00004070 Values[Value] = getCopyFromParts(DAG, Parts.begin(), NumRegs, RegisterVT,
Dan Gohman23ce5022008-04-25 18:27:55 +00004071 ValueVT);
4072 Part += NumRegs;
Rafael Espindola91ee5452008-08-28 18:29:58 +00004073 Parts.clear();
Dan Gohman23ce5022008-04-25 18:27:55 +00004074 }
Duncan Sands4bdcb612008-07-02 17:40:58 +00004075
Duncan Sandsf9516202008-06-30 10:19:09 +00004076 return DAG.getMergeValues(DAG.getVTList(&ValueVTs[0], ValueVTs.size()),
4077 &Values[0], ValueVTs.size());
Chris Lattner864635a2006-02-22 22:37:12 +00004078}
4079
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00004080/// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
4081/// specified value into the registers specified by this object. This uses
4082/// Chain/Flag as the input and updates them for the output Chain/Flag.
Dan Gohmanb6f5b002007-06-28 23:29:44 +00004083/// If the Flag pointer is NULL, no flag is used.
Dan Gohman475871a2008-07-27 21:46:04 +00004084void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG,
4085 SDValue &Chain, SDValue *Flag) const {
Dan Gohmanb6f5b002007-06-28 23:29:44 +00004086 // Get the list of the values's legal parts.
Dan Gohman23ce5022008-04-25 18:27:55 +00004087 unsigned NumRegs = Regs.size();
Dan Gohman475871a2008-07-27 21:46:04 +00004088 SmallVector<SDValue, 8> Parts(NumRegs);
Chris Lattner6833b062008-04-28 07:16:35 +00004089 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
Duncan Sands83ec4b62008-06-06 12:08:01 +00004090 MVT ValueVT = ValueVTs[Value];
Dan Gohman23ce5022008-04-25 18:27:55 +00004091 unsigned NumParts = TLI->getNumRegisters(ValueVT);
Duncan Sands83ec4b62008-06-06 12:08:01 +00004092 MVT RegisterVT = RegVTs[Value];
Dan Gohman23ce5022008-04-25 18:27:55 +00004093
Gabor Greif99a6cb92008-08-26 22:36:50 +00004094 getCopyToParts(DAG, Val.getValue(Val.getResNo() + Value),
Dan Gohman23ce5022008-04-25 18:27:55 +00004095 &Parts[Part], NumParts, RegisterVT);
4096 Part += NumParts;
4097 }
Dan Gohmanb6f5b002007-06-28 23:29:44 +00004098
4099 // Copy the parts into the registers.
Dan Gohman475871a2008-07-27 21:46:04 +00004100 SmallVector<SDValue, 8> Chains(NumRegs);
Dan Gohman23ce5022008-04-25 18:27:55 +00004101 for (unsigned i = 0; i != NumRegs; ++i) {
Dan Gohman475871a2008-07-27 21:46:04 +00004102 SDValue Part;
Chris Lattner6833b062008-04-28 07:16:35 +00004103 if (Flag == 0)
4104 Part = DAG.getCopyToReg(Chain, Regs[i], Parts[i]);
4105 else {
4106 Part = DAG.getCopyToReg(Chain, Regs[i], Parts[i], *Flag);
Dan Gohmanb6f5b002007-06-28 23:29:44 +00004107 *Flag = Part.getValue(1);
Chris Lattner6833b062008-04-28 07:16:35 +00004108 }
4109 Chains[i] = Part.getValue(0);
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00004110 }
Chris Lattner6833b062008-04-28 07:16:35 +00004111
Evan Cheng33bf38a2008-04-28 22:07:13 +00004112 if (NumRegs == 1 || Flag)
4113 // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is
4114 // flagged to it. That is the CopyToReg nodes and the user are considered
4115 // a single scheduling unit. If we create a TokenFactor and return it as
4116 // chain, then the TokenFactor is both a predecessor (operand) of the
4117 // user as well as a successor (the TF operands are flagged to the user).
4118 // c1, f1 = CopyToReg
4119 // c2, f2 = CopyToReg
4120 // c3 = TokenFactor c1, c2
4121 // ...
4122 // = op c3, ..., f2
4123 Chain = Chains[NumRegs-1];
Chris Lattner6833b062008-04-28 07:16:35 +00004124 else
4125 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other, &Chains[0], NumRegs);
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00004126}
Chris Lattner864635a2006-02-22 22:37:12 +00004127
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00004128/// AddInlineAsmOperands - Add this value to the specified inlineasm node
4129/// operand list. This adds the code marker and includes the number of
4130/// values added into it.
4131void RegsForValue::AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
Dan Gohman475871a2008-07-27 21:46:04 +00004132 std::vector<SDValue> &Ops) const {
Duncan Sands83ec4b62008-06-06 12:08:01 +00004133 MVT IntPtrTy = DAG.getTargetLoweringInfo().getPointerTy();
Chris Lattner4b993b12007-04-09 00:33:58 +00004134 Ops.push_back(DAG.getTargetConstant(Code | (Regs.size() << 3), IntPtrTy));
Chris Lattner6833b062008-04-28 07:16:35 +00004135 for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
4136 unsigned NumRegs = TLI->getNumRegisters(ValueVTs[Value]);
Duncan Sands83ec4b62008-06-06 12:08:01 +00004137 MVT RegisterVT = RegVTs[Value];
Chris Lattner6833b062008-04-28 07:16:35 +00004138 for (unsigned i = 0; i != NumRegs; ++i)
4139 Ops.push_back(DAG.getRegister(Regs[Reg++], RegisterVT));
Dan Gohman23ce5022008-04-25 18:27:55 +00004140 }
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00004141}
Chris Lattner864635a2006-02-22 22:37:12 +00004142
4143/// isAllocatableRegister - If the specified register is safe to allocate,
4144/// i.e. it isn't a stack pointer or some other special register, return the
4145/// register class for the register. Otherwise, return null.
4146static const TargetRegisterClass *
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00004147isAllocatableRegister(unsigned Reg, MachineFunction &MF,
Dan Gohman6f0d0242008-02-10 18:45:23 +00004148 const TargetLowering &TLI,
4149 const TargetRegisterInfo *TRI) {
Duncan Sands83ec4b62008-06-06 12:08:01 +00004150 MVT FoundVT = MVT::Other;
Chris Lattnerf8814cf2006-04-02 00:24:45 +00004151 const TargetRegisterClass *FoundRC = 0;
Dan Gohman6f0d0242008-02-10 18:45:23 +00004152 for (TargetRegisterInfo::regclass_iterator RCI = TRI->regclass_begin(),
4153 E = TRI->regclass_end(); RCI != E; ++RCI) {
Duncan Sands83ec4b62008-06-06 12:08:01 +00004154 MVT ThisVT = MVT::Other;
Chris Lattnerf8814cf2006-04-02 00:24:45 +00004155
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00004156 const TargetRegisterClass *RC = *RCI;
4157 // If none of the the value types for this register class are valid, we
4158 // can't use it. For example, 64-bit reg classes on 32-bit targets.
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00004159 for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
4160 I != E; ++I) {
4161 if (TLI.isTypeLegal(*I)) {
Chris Lattnerf8814cf2006-04-02 00:24:45 +00004162 // If we have already found this register in a different register class,
4163 // choose the one with the largest VT specified. For example, on
4164 // PowerPC, we favor f64 register classes over f32.
Duncan Sands8e4eb092008-06-08 20:54:56 +00004165 if (FoundVT == MVT::Other || FoundVT.bitsLT(*I)) {
Chris Lattnerf8814cf2006-04-02 00:24:45 +00004166 ThisVT = *I;
4167 break;
4168 }
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00004169 }
4170 }
4171
Chris Lattnerf8814cf2006-04-02 00:24:45 +00004172 if (ThisVT == MVT::Other) continue;
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00004173
Chris Lattner864635a2006-02-22 22:37:12 +00004174 // NOTE: This isn't ideal. In particular, this might allocate the
4175 // frame pointer in functions that need it (due to them not being taken
4176 // out of allocation, because a variable sized allocation hasn't been seen
4177 // yet). This is a slight code pessimization, but should still work.
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00004178 for (TargetRegisterClass::iterator I = RC->allocation_order_begin(MF),
4179 E = RC->allocation_order_end(MF); I != E; ++I)
Chris Lattnerf8814cf2006-04-02 00:24:45 +00004180 if (*I == Reg) {
4181 // We found a matching register class. Keep looking at others in case
4182 // we find one with larger registers that this physreg is also in.
4183 FoundRC = RC;
4184 FoundVT = ThisVT;
4185 break;
4186 }
Chris Lattner4e4b5762006-02-01 18:59:47 +00004187 }
Chris Lattnerf8814cf2006-04-02 00:24:45 +00004188 return FoundRC;
Chris Lattner864635a2006-02-22 22:37:12 +00004189}
4190
Chris Lattner4e4b5762006-02-01 18:59:47 +00004191
Chris Lattner0c583402007-04-28 20:49:53 +00004192namespace {
4193/// AsmOperandInfo - This contains information for each constraint that we are
4194/// lowering.
Evan Cheng5c807602008-02-26 02:33:44 +00004195struct SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo {
4196 /// CallOperand - If this is the result output operand or a clobber
4197 /// this is null, otherwise it is the incoming operand to the CallInst.
4198 /// This gets modified as the asm is processed.
Dan Gohman475871a2008-07-27 21:46:04 +00004199 SDValue CallOperand;
Evan Cheng5c807602008-02-26 02:33:44 +00004200
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004201 /// AssignedRegs - If this is a register or register class operand, this
4202 /// contains the set of register corresponding to the operand.
4203 RegsForValue AssignedRegs;
4204
Dan Gohman23ce5022008-04-25 18:27:55 +00004205 explicit SDISelAsmOperandInfo(const InlineAsm::ConstraintInfo &info)
Evan Cheng5c807602008-02-26 02:33:44 +00004206 : TargetLowering::AsmOperandInfo(info), CallOperand(0,0) {
Chris Lattner0c583402007-04-28 20:49:53 +00004207 }
Chris Lattner3ff90dc2007-04-30 17:16:27 +00004208
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004209 /// MarkAllocatedRegs - Once AssignedRegs is set, mark the assigned registers
4210 /// busy in OutputRegs/InputRegs.
4211 void MarkAllocatedRegs(bool isOutReg, bool isInReg,
4212 std::set<unsigned> &OutputRegs,
Chris Lattner7cbeb242008-02-21 04:55:52 +00004213 std::set<unsigned> &InputRegs,
4214 const TargetRegisterInfo &TRI) const {
4215 if (isOutReg) {
4216 for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i)
4217 MarkRegAndAliases(AssignedRegs.Regs[i], OutputRegs, TRI);
4218 }
4219 if (isInReg) {
4220 for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i)
4221 MarkRegAndAliases(AssignedRegs.Regs[i], InputRegs, TRI);
4222 }
4223 }
4224
4225private:
4226 /// MarkRegAndAliases - Mark the specified register and all aliases in the
4227 /// specified set.
4228 static void MarkRegAndAliases(unsigned Reg, std::set<unsigned> &Regs,
4229 const TargetRegisterInfo &TRI) {
4230 assert(TargetRegisterInfo::isPhysicalRegister(Reg) && "Isn't a physreg");
4231 Regs.insert(Reg);
4232 if (const unsigned *Aliases = TRI.getAliasSet(Reg))
4233 for (; *Aliases; ++Aliases)
4234 Regs.insert(*Aliases);
4235 }
Chris Lattner0c583402007-04-28 20:49:53 +00004236};
4237} // end anon namespace.
Chris Lattner864635a2006-02-22 22:37:12 +00004238
Chris Lattner3ff90dc2007-04-30 17:16:27 +00004239
Chris Lattner0fe71e92008-02-21 19:43:13 +00004240/// GetRegistersForValue - Assign registers (virtual or physical) for the
4241/// specified operand. We prefer to assign virtual registers, to allow the
4242/// register allocator handle the assignment process. However, if the asm uses
4243/// features that we can't model on machineinstrs, we have SDISel do the
4244/// allocation. This produces generally horrible, but correct, code.
4245///
4246/// OpInfo describes the operand.
4247/// HasEarlyClobber is true if there are any early clobber constraints (=&r)
4248/// or any explicitly clobbered registers.
4249/// Input and OutputRegs are the set of already allocated physical registers.
4250///
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004251void SelectionDAGLowering::
Evan Cheng5c807602008-02-26 02:33:44 +00004252GetRegistersForValue(SDISelAsmOperandInfo &OpInfo, bool HasEarlyClobber,
Chris Lattnerbf996f12007-04-30 17:29:31 +00004253 std::set<unsigned> &OutputRegs,
4254 std::set<unsigned> &InputRegs) {
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004255 // Compute whether this value requires an input register, an output register,
4256 // or both.
4257 bool isOutReg = false;
4258 bool isInReg = false;
4259 switch (OpInfo.Type) {
4260 case InlineAsm::isOutput:
4261 isOutReg = true;
4262
4263 // If this is an early-clobber output, or if there is an input
4264 // constraint that matches this, we need to reserve the input register
4265 // so no other inputs allocate to it.
4266 isInReg = OpInfo.isEarlyClobber || OpInfo.hasMatchingInput;
4267 break;
4268 case InlineAsm::isInput:
4269 isInReg = true;
4270 isOutReg = false;
4271 break;
4272 case InlineAsm::isClobber:
4273 isOutReg = true;
4274 isInReg = true;
4275 break;
4276 }
4277
4278
4279 MachineFunction &MF = DAG.getMachineFunction();
Chris Lattnerb606dba2008-04-28 06:44:42 +00004280 SmallVector<unsigned, 4> Regs;
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004281
4282 // If this is a constraint for a single physreg, or a constraint for a
4283 // register class, find it.
4284 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
4285 TLI.getRegForInlineAsmConstraint(OpInfo.ConstraintCode,
4286 OpInfo.ConstraintVT);
Chris Lattnerbf996f12007-04-30 17:29:31 +00004287
4288 unsigned NumRegs = 1;
4289 if (OpInfo.ConstraintVT != MVT::Other)
Dan Gohmanb9f10192007-06-21 14:42:22 +00004290 NumRegs = TLI.getNumRegisters(OpInfo.ConstraintVT);
Duncan Sands83ec4b62008-06-06 12:08:01 +00004291 MVT RegVT;
4292 MVT ValueVT = OpInfo.ConstraintVT;
Chris Lattnerbf996f12007-04-30 17:29:31 +00004293
Chris Lattnerbf996f12007-04-30 17:29:31 +00004294
4295 // If this is a constraint for a specific physical register, like {r17},
4296 // assign it now.
4297 if (PhysReg.first) {
4298 if (OpInfo.ConstraintVT == MVT::Other)
4299 ValueVT = *PhysReg.second->vt_begin();
4300
4301 // Get the actual register value type. This is important, because the user
4302 // may have asked for (e.g.) the AX register in i32 type. We need to
4303 // remember that AX is actually i16 to get the right extension.
4304 RegVT = *PhysReg.second->vt_begin();
4305
4306 // This is a explicit reference to a physical register.
4307 Regs.push_back(PhysReg.first);
4308
4309 // If this is an expanded reference, add the rest of the regs to Regs.
4310 if (NumRegs != 1) {
4311 TargetRegisterClass::iterator I = PhysReg.second->begin();
Chris Lattnerbf996f12007-04-30 17:29:31 +00004312 for (; *I != PhysReg.first; ++I)
Evan Cheng50871242008-05-14 20:07:51 +00004313 assert(I != PhysReg.second->end() && "Didn't find reg!");
Chris Lattnerbf996f12007-04-30 17:29:31 +00004314
4315 // Already added the first reg.
4316 --NumRegs; ++I;
4317 for (; NumRegs; --NumRegs, ++I) {
Evan Cheng50871242008-05-14 20:07:51 +00004318 assert(I != PhysReg.second->end() && "Ran out of registers to allocate!");
Chris Lattnerbf996f12007-04-30 17:29:31 +00004319 Regs.push_back(*I);
4320 }
4321 }
Dan Gohman23ce5022008-04-25 18:27:55 +00004322 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, RegVT, ValueVT);
Chris Lattner7cbeb242008-02-21 04:55:52 +00004323 const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
4324 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TRI);
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004325 return;
Chris Lattnerbf996f12007-04-30 17:29:31 +00004326 }
4327
4328 // Otherwise, if this was a reference to an LLVM register class, create vregs
4329 // for this reference.
4330 std::vector<unsigned> RegClassRegs;
Chris Lattnerc2c28fc2007-06-15 19:11:01 +00004331 const TargetRegisterClass *RC = PhysReg.second;
4332 if (RC) {
Chris Lattnerbf996f12007-04-30 17:29:31 +00004333 // If this is an early clobber or tied register, our regalloc doesn't know
4334 // how to maintain the constraint. If it isn't, go ahead and create vreg
4335 // and let the regalloc do the right thing.
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004336 if (!OpInfo.hasMatchingInput && !OpInfo.isEarlyClobber &&
4337 // If there is some other early clobber and this is an input register,
4338 // then we are forced to pre-allocate the input reg so it doesn't
4339 // conflict with the earlyclobber.
4340 !(OpInfo.Type == InlineAsm::isInput && HasEarlyClobber)) {
Chris Lattnerbf996f12007-04-30 17:29:31 +00004341 RegVT = *PhysReg.second->vt_begin();
4342
4343 if (OpInfo.ConstraintVT == MVT::Other)
4344 ValueVT = RegVT;
4345
4346 // Create the appropriate number of virtual registers.
Chris Lattner84bc5422007-12-31 04:13:23 +00004347 MachineRegisterInfo &RegInfo = MF.getRegInfo();
Chris Lattnerbf996f12007-04-30 17:29:31 +00004348 for (; NumRegs; --NumRegs)
Chris Lattner84bc5422007-12-31 04:13:23 +00004349 Regs.push_back(RegInfo.createVirtualRegister(PhysReg.second));
Chris Lattnerbf996f12007-04-30 17:29:31 +00004350
Dan Gohman23ce5022008-04-25 18:27:55 +00004351 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, RegVT, ValueVT);
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004352 return;
Chris Lattnerbf996f12007-04-30 17:29:31 +00004353 }
4354
4355 // Otherwise, we can't allocate it. Let the code below figure out how to
4356 // maintain these constraints.
4357 RegClassRegs.assign(PhysReg.second->begin(), PhysReg.second->end());
4358
4359 } else {
4360 // This is a reference to a register class that doesn't directly correspond
4361 // to an LLVM register class. Allocate NumRegs consecutive, available,
4362 // registers from the class.
4363 RegClassRegs = TLI.getRegClassForInlineAsmConstraint(OpInfo.ConstraintCode,
4364 OpInfo.ConstraintVT);
4365 }
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004366
Dan Gohman6f0d0242008-02-10 18:45:23 +00004367 const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
Chris Lattnerbf996f12007-04-30 17:29:31 +00004368 unsigned NumAllocated = 0;
4369 for (unsigned i = 0, e = RegClassRegs.size(); i != e; ++i) {
4370 unsigned Reg = RegClassRegs[i];
4371 // See if this register is available.
4372 if ((isOutReg && OutputRegs.count(Reg)) || // Already used.
4373 (isInReg && InputRegs.count(Reg))) { // Already used.
4374 // Make sure we find consecutive registers.
4375 NumAllocated = 0;
4376 continue;
4377 }
4378
4379 // Check to see if this register is allocatable (i.e. don't give out the
4380 // stack pointer).
Chris Lattnerc2c28fc2007-06-15 19:11:01 +00004381 if (RC == 0) {
Dan Gohman6f0d0242008-02-10 18:45:23 +00004382 RC = isAllocatableRegister(Reg, MF, TLI, TRI);
Chris Lattnerc2c28fc2007-06-15 19:11:01 +00004383 if (!RC) { // Couldn't allocate this register.
4384 // Reset NumAllocated to make sure we return consecutive registers.
4385 NumAllocated = 0;
4386 continue;
4387 }
Chris Lattnerbf996f12007-04-30 17:29:31 +00004388 }
4389
4390 // Okay, this register is good, we can use it.
4391 ++NumAllocated;
4392
4393 // If we allocated enough consecutive registers, succeed.
4394 if (NumAllocated == NumRegs) {
4395 unsigned RegStart = (i-NumAllocated)+1;
4396 unsigned RegEnd = i+1;
4397 // Mark all of the allocated registers used.
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004398 for (unsigned i = RegStart; i != RegEnd; ++i)
4399 Regs.push_back(RegClassRegs[i]);
Chris Lattnerbf996f12007-04-30 17:29:31 +00004400
Dan Gohman23ce5022008-04-25 18:27:55 +00004401 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, *RC->vt_begin(),
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004402 OpInfo.ConstraintVT);
Chris Lattner7cbeb242008-02-21 04:55:52 +00004403 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TRI);
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004404 return;
Chris Lattnerbf996f12007-04-30 17:29:31 +00004405 }
4406 }
4407
4408 // Otherwise, we couldn't allocate enough registers for this.
Chris Lattnerbf996f12007-04-30 17:29:31 +00004409}
4410
4411
Chris Lattnerce7518c2006-01-26 22:24:51 +00004412/// visitInlineAsm - Handle a call to an InlineAsm object.
4413///
Duncan Sandsfd7b3262007-12-17 18:08:19 +00004414void SelectionDAGLowering::visitInlineAsm(CallSite CS) {
4415 InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
Chris Lattnerce7518c2006-01-26 22:24:51 +00004416
Chris Lattner0c583402007-04-28 20:49:53 +00004417 /// ConstraintOperands - Information about all of the constraints.
Evan Cheng5c807602008-02-26 02:33:44 +00004418 std::vector<SDISelAsmOperandInfo> ConstraintOperands;
Chris Lattnerce7518c2006-01-26 22:24:51 +00004419
Dan Gohman475871a2008-07-27 21:46:04 +00004420 SDValue Chain = getRoot();
4421 SDValue Flag;
Chris Lattnerce7518c2006-01-26 22:24:51 +00004422
Chris Lattner4e4b5762006-02-01 18:59:47 +00004423 std::set<unsigned> OutputRegs, InputRegs;
Chris Lattner1efa40f2006-02-22 00:56:39 +00004424
Chris Lattner0c583402007-04-28 20:49:53 +00004425 // Do a prepass over the constraints, canonicalizing them, and building up the
4426 // ConstraintOperands list.
4427 std::vector<InlineAsm::ConstraintInfo>
4428 ConstraintInfos = IA->ParseConstraints();
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004429
4430 // SawEarlyClobber - Keep track of whether we saw an earlyclobber output
4431 // constraint. If so, we can't let the register allocator allocate any input
4432 // registers, because it will not know to avoid the earlyclobbered output reg.
4433 bool SawEarlyClobber = false;
4434
Duncan Sandsfd7b3262007-12-17 18:08:19 +00004435 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst.
Chris Lattneracf8b012008-04-27 23:44:28 +00004436 unsigned ResNo = 0; // ResNo - The result number of the next output.
Chris Lattner0c583402007-04-28 20:49:53 +00004437 for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) {
Evan Cheng5c807602008-02-26 02:33:44 +00004438 ConstraintOperands.push_back(SDISelAsmOperandInfo(ConstraintInfos[i]));
4439 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
Chris Lattner0c583402007-04-28 20:49:53 +00004440
Duncan Sands83ec4b62008-06-06 12:08:01 +00004441 MVT OpVT = MVT::Other;
Chris Lattner0c583402007-04-28 20:49:53 +00004442
4443 // Compute the value type for each operand.
4444 switch (OpInfo.Type) {
Chris Lattner1efa40f2006-02-22 00:56:39 +00004445 case InlineAsm::isOutput:
Chris Lattneracf8b012008-04-27 23:44:28 +00004446 // Indirect outputs just consume an argument.
4447 if (OpInfo.isIndirect) {
Duncan Sandsfd7b3262007-12-17 18:08:19 +00004448 OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
Chris Lattneracf8b012008-04-27 23:44:28 +00004449 break;
Chris Lattner1efa40f2006-02-22 00:56:39 +00004450 }
Chris Lattneracf8b012008-04-27 23:44:28 +00004451 // The return value of the call is this value. As such, there is no
4452 // corresponding argument.
4453 assert(CS.getType() != Type::VoidTy && "Bad inline asm!");
4454 if (const StructType *STy = dyn_cast<StructType>(CS.getType())) {
4455 OpVT = TLI.getValueType(STy->getElementType(ResNo));
4456 } else {
4457 assert(ResNo == 0 && "Asm only has one result!");
4458 OpVT = TLI.getValueType(CS.getType());
4459 }
4460 ++ResNo;
Chris Lattner1efa40f2006-02-22 00:56:39 +00004461 break;
4462 case InlineAsm::isInput:
Duncan Sandsfd7b3262007-12-17 18:08:19 +00004463 OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
Chris Lattner1efa40f2006-02-22 00:56:39 +00004464 break;
4465 case InlineAsm::isClobber:
Chris Lattner0c583402007-04-28 20:49:53 +00004466 // Nothing to do.
Chris Lattner1efa40f2006-02-22 00:56:39 +00004467 break;
4468 }
Chris Lattner1efa40f2006-02-22 00:56:39 +00004469
Chris Lattner0c583402007-04-28 20:49:53 +00004470 // If this is an input or an indirect output, process the call argument.
Dale Johanneseneb57ea72007-11-05 21:20:28 +00004471 // BasicBlocks are labels, currently appearing only in asm's.
Chris Lattner0c583402007-04-28 20:49:53 +00004472 if (OpInfo.CallOperandVal) {
Chris Lattner507ffd22008-04-27 00:16:18 +00004473 if (BasicBlock *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal))
4474 OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
Dale Johanneseneb57ea72007-11-05 21:20:28 +00004475 else {
4476 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
4477 const Type *OpTy = OpInfo.CallOperandVal->getType();
4478 // If this is an indirect operand, the operand is a pointer to the
4479 // accessed type.
4480 if (OpInfo.isIndirect)
4481 OpTy = cast<PointerType>(OpTy)->getElementType();
4482
Dan Gohman4fa2a3f2008-05-23 00:34:04 +00004483 // If OpTy is not a single value, it may be a struct/union that we
Dale Johanneseneb57ea72007-11-05 21:20:28 +00004484 // can tile with integers.
Dan Gohman4fa2a3f2008-05-23 00:34:04 +00004485 if (!OpTy->isSingleValueType() && OpTy->isSized()) {
Dale Johanneseneb57ea72007-11-05 21:20:28 +00004486 unsigned BitSize = TD->getTypeSizeInBits(OpTy);
4487 switch (BitSize) {
4488 default: break;
4489 case 1:
4490 case 8:
4491 case 16:
4492 case 32:
4493 case 64:
4494 OpTy = IntegerType::get(BitSize);
4495 break;
4496 }
Chris Lattner6995cf62007-04-29 18:58:03 +00004497 }
Dale Johanneseneb57ea72007-11-05 21:20:28 +00004498
4499 OpVT = TLI.getValueType(OpTy, true);
Chris Lattner0c583402007-04-28 20:49:53 +00004500 }
4501 }
4502
4503 OpInfo.ConstraintVT = OpVT;
Chris Lattner2a600be2007-04-28 21:01:43 +00004504
Chris Lattner3ff90dc2007-04-30 17:16:27 +00004505 // Compute the constraint code and ConstraintType to use.
Chris Lattner5a096902008-04-27 00:37:18 +00004506 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
Chris Lattner0c583402007-04-28 20:49:53 +00004507
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004508 // Keep track of whether we see an earlyclobber.
4509 SawEarlyClobber |= OpInfo.isEarlyClobber;
Chris Lattner09e4b7e2007-04-28 21:12:06 +00004510
Chris Lattner0fe71e92008-02-21 19:43:13 +00004511 // If we see a clobber of a register, it is an early clobber.
Chris Lattner69e6a8d2008-02-21 20:54:31 +00004512 if (!SawEarlyClobber &&
4513 OpInfo.Type == InlineAsm::isClobber &&
4514 OpInfo.ConstraintType == TargetLowering::C_Register) {
Chris Lattner09c5d8b2008-08-26 06:07:47 +00004515 // Note that we want to ignore things that we don't track here, like
Chris Lattner69e6a8d2008-02-21 20:54:31 +00004516 // dirflag, fpsr, flags, etc.
4517 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
4518 TLI.getRegForInlineAsmConstraint(OpInfo.ConstraintCode,
4519 OpInfo.ConstraintVT);
4520 if (PhysReg.first || PhysReg.second) {
4521 // This is a register we know of.
4522 SawEarlyClobber = true;
4523 }
4524 }
Chris Lattner0fe71e92008-02-21 19:43:13 +00004525
Chris Lattner09e4b7e2007-04-28 21:12:06 +00004526 // If this is a memory input, and if the operand is not indirect, do what we
4527 // need to to provide an address for the memory input.
4528 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
4529 !OpInfo.isIndirect) {
4530 assert(OpInfo.Type == InlineAsm::isInput &&
4531 "Can only indirectify direct input operands!");
4532
4533 // Memory operands really want the address of the value. If we don't have
4534 // an indirect input, put it in the constpool if we can, otherwise spill
4535 // it to a stack slot.
4536
4537 // If the operand is a float, integer, or vector constant, spill to a
4538 // constant pool entry to get its address.
4539 Value *OpVal = OpInfo.CallOperandVal;
4540 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
4541 isa<ConstantVector>(OpVal)) {
4542 OpInfo.CallOperand = DAG.getConstantPool(cast<Constant>(OpVal),
4543 TLI.getPointerTy());
4544 } else {
4545 // Otherwise, create a stack slot and emit a store to it before the
4546 // asm.
4547 const Type *Ty = OpVal->getType();
Duncan Sands514ab342007-11-01 20:53:16 +00004548 uint64_t TySize = TLI.getTargetData()->getABITypeSize(Ty);
Chris Lattner09e4b7e2007-04-28 21:12:06 +00004549 unsigned Align = TLI.getTargetData()->getPrefTypeAlignment(Ty);
4550 MachineFunction &MF = DAG.getMachineFunction();
4551 int SSFI = MF.getFrameInfo()->CreateStackObject(TySize, Align);
Dan Gohman475871a2008-07-27 21:46:04 +00004552 SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getPointerTy());
Chris Lattner09e4b7e2007-04-28 21:12:06 +00004553 Chain = DAG.getStore(Chain, OpInfo.CallOperand, StackSlot, NULL, 0);
4554 OpInfo.CallOperand = StackSlot;
4555 }
4556
4557 // There is no longer a Value* corresponding to this operand.
4558 OpInfo.CallOperandVal = 0;
4559 // It is now an indirect operand.
4560 OpInfo.isIndirect = true;
4561 }
4562
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004563 // If this constraint is for a specific register, allocate it before
4564 // anything else.
4565 if (OpInfo.ConstraintType == TargetLowering::C_Register)
4566 GetRegistersForValue(OpInfo, SawEarlyClobber, OutputRegs, InputRegs);
Chris Lattner0c583402007-04-28 20:49:53 +00004567 }
Chris Lattner0c583402007-04-28 20:49:53 +00004568 ConstraintInfos.clear();
4569
4570
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004571 // Second pass - Loop over all of the operands, assigning virtual or physregs
4572 // to registerclass operands.
4573 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
Evan Cheng5c807602008-02-26 02:33:44 +00004574 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004575
4576 // C_Register operands have already been allocated, Other/Memory don't need
4577 // to be.
4578 if (OpInfo.ConstraintType == TargetLowering::C_RegisterClass)
4579 GetRegistersForValue(OpInfo, SawEarlyClobber, OutputRegs, InputRegs);
4580 }
4581
Chris Lattner0c583402007-04-28 20:49:53 +00004582 // AsmNodeOperands - The operands for the ISD::INLINEASM node.
Dan Gohman475871a2008-07-27 21:46:04 +00004583 std::vector<SDValue> AsmNodeOperands;
4584 AsmNodeOperands.push_back(SDValue()); // reserve space for input chain
Chris Lattner0c583402007-04-28 20:49:53 +00004585 AsmNodeOperands.push_back(
4586 DAG.getTargetExternalSymbol(IA->getAsmString().c_str(), MVT::Other));
4587
Chris Lattner2cc2f662006-02-01 01:28:23 +00004588
Chris Lattner0f0b7d42006-02-21 23:12:12 +00004589 // Loop over all of the inputs, copying the operand values into the
4590 // appropriate registers and processing the output regs.
Chris Lattner864635a2006-02-22 22:37:12 +00004591 RegsForValue RetValRegs;
Chris Lattner41f62592008-04-29 04:29:54 +00004592
Chris Lattner0c583402007-04-28 20:49:53 +00004593 // IndirectStoresToEmit - The set of stores to emit after the inline asm node.
4594 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
4595
4596 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
Evan Cheng5c807602008-02-26 02:33:44 +00004597 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
Chris Lattner1efa40f2006-02-22 00:56:39 +00004598
Chris Lattner0c583402007-04-28 20:49:53 +00004599 switch (OpInfo.Type) {
Chris Lattner2cc2f662006-02-01 01:28:23 +00004600 case InlineAsm::isOutput: {
Chris Lattnerc83994e2007-04-28 21:03:16 +00004601 if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass &&
4602 OpInfo.ConstraintType != TargetLowering::C_Register) {
Chris Lattnerf2f3cd52007-04-28 06:08:13 +00004603 // Memory output, or 'other' output (e.g. 'X' constraint).
Chris Lattner09e4b7e2007-04-28 21:12:06 +00004604 assert(OpInfo.isIndirect && "Memory output must be indirect operand");
Chris Lattner22873462006-02-27 23:45:39 +00004605
Chris Lattner22873462006-02-27 23:45:39 +00004606 // Add information to the INLINEASM node to know about this output.
4607 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
Chris Lattnerc90233b2007-05-15 01:33:58 +00004608 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
4609 TLI.getPointerTy()));
Chris Lattner09e4b7e2007-04-28 21:12:06 +00004610 AsmNodeOperands.push_back(OpInfo.CallOperand);
Chris Lattner22873462006-02-27 23:45:39 +00004611 break;
4612 }
4613
Chris Lattner2a600be2007-04-28 21:01:43 +00004614 // Otherwise, this is a register or register class output.
Chris Lattner22873462006-02-27 23:45:39 +00004615
Chris Lattner864635a2006-02-22 22:37:12 +00004616 // Copy the output from the appropriate register. Find a register that
Chris Lattner1efa40f2006-02-22 00:56:39 +00004617 // we can use.
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004618 if (OpInfo.AssignedRegs.Regs.empty()) {
Duncan Sandsa47c6c32008-06-17 03:24:13 +00004619 cerr << "Couldn't allocate output reg for constraint '"
Chris Lattner0c583402007-04-28 20:49:53 +00004620 << OpInfo.ConstraintCode << "'!\n";
Chris Lattnerd03f1582006-10-31 07:33:13 +00004621 exit(1);
4622 }
Chris Lattner1efa40f2006-02-22 00:56:39 +00004623
Chris Lattner41f62592008-04-29 04:29:54 +00004624 // If this is an indirect operand, store through the pointer after the
4625 // asm.
4626 if (OpInfo.isIndirect) {
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004627 IndirectStoresToEmit.push_back(std::make_pair(OpInfo.AssignedRegs,
Chris Lattner0c583402007-04-28 20:49:53 +00004628 OpInfo.CallOperandVal));
Chris Lattner41f62592008-04-29 04:29:54 +00004629 } else {
4630 // This is the result value of the call.
4631 assert(CS.getType() != Type::VoidTy && "Bad inline asm!");
4632 // Concatenate this output onto the outputs list.
4633 RetValRegs.append(OpInfo.AssignedRegs);
Chris Lattner2cc2f662006-02-01 01:28:23 +00004634 }
Chris Lattner6656dd12006-01-31 02:03:41 +00004635
4636 // Add information to the INLINEASM node to know that this register is
4637 // set.
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004638 OpInfo.AssignedRegs.AddInlineAsmOperands(2 /*REGDEF*/, DAG,
4639 AsmNodeOperands);
Chris Lattner6656dd12006-01-31 02:03:41 +00004640 break;
4641 }
4642 case InlineAsm::isInput: {
Dan Gohman475871a2008-07-27 21:46:04 +00004643 SDValue InOperandVal = OpInfo.CallOperand;
Chris Lattner3d81fee2006-02-04 02:16:44 +00004644
Chris Lattner0c583402007-04-28 20:49:53 +00004645 if (isdigit(OpInfo.ConstraintCode[0])) { // Matching constraint?
Chris Lattner2223aea2006-02-02 00:25:23 +00004646 // If this is required to match an output register we have already set,
4647 // just use its register.
Chris Lattner0c583402007-04-28 20:49:53 +00004648 unsigned OperandNo = atoi(OpInfo.ConstraintCode.c_str());
Chris Lattner3d81fee2006-02-04 02:16:44 +00004649
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00004650 // Scan until we find the definition we already emitted of this operand.
4651 // When we find it, create a RegsForValue operand.
4652 unsigned CurOp = 2; // The first operand.
4653 for (; OperandNo; --OperandNo) {
4654 // Advance to the next operand.
4655 unsigned NumOps =
4656 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
Chris Lattnera15cf702006-07-20 19:02:21 +00004657 assert(((NumOps & 7) == 2 /*REGDEF*/ ||
4658 (NumOps & 7) == 4 /*MEM*/) &&
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00004659 "Skipped past definitions?");
4660 CurOp += (NumOps>>3)+1;
4661 }
4662
4663 unsigned NumOps =
4664 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
Chris Lattner527fae12007-02-01 01:21:12 +00004665 if ((NumOps & 7) == 2 /*REGDEF*/) {
4666 // Add NumOps>>3 registers to MatchedRegs.
4667 RegsForValue MatchedRegs;
Dan Gohman23ce5022008-04-25 18:27:55 +00004668 MatchedRegs.TLI = &TLI;
Dan Gohman1fa850b2008-05-02 00:03:54 +00004669 MatchedRegs.ValueVTs.push_back(InOperandVal.getValueType());
4670 MatchedRegs.RegVTs.push_back(AsmNodeOperands[CurOp+1].getValueType());
Chris Lattner527fae12007-02-01 01:21:12 +00004671 for (unsigned i = 0, e = NumOps>>3; i != e; ++i) {
4672 unsigned Reg =
4673 cast<RegisterSDNode>(AsmNodeOperands[++CurOp])->getReg();
4674 MatchedRegs.Regs.push_back(Reg);
4675 }
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00004676
Chris Lattner527fae12007-02-01 01:21:12 +00004677 // Use the produced MatchedRegs object to
Dan Gohmanb6f5b002007-06-28 23:29:44 +00004678 MatchedRegs.getCopyToRegs(InOperandVal, DAG, Chain, &Flag);
Chris Lattner527fae12007-02-01 01:21:12 +00004679 MatchedRegs.AddInlineAsmOperands(1 /*REGUSE*/, DAG, AsmNodeOperands);
4680 break;
4681 } else {
4682 assert((NumOps & 7) == 4/*MEM*/ && "Unknown matching constraint!");
Chris Lattnerf9853bc2008-02-21 05:27:19 +00004683 assert((NumOps >> 3) == 1 && "Unexpected number of operands");
4684 // Add information to the INLINEASM node to know about this input.
4685 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
4686 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
4687 TLI.getPointerTy()));
4688 AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
4689 break;
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00004690 }
Chris Lattner2223aea2006-02-02 00:25:23 +00004691 }
Chris Lattner87bc3bd2006-02-24 01:11:24 +00004692
Chris Lattner2a600be2007-04-28 21:01:43 +00004693 if (OpInfo.ConstraintType == TargetLowering::C_Other) {
Chris Lattner0c583402007-04-28 20:49:53 +00004694 assert(!OpInfo.isIndirect &&
Chris Lattner44b2c502007-04-28 06:42:38 +00004695 "Don't know how to handle indirect other inputs yet!");
4696
Dan Gohman475871a2008-07-27 21:46:04 +00004697 std::vector<SDValue> Ops;
Chris Lattner48884cd2007-08-25 00:47:38 +00004698 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode[0],
4699 Ops, DAG);
4700 if (Ops.empty()) {
Bill Wendling832171c2006-12-07 20:04:42 +00004701 cerr << "Invalid operand for inline asm constraint '"
Chris Lattner0c583402007-04-28 20:49:53 +00004702 << OpInfo.ConstraintCode << "'!\n";
Chris Lattner53069fb2006-10-31 19:41:18 +00004703 exit(1);
4704 }
Chris Lattner87bc3bd2006-02-24 01:11:24 +00004705
4706 // Add information to the INLINEASM node to know about this input.
Chris Lattner48884cd2007-08-25 00:47:38 +00004707 unsigned ResOpType = 3 /*IMM*/ | (Ops.size() << 3);
Chris Lattnerc90233b2007-05-15 01:33:58 +00004708 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
4709 TLI.getPointerTy()));
Chris Lattner48884cd2007-08-25 00:47:38 +00004710 AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end());
Chris Lattner87bc3bd2006-02-24 01:11:24 +00004711 break;
Chris Lattner2a600be2007-04-28 21:01:43 +00004712 } else if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
Chris Lattner09e4b7e2007-04-28 21:12:06 +00004713 assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
Chris Lattner44b2c502007-04-28 06:42:38 +00004714 assert(InOperandVal.getValueType() == TLI.getPointerTy() &&
4715 "Memory operands expect pointer values");
4716
Chris Lattner87bc3bd2006-02-24 01:11:24 +00004717 // Add information to the INLINEASM node to know about this input.
4718 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
Chris Lattnerc90233b2007-05-15 01:33:58 +00004719 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
4720 TLI.getPointerTy()));
Chris Lattner87bc3bd2006-02-24 01:11:24 +00004721 AsmNodeOperands.push_back(InOperandVal);
4722 break;
4723 }
4724
Chris Lattner2a600be2007-04-28 21:01:43 +00004725 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
4726 OpInfo.ConstraintType == TargetLowering::C_Register) &&
4727 "Unknown constraint type!");
Chris Lattner0c583402007-04-28 20:49:53 +00004728 assert(!OpInfo.isIndirect &&
Chris Lattner44b2c502007-04-28 06:42:38 +00004729 "Don't know how to handle indirect register inputs yet!");
Chris Lattner87bc3bd2006-02-24 01:11:24 +00004730
4731 // Copy the input into the appropriate registers.
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004732 assert(!OpInfo.AssignedRegs.Regs.empty() &&
4733 "Couldn't allocate input reg!");
Chris Lattner87bc3bd2006-02-24 01:11:24 +00004734
Dan Gohmanb6f5b002007-06-28 23:29:44 +00004735 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, Chain, &Flag);
Chris Lattner87bc3bd2006-02-24 01:11:24 +00004736
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004737 OpInfo.AssignedRegs.AddInlineAsmOperands(1/*REGUSE*/, DAG,
4738 AsmNodeOperands);
Chris Lattner6656dd12006-01-31 02:03:41 +00004739 break;
4740 }
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00004741 case InlineAsm::isClobber: {
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00004742 // Add the clobbered value to the operand list, so that the register
4743 // allocator is aware that the physreg got clobbered.
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004744 if (!OpInfo.AssignedRegs.Regs.empty())
4745 OpInfo.AssignedRegs.AddInlineAsmOperands(2/*REGDEF*/, DAG,
4746 AsmNodeOperands);
Chris Lattner6656dd12006-01-31 02:03:41 +00004747 break;
4748 }
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00004749 }
Chris Lattner6656dd12006-01-31 02:03:41 +00004750 }
Chris Lattnerce7518c2006-01-26 22:24:51 +00004751
4752 // Finish up input operands.
4753 AsmNodeOperands[0] = Chain;
Gabor Greifba36cb52008-08-28 21:40:38 +00004754 if (Flag.getNode()) AsmNodeOperands.push_back(Flag);
Chris Lattnerce7518c2006-01-26 22:24:51 +00004755
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00004756 Chain = DAG.getNode(ISD::INLINEASM,
4757 DAG.getNodeValueTypes(MVT::Other, MVT::Flag), 2,
Chris Lattnerbd564bf2006-08-08 02:23:42 +00004758 &AsmNodeOperands[0], AsmNodeOperands.size());
Chris Lattnerce7518c2006-01-26 22:24:51 +00004759 Flag = Chain.getValue(1);
4760
Chris Lattner6656dd12006-01-31 02:03:41 +00004761 // If this asm returns a register value, copy the result from that register
4762 // and set it as the value of the call.
Chris Lattner3a508c92007-04-12 06:00:20 +00004763 if (!RetValRegs.Regs.empty()) {
Dan Gohman475871a2008-07-27 21:46:04 +00004764 SDValue Val = RetValRegs.getCopyFromRegs(DAG, Chain, &Flag);
Chris Lattner3fb29682008-04-29 04:48:56 +00004765
4766 // If any of the results of the inline asm is a vector, it may have the
4767 // wrong width/num elts. This can happen for register classes that can
4768 // contain multiple different value types. The preg or vreg allocated may
4769 // not have the same VT as was expected. Convert it to the right type with
Dan Gohman7f321562007-06-25 16:23:39 +00004770 // bit_convert.
Chris Lattner3fb29682008-04-29 04:48:56 +00004771 if (const StructType *ResSTy = dyn_cast<StructType>(CS.getType())) {
4772 for (unsigned i = 0, e = ResSTy->getNumElements(); i != e; ++i) {
Gabor Greifba36cb52008-08-28 21:40:38 +00004773 if (Val.getNode()->getValueType(i).isVector())
Chris Lattner3fb29682008-04-29 04:48:56 +00004774 Val = DAG.getNode(ISD::BIT_CONVERT,
4775 TLI.getValueType(ResSTy->getElementType(i)), Val);
4776 }
4777 } else {
Duncan Sands83ec4b62008-06-06 12:08:01 +00004778 if (Val.getValueType().isVector())
Chris Lattner3fb29682008-04-29 04:48:56 +00004779 Val = DAG.getNode(ISD::BIT_CONVERT, TLI.getValueType(CS.getType()),
4780 Val);
Chris Lattner3a508c92007-04-12 06:00:20 +00004781 }
Chris Lattner3fb29682008-04-29 04:48:56 +00004782
Duncan Sandsfd7b3262007-12-17 18:08:19 +00004783 setValue(CS.getInstruction(), Val);
Chris Lattner3a508c92007-04-12 06:00:20 +00004784 }
Chris Lattnerce7518c2006-01-26 22:24:51 +00004785
Dan Gohman475871a2008-07-27 21:46:04 +00004786 std::vector<std::pair<SDValue, Value*> > StoresToEmit;
Chris Lattner6656dd12006-01-31 02:03:41 +00004787
4788 // Process indirect outputs, first output all of the flagged copies out of
4789 // physregs.
4790 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
Chris Lattner864635a2006-02-22 22:37:12 +00004791 RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
Chris Lattner6656dd12006-01-31 02:03:41 +00004792 Value *Ptr = IndirectStoresToEmit[i].second;
Dan Gohman475871a2008-07-27 21:46:04 +00004793 SDValue OutVal = OutRegs.getCopyFromRegs(DAG, Chain, &Flag);
Chris Lattner864635a2006-02-22 22:37:12 +00004794 StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
Chris Lattner6656dd12006-01-31 02:03:41 +00004795 }
4796
4797 // Emit the non-flagged stores from the physregs.
Dan Gohman475871a2008-07-27 21:46:04 +00004798 SmallVector<SDValue, 8> OutChains;
Chris Lattner6656dd12006-01-31 02:03:41 +00004799 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i)
Chris Lattner0c583402007-04-28 20:49:53 +00004800 OutChains.push_back(DAG.getStore(Chain, StoresToEmit[i].first,
Chris Lattner6656dd12006-01-31 02:03:41 +00004801 getValue(StoresToEmit[i].second),
Evan Cheng8b2794a2006-10-13 21:14:26 +00004802 StoresToEmit[i].second, 0));
Chris Lattner6656dd12006-01-31 02:03:41 +00004803 if (!OutChains.empty())
Chris Lattnerbd564bf2006-08-08 02:23:42 +00004804 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
4805 &OutChains[0], OutChains.size());
Chris Lattnerce7518c2006-01-26 22:24:51 +00004806 DAG.setRoot(Chain);
4807}
4808
4809
Chris Lattner1c08c712005-01-07 07:47:53 +00004810void SelectionDAGLowering::visitMalloc(MallocInst &I) {
Dan Gohman475871a2008-07-27 21:46:04 +00004811 SDValue Src = getValue(I.getOperand(0));
Chris Lattner1c08c712005-01-07 07:47:53 +00004812
Duncan Sands83ec4b62008-06-06 12:08:01 +00004813 MVT IntPtr = TLI.getPointerTy();
Chris Lattner68cd65e2005-01-22 23:04:37 +00004814
Duncan Sands8e4eb092008-06-08 20:54:56 +00004815 if (IntPtr.bitsLT(Src.getValueType()))
Chris Lattner68cd65e2005-01-22 23:04:37 +00004816 Src = DAG.getNode(ISD::TRUNCATE, IntPtr, Src);
Duncan Sands8e4eb092008-06-08 20:54:56 +00004817 else if (IntPtr.bitsGT(Src.getValueType()))
Chris Lattner68cd65e2005-01-22 23:04:37 +00004818 Src = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, Src);
Chris Lattner1c08c712005-01-07 07:47:53 +00004819
4820 // Scale the source by the type size.
Duncan Sands514ab342007-11-01 20:53:16 +00004821 uint64_t ElementSize = TD->getABITypeSize(I.getType()->getElementType());
Chris Lattner1c08c712005-01-07 07:47:53 +00004822 Src = DAG.getNode(ISD::MUL, Src.getValueType(),
Chris Lattner0bd48932008-01-17 07:00:52 +00004823 Src, DAG.getIntPtrConstant(ElementSize));
Chris Lattner1c08c712005-01-07 07:47:53 +00004824
Reid Spencer47857812006-12-31 05:55:36 +00004825 TargetLowering::ArgListTy Args;
4826 TargetLowering::ArgListEntry Entry;
4827 Entry.Node = Src;
4828 Entry.Ty = TLI.getTargetData()->getIntPtrType();
Reid Spencer47857812006-12-31 05:55:36 +00004829 Args.push_back(Entry);
Chris Lattnercf5734d2005-01-08 19:26:18 +00004830
Dan Gohman475871a2008-07-27 21:46:04 +00004831 std::pair<SDValue,SDValue> Result =
Duncan Sands00fee652008-02-14 17:28:50 +00004832 TLI.LowerCallTo(getRoot(), I.getType(), false, false, false, CallingConv::C,
4833 true, DAG.getExternalSymbol("malloc", IntPtr), Args, DAG);
Chris Lattnercf5734d2005-01-08 19:26:18 +00004834 setValue(&I, Result.first); // Pointers always fit in registers
4835 DAG.setRoot(Result.second);
Chris Lattner1c08c712005-01-07 07:47:53 +00004836}
4837
4838void SelectionDAGLowering::visitFree(FreeInst &I) {
Reid Spencer47857812006-12-31 05:55:36 +00004839 TargetLowering::ArgListTy Args;
4840 TargetLowering::ArgListEntry Entry;
4841 Entry.Node = getValue(I.getOperand(0));
4842 Entry.Ty = TLI.getTargetData()->getIntPtrType();
Reid Spencer47857812006-12-31 05:55:36 +00004843 Args.push_back(Entry);
Duncan Sands83ec4b62008-06-06 12:08:01 +00004844 MVT IntPtr = TLI.getPointerTy();
Dan Gohman475871a2008-07-27 21:46:04 +00004845 std::pair<SDValue,SDValue> Result =
Duncan Sands00fee652008-02-14 17:28:50 +00004846 TLI.LowerCallTo(getRoot(), Type::VoidTy, false, false, false,
4847 CallingConv::C, true,
Chris Lattnercf5734d2005-01-08 19:26:18 +00004848 DAG.getExternalSymbol("free", IntPtr), Args, DAG);
4849 DAG.setRoot(Result.second);
Chris Lattner1c08c712005-01-07 07:47:53 +00004850}
4851
Evan Chengff9b3732008-01-30 18:18:23 +00004852// EmitInstrWithCustomInserter - This method should be implemented by targets
4853// that mark instructions with the 'usesCustomDAGSchedInserter' flag. These
Chris Lattner025c39b2005-08-26 20:54:47 +00004854// instructions are special in various ways, which require special support to
4855// insert. The specified MachineInstr is created but not inserted into any
4856// basic blocks, and the scheduler passes ownership of it to this method.
Evan Chengff9b3732008-01-30 18:18:23 +00004857MachineBasicBlock *TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
Chris Lattner025c39b2005-08-26 20:54:47 +00004858 MachineBasicBlock *MBB) {
Bill Wendling832171c2006-12-07 20:04:42 +00004859 cerr << "If a target marks an instruction with "
4860 << "'usesCustomDAGSchedInserter', it must implement "
Evan Chengff9b3732008-01-30 18:18:23 +00004861 << "TargetLowering::EmitInstrWithCustomInserter!\n";
Chris Lattner025c39b2005-08-26 20:54:47 +00004862 abort();
4863 return 0;
4864}
4865
Chris Lattner39ae3622005-01-09 00:00:49 +00004866void SelectionDAGLowering::visitVAStart(CallInst &I) {
Nate Begemanacc398c2006-01-25 18:21:52 +00004867 DAG.setRoot(DAG.getNode(ISD::VASTART, MVT::Other, getRoot(),
4868 getValue(I.getOperand(1)),
4869 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner39ae3622005-01-09 00:00:49 +00004870}
4871
4872void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
Dan Gohman475871a2008-07-27 21:46:04 +00004873 SDValue V = DAG.getVAArg(TLI.getValueType(I.getType()), getRoot(),
Nate Begemanacc398c2006-01-25 18:21:52 +00004874 getValue(I.getOperand(0)),
4875 DAG.getSrcValue(I.getOperand(0)));
4876 setValue(&I, V);
4877 DAG.setRoot(V.getValue(1));
Chris Lattner1c08c712005-01-07 07:47:53 +00004878}
4879
4880void SelectionDAGLowering::visitVAEnd(CallInst &I) {
Nate Begemanacc398c2006-01-25 18:21:52 +00004881 DAG.setRoot(DAG.getNode(ISD::VAEND, MVT::Other, getRoot(),
4882 getValue(I.getOperand(1)),
4883 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner1c08c712005-01-07 07:47:53 +00004884}
4885
4886void SelectionDAGLowering::visitVACopy(CallInst &I) {
Nate Begemanacc398c2006-01-25 18:21:52 +00004887 DAG.setRoot(DAG.getNode(ISD::VACOPY, MVT::Other, getRoot(),
4888 getValue(I.getOperand(1)),
4889 getValue(I.getOperand(2)),
4890 DAG.getSrcValue(I.getOperand(1)),
4891 DAG.getSrcValue(I.getOperand(2))));
Chris Lattner1c08c712005-01-07 07:47:53 +00004892}
4893
Chris Lattnerfdfded52006-04-12 16:20:43 +00004894/// TargetLowering::LowerArguments - This is the default LowerArguments
4895/// implementation, which just inserts a FORMAL_ARGUMENTS node. FIXME: When all
Chris Lattnerf4ec8172006-05-16 22:53:20 +00004896/// targets are migrated to using FORMAL_ARGUMENTS, this hook should be
4897/// integrated into SDISel.
Dan Gohmana44b6742008-06-30 20:31:15 +00004898void TargetLowering::LowerArguments(Function &F, SelectionDAG &DAG,
Dan Gohman475871a2008-07-27 21:46:04 +00004899 SmallVectorImpl<SDValue> &ArgValues) {
Chris Lattnerfdfded52006-04-12 16:20:43 +00004900 // Add CC# and isVararg as operands to the FORMAL_ARGUMENTS node.
Dan Gohman475871a2008-07-27 21:46:04 +00004901 SmallVector<SDValue, 3+16> Ops;
Chris Lattner8c0c10c2006-05-16 06:45:34 +00004902 Ops.push_back(DAG.getRoot());
Chris Lattnerfdfded52006-04-12 16:20:43 +00004903 Ops.push_back(DAG.getConstant(F.getCallingConv(), getPointerTy()));
4904 Ops.push_back(DAG.getConstant(F.isVarArg(), getPointerTy()));
4905
4906 // Add one result value for each formal argument.
Dan Gohmana44b6742008-06-30 20:31:15 +00004907 SmallVector<MVT, 16> RetVals;
Anton Korobeynikov6aa279d2007-01-28 18:01:49 +00004908 unsigned j = 1;
Anton Korobeynikovac2b2cf2007-01-28 16:04:40 +00004909 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end();
4910 I != E; ++I, ++j) {
Dan Gohmanf5025cf2008-06-09 21:19:23 +00004911 SmallVector<MVT, 4> ValueVTs;
4912 ComputeValueVTs(*this, I->getType(), ValueVTs);
4913 for (unsigned Value = 0, NumValues = ValueVTs.size();
4914 Value != NumValues; ++Value) {
4915 MVT VT = ValueVTs[Value];
4916 const Type *ArgTy = VT.getTypeForMVT();
4917 ISD::ArgFlagsTy Flags;
4918 unsigned OriginalAlignment =
4919 getTargetData()->getABITypeAlignment(ArgTy);
Lauro Ramos Venancio7aa47b62007-02-13 13:50:08 +00004920
Dan Gohmanf5025cf2008-06-09 21:19:23 +00004921 if (F.paramHasAttr(j, ParamAttr::ZExt))
4922 Flags.setZExt();
4923 if (F.paramHasAttr(j, ParamAttr::SExt))
4924 Flags.setSExt();
4925 if (F.paramHasAttr(j, ParamAttr::InReg))
4926 Flags.setInReg();
4927 if (F.paramHasAttr(j, ParamAttr::StructRet))
4928 Flags.setSRet();
4929 if (F.paramHasAttr(j, ParamAttr::ByVal)) {
4930 Flags.setByVal();
4931 const PointerType *Ty = cast<PointerType>(I->getType());
4932 const Type *ElementTy = Ty->getElementType();
4933 unsigned FrameAlign = getByValTypeAlignment(ElementTy);
4934 unsigned FrameSize = getTargetData()->getABITypeSize(ElementTy);
4935 // For ByVal, alignment should be passed from FE. BE will guess if
4936 // this info is not there but there are cases it cannot get right.
4937 if (F.getParamAlignment(j))
4938 FrameAlign = F.getParamAlignment(j);
4939 Flags.setByValAlign(FrameAlign);
4940 Flags.setByValSize(FrameSize);
4941 }
4942 if (F.paramHasAttr(j, ParamAttr::Nest))
4943 Flags.setNest();
4944 Flags.setOrigAlign(OriginalAlignment);
Duncan Sandsb988bac2008-02-11 20:58:28 +00004945
Dan Gohmanf5025cf2008-06-09 21:19:23 +00004946 MVT RegisterVT = getRegisterType(VT);
4947 unsigned NumRegs = getNumRegisters(VT);
4948 for (unsigned i = 0; i != NumRegs; ++i) {
4949 RetVals.push_back(RegisterVT);
4950 ISD::ArgFlagsTy MyFlags = Flags;
4951 if (NumRegs > 1 && i == 0)
4952 MyFlags.setSplit();
4953 // if it isn't first piece, alignment must be 1
4954 else if (i > 0)
4955 MyFlags.setOrigAlign(1);
4956 Ops.push_back(DAG.getArgFlags(MyFlags));
4957 }
Dan Gohmanb6f5b002007-06-28 23:29:44 +00004958 }
Chris Lattnerfdfded52006-04-12 16:20:43 +00004959 }
Evan Cheng3b0d2862006-04-25 23:03:35 +00004960
Chris Lattner8c0c10c2006-05-16 06:45:34 +00004961 RetVals.push_back(MVT::Other);
Chris Lattnerfdfded52006-04-12 16:20:43 +00004962
4963 // Create the node.
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00004964 SDNode *Result = DAG.getNode(ISD::FORMAL_ARGUMENTS,
Chris Lattner86ca3ca2008-02-13 07:39:09 +00004965 DAG.getVTList(&RetVals[0], RetVals.size()),
Gabor Greifba36cb52008-08-28 21:40:38 +00004966 &Ops[0], Ops.size()).getNode();
Chris Lattner86ca3ca2008-02-13 07:39:09 +00004967
4968 // Prelower FORMAL_ARGUMENTS. This isn't required for functionality, but
4969 // allows exposing the loads that may be part of the argument access to the
4970 // first DAGCombiner pass.
Dan Gohman475871a2008-07-27 21:46:04 +00004971 SDValue TmpRes = LowerOperation(SDValue(Result, 0), DAG);
Chris Lattner86ca3ca2008-02-13 07:39:09 +00004972
4973 // The number of results should match up, except that the lowered one may have
4974 // an extra flag result.
Gabor Greifba36cb52008-08-28 21:40:38 +00004975 assert((Result->getNumValues() == TmpRes.getNode()->getNumValues() ||
4976 (Result->getNumValues()+1 == TmpRes.getNode()->getNumValues() &&
Chris Lattner86ca3ca2008-02-13 07:39:09 +00004977 TmpRes.getValue(Result->getNumValues()).getValueType() == MVT::Flag))
4978 && "Lowering produced unexpected number of results!");
Dan Gohman2dbc1672008-07-21 21:04:07 +00004979
4980 // The FORMAL_ARGUMENTS node itself is likely no longer needed.
Gabor Greifba36cb52008-08-28 21:40:38 +00004981 if (Result != TmpRes.getNode() && Result->use_empty()) {
Dan Gohman2dbc1672008-07-21 21:04:07 +00004982 HandleSDNode Dummy(DAG.getRoot());
4983 DAG.RemoveDeadNode(Result);
4984 }
4985
Gabor Greifba36cb52008-08-28 21:40:38 +00004986 Result = TmpRes.getNode();
Chris Lattner86ca3ca2008-02-13 07:39:09 +00004987
Dan Gohman27a70be2007-07-02 16:18:06 +00004988 unsigned NumArgRegs = Result->getNumValues() - 1;
Dan Gohman475871a2008-07-27 21:46:04 +00004989 DAG.setRoot(SDValue(Result, NumArgRegs));
Chris Lattnerfdfded52006-04-12 16:20:43 +00004990
4991 // Set up the return result vector.
Chris Lattnerfdfded52006-04-12 16:20:43 +00004992 unsigned i = 0;
Reid Spencer47857812006-12-31 05:55:36 +00004993 unsigned Idx = 1;
4994 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E;
4995 ++I, ++Idx) {
Dan Gohmanf5025cf2008-06-09 21:19:23 +00004996 SmallVector<MVT, 4> ValueVTs;
4997 ComputeValueVTs(*this, I->getType(), ValueVTs);
4998 for (unsigned Value = 0, NumValues = ValueVTs.size();
4999 Value != NumValues; ++Value) {
5000 MVT VT = ValueVTs[Value];
5001 MVT PartVT = getRegisterType(VT);
Duncan Sandsb988bac2008-02-11 20:58:28 +00005002
Dan Gohmanf5025cf2008-06-09 21:19:23 +00005003 unsigned NumParts = getNumRegisters(VT);
Dan Gohman475871a2008-07-27 21:46:04 +00005004 SmallVector<SDValue, 4> Parts(NumParts);
Dan Gohmanf5025cf2008-06-09 21:19:23 +00005005 for (unsigned j = 0; j != NumParts; ++j)
Dan Gohman475871a2008-07-27 21:46:04 +00005006 Parts[j] = SDValue(Result, i++);
Duncan Sandsb988bac2008-02-11 20:58:28 +00005007
Dan Gohmanf5025cf2008-06-09 21:19:23 +00005008 ISD::NodeType AssertOp = ISD::DELETED_NODE;
5009 if (F.paramHasAttr(Idx, ParamAttr::SExt))
5010 AssertOp = ISD::AssertSext;
5011 else if (F.paramHasAttr(Idx, ParamAttr::ZExt))
5012 AssertOp = ISD::AssertZext;
Duncan Sandsb988bac2008-02-11 20:58:28 +00005013
Dan Gohmana44b6742008-06-30 20:31:15 +00005014 ArgValues.push_back(getCopyFromParts(DAG, &Parts[0], NumParts, PartVT, VT,
5015 AssertOp));
Dan Gohmanf5025cf2008-06-09 21:19:23 +00005016 }
Chris Lattnerfdfded52006-04-12 16:20:43 +00005017 }
Dan Gohman27a70be2007-07-02 16:18:06 +00005018 assert(i == NumArgRegs && "Argument register count mismatch!");
Chris Lattnerfdfded52006-04-12 16:20:43 +00005019}
5020
Chris Lattnerf4ec8172006-05-16 22:53:20 +00005021
5022/// TargetLowering::LowerCallTo - This is the default LowerCallTo
5023/// implementation, which just inserts an ISD::CALL node, which is later custom
5024/// lowered by the target to something concrete. FIXME: When all targets are
5025/// migrated to using ISD::CALL, this hook should be integrated into SDISel.
Dan Gohman475871a2008-07-27 21:46:04 +00005026std::pair<SDValue, SDValue>
5027TargetLowering::LowerCallTo(SDValue Chain, const Type *RetTy,
Duncan Sands00fee652008-02-14 17:28:50 +00005028 bool RetSExt, bool RetZExt, bool isVarArg,
5029 unsigned CallingConv, bool isTailCall,
Dan Gohman475871a2008-07-27 21:46:04 +00005030 SDValue Callee,
Chris Lattnerf4ec8172006-05-16 22:53:20 +00005031 ArgListTy &Args, SelectionDAG &DAG) {
Dan Gohman475871a2008-07-27 21:46:04 +00005032 SmallVector<SDValue, 32> Ops;
Chris Lattnerf4ec8172006-05-16 22:53:20 +00005033 Ops.push_back(Chain); // Op#0 - Chain
5034 Ops.push_back(DAG.getConstant(CallingConv, getPointerTy())); // Op#1 - CC
5035 Ops.push_back(DAG.getConstant(isVarArg, getPointerTy())); // Op#2 - VarArg
5036 Ops.push_back(DAG.getConstant(isTailCall, getPointerTy())); // Op#3 - Tail
5037 Ops.push_back(Callee);
5038
5039 // Handle all of the outgoing arguments.
5040 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
Dan Gohmanf5025cf2008-06-09 21:19:23 +00005041 SmallVector<MVT, 4> ValueVTs;
5042 ComputeValueVTs(*this, Args[i].Ty, ValueVTs);
5043 for (unsigned Value = 0, NumValues = ValueVTs.size();
5044 Value != NumValues; ++Value) {
5045 MVT VT = ValueVTs[Value];
5046 const Type *ArgTy = VT.getTypeForMVT();
Gabor Greifba36cb52008-08-28 21:40:38 +00005047 SDValue Op = SDValue(Args[i].Node.getNode(), Args[i].Node.getResNo() + Value);
Dan Gohmanf5025cf2008-06-09 21:19:23 +00005048 ISD::ArgFlagsTy Flags;
5049 unsigned OriginalAlignment =
5050 getTargetData()->getABITypeAlignment(ArgTy);
Duncan Sands276dcbd2008-03-21 09:14:45 +00005051
Dan Gohmanf5025cf2008-06-09 21:19:23 +00005052 if (Args[i].isZExt)
5053 Flags.setZExt();
5054 if (Args[i].isSExt)
5055 Flags.setSExt();
5056 if (Args[i].isInReg)
5057 Flags.setInReg();
5058 if (Args[i].isSRet)
5059 Flags.setSRet();
5060 if (Args[i].isByVal) {
5061 Flags.setByVal();
5062 const PointerType *Ty = cast<PointerType>(Args[i].Ty);
5063 const Type *ElementTy = Ty->getElementType();
5064 unsigned FrameAlign = getByValTypeAlignment(ElementTy);
5065 unsigned FrameSize = getTargetData()->getABITypeSize(ElementTy);
5066 // For ByVal, alignment should come from FE. BE will guess if this
5067 // info is not there but there are cases it cannot get right.
5068 if (Args[i].Alignment)
5069 FrameAlign = Args[i].Alignment;
5070 Flags.setByValAlign(FrameAlign);
5071 Flags.setByValSize(FrameSize);
5072 }
5073 if (Args[i].isNest)
5074 Flags.setNest();
5075 Flags.setOrigAlign(OriginalAlignment);
Dan Gohman27a70be2007-07-02 16:18:06 +00005076
Dan Gohmanf5025cf2008-06-09 21:19:23 +00005077 MVT PartVT = getRegisterType(VT);
5078 unsigned NumParts = getNumRegisters(VT);
Dan Gohman475871a2008-07-27 21:46:04 +00005079 SmallVector<SDValue, 4> Parts(NumParts);
Dan Gohmanf5025cf2008-06-09 21:19:23 +00005080 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
Duncan Sandsb988bac2008-02-11 20:58:28 +00005081
Dan Gohmanf5025cf2008-06-09 21:19:23 +00005082 if (Args[i].isSExt)
5083 ExtendKind = ISD::SIGN_EXTEND;
5084 else if (Args[i].isZExt)
5085 ExtendKind = ISD::ZERO_EXTEND;
Duncan Sandsb988bac2008-02-11 20:58:28 +00005086
Dan Gohmanf5025cf2008-06-09 21:19:23 +00005087 getCopyToParts(DAG, Op, &Parts[0], NumParts, PartVT, ExtendKind);
Duncan Sandsb988bac2008-02-11 20:58:28 +00005088
Dan Gohmanf5025cf2008-06-09 21:19:23 +00005089 for (unsigned i = 0; i != NumParts; ++i) {
5090 // if it isn't first piece, alignment must be 1
5091 ISD::ArgFlagsTy MyFlags = Flags;
5092 if (NumParts > 1 && i == 0)
5093 MyFlags.setSplit();
5094 else if (i != 0)
5095 MyFlags.setOrigAlign(1);
Duncan Sandsb988bac2008-02-11 20:58:28 +00005096
Dan Gohmanf5025cf2008-06-09 21:19:23 +00005097 Ops.push_back(Parts[i]);
5098 Ops.push_back(DAG.getArgFlags(MyFlags));
5099 }
Dan Gohman27a70be2007-07-02 16:18:06 +00005100 }
Chris Lattnerf4ec8172006-05-16 22:53:20 +00005101 }
5102
Dan Gohmanef5d1942008-03-11 21:11:25 +00005103 // Figure out the result value types. We start by making a list of
Dan Gohman23ce5022008-04-25 18:27:55 +00005104 // the potentially illegal return value types.
Duncan Sands83ec4b62008-06-06 12:08:01 +00005105 SmallVector<MVT, 4> LoweredRetTys;
5106 SmallVector<MVT, 4> RetTys;
Dan Gohman23ce5022008-04-25 18:27:55 +00005107 ComputeValueVTs(*this, RetTy, RetTys);
Dan Gohmanef5d1942008-03-11 21:11:25 +00005108
Dan Gohman23ce5022008-04-25 18:27:55 +00005109 // Then we translate that to a list of legal types.
5110 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
Duncan Sands83ec4b62008-06-06 12:08:01 +00005111 MVT VT = RetTys[I];
5112 MVT RegisterVT = getRegisterType(VT);
Dan Gohmanef5d1942008-03-11 21:11:25 +00005113 unsigned NumRegs = getNumRegisters(VT);
5114 for (unsigned i = 0; i != NumRegs; ++i)
5115 LoweredRetTys.push_back(RegisterVT);
5116 }
Chris Lattnerf4ec8172006-05-16 22:53:20 +00005117
Dan Gohmanef5d1942008-03-11 21:11:25 +00005118 LoweredRetTys.push_back(MVT::Other); // Always has a chain.
Chris Lattnerf4ec8172006-05-16 22:53:20 +00005119
Dan Gohmanb6f5b002007-06-28 23:29:44 +00005120 // Create the CALL node.
Dan Gohman475871a2008-07-27 21:46:04 +00005121 SDValue Res = DAG.getNode(ISD::CALL,
Dan Gohmanef5d1942008-03-11 21:11:25 +00005122 DAG.getVTList(&LoweredRetTys[0],
5123 LoweredRetTys.size()),
Chris Lattnerbe384162006-08-16 22:57:46 +00005124 &Ops[0], Ops.size());
Dan Gohmanef5d1942008-03-11 21:11:25 +00005125 Chain = Res.getValue(LoweredRetTys.size() - 1);
Dan Gohmanb6f5b002007-06-28 23:29:44 +00005126
5127 // Gather up the call result into a single value.
5128 if (RetTy != Type::VoidTy) {
Duncan Sands00fee652008-02-14 17:28:50 +00005129 ISD::NodeType AssertOp = ISD::DELETED_NODE;
5130
5131 if (RetSExt)
5132 AssertOp = ISD::AssertSext;
5133 else if (RetZExt)
Dan Gohmanb6f5b002007-06-28 23:29:44 +00005134 AssertOp = ISD::AssertZext;
Duncan Sands00fee652008-02-14 17:28:50 +00005135
Dan Gohman475871a2008-07-27 21:46:04 +00005136 SmallVector<SDValue, 4> ReturnValues;
Dan Gohmanef5d1942008-03-11 21:11:25 +00005137 unsigned RegNo = 0;
Dan Gohman23ce5022008-04-25 18:27:55 +00005138 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
Duncan Sands83ec4b62008-06-06 12:08:01 +00005139 MVT VT = RetTys[I];
5140 MVT RegisterVT = getRegisterType(VT);
Dan Gohmanef5d1942008-03-11 21:11:25 +00005141 unsigned NumRegs = getNumRegisters(VT);
5142 unsigned RegNoEnd = NumRegs + RegNo;
Dan Gohman475871a2008-07-27 21:46:04 +00005143 SmallVector<SDValue, 4> Results;
Dan Gohmanef5d1942008-03-11 21:11:25 +00005144 for (; RegNo != RegNoEnd; ++RegNo)
5145 Results.push_back(Res.getValue(RegNo));
Dan Gohman475871a2008-07-27 21:46:04 +00005146 SDValue ReturnValue =
Dan Gohmanef5d1942008-03-11 21:11:25 +00005147 getCopyFromParts(DAG, &Results[0], NumRegs, RegisterVT, VT,
5148 AssertOp);
5149 ReturnValues.push_back(ReturnValue);
5150 }
Duncan Sandsf9516202008-06-30 10:19:09 +00005151 Res = DAG.getMergeValues(DAG.getVTList(&RetTys[0], RetTys.size()),
5152 &ReturnValues[0], ReturnValues.size());
Chris Lattnerf4ec8172006-05-16 22:53:20 +00005153 }
Dan Gohmanb6f5b002007-06-28 23:29:44 +00005154
5155 return std::make_pair(Res, Chain);
Chris Lattnerf4ec8172006-05-16 22:53:20 +00005156}
5157
Dan Gohman475871a2008-07-27 21:46:04 +00005158SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) {
Chris Lattner171453a2005-01-16 07:28:41 +00005159 assert(0 && "LowerOperation not implemented for this target!");
5160 abort();
Dan Gohman475871a2008-07-27 21:46:04 +00005161 return SDValue();
Chris Lattner171453a2005-01-16 07:28:41 +00005162}
5163
Nate Begeman0aed7842006-01-28 03:14:31 +00005164
Chris Lattner7041ee32005-01-11 05:56:49 +00005165//===----------------------------------------------------------------------===//
5166// SelectionDAGISel code
5167//===----------------------------------------------------------------------===//
Chris Lattner1c08c712005-01-07 07:47:53 +00005168
Dan Gohman7c3234c2008-08-27 23:52:12 +00005169SelectionDAGISel::SelectionDAGISel(TargetLowering &tli, bool fast) :
5170 FunctionPass((intptr_t)&ID), TLI(tli),
5171 FuncInfo(new FunctionLoweringInfo(TLI)),
5172 CurDAG(new SelectionDAG(TLI, *FuncInfo)),
5173 SDL(new SelectionDAGLowering(*CurDAG, TLI, *FuncInfo)),
5174 GFI(),
5175 Fast(fast),
5176 DAGSize(0)
5177{}
5178
5179SelectionDAGISel::~SelectionDAGISel() {
5180 delete SDL;
5181 delete CurDAG;
5182 delete FuncInfo;
5183}
5184
Duncan Sands83ec4b62008-06-06 12:08:01 +00005185unsigned SelectionDAGISel::MakeReg(MVT VT) {
Chris Lattner84bc5422007-12-31 04:13:23 +00005186 return RegInfo->createVirtualRegister(TLI.getRegClassFor(VT));
Chris Lattner1c08c712005-01-07 07:47:53 +00005187}
5188
Chris Lattner495a0b52005-08-17 06:37:43 +00005189void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const {
Jim Laskeyc7c3f112006-10-16 20:52:31 +00005190 AU.addRequired<AliasAnalysis>();
Gordon Henriksen5eca0752008-08-17 18:44:35 +00005191 AU.addRequired<GCModuleInfo>();
Chris Lattnerc8d288f2007-03-31 04:18:03 +00005192 AU.setPreservesAll();
Chris Lattner495a0b52005-08-17 06:37:43 +00005193}
Chris Lattner1c08c712005-01-07 07:47:53 +00005194
Chris Lattner1c08c712005-01-07 07:47:53 +00005195bool SelectionDAGISel::runOnFunction(Function &Fn) {
Dan Gohman5f43f922007-08-27 16:26:13 +00005196 // Get alias analysis for load/store combining.
5197 AA = &getAnalysis<AliasAnalysis>();
5198
Chris Lattner1c08c712005-01-07 07:47:53 +00005199 MachineFunction &MF = MachineFunction::construct(&Fn, TLI.getTargetMachine());
Gordon Henriksen5eca0752008-08-17 18:44:35 +00005200 if (MF.getFunction()->hasGC())
5201 GFI = &getAnalysis<GCModuleInfo>().getFunctionInfo(*MF.getFunction());
Gordon Henriksence224772008-01-07 01:30:38 +00005202 else
Gordon Henriksen5eca0752008-08-17 18:44:35 +00005203 GFI = 0;
Chris Lattner84bc5422007-12-31 04:13:23 +00005204 RegInfo = &MF.getRegInfo();
Bill Wendling832171c2006-12-07 20:04:42 +00005205 DOUT << "\n\n\n=== " << Fn.getName() << "\n";
Chris Lattner1c08c712005-01-07 07:47:53 +00005206
Dan Gohman7c3234c2008-08-27 23:52:12 +00005207 FuncInfo->set(Fn, MF);
5208 CurDAG->init(MF, getAnalysisToUpdate<MachineModuleInfo>());
5209 SDL->init(GFI, *AA);
Chris Lattner1c08c712005-01-07 07:47:53 +00005210
Dale Johannesen1532f3d2008-04-02 00:25:04 +00005211 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
5212 if (InvokeInst *Invoke = dyn_cast<InvokeInst>(I->getTerminator()))
5213 // Mark landing pad.
Dan Gohman7c3234c2008-08-27 23:52:12 +00005214 FuncInfo->MBBMap[Invoke->getSuccessor(1)]->setIsLandingPad();
Duncan Sands9fac0b52007-06-06 10:05:18 +00005215
Dan Gohman7c3234c2008-08-27 23:52:12 +00005216 SelectAllBasicBlocks(Fn, MF);
Misha Brukmanedf128a2005-04-21 22:36:52 +00005217
Evan Chengad2070c2007-02-10 02:43:39 +00005218 // Add function live-ins to entry block live-in set.
5219 BasicBlock *EntryBB = &Fn.getEntryBlock();
Dan Gohman7c3234c2008-08-27 23:52:12 +00005220 BB = FuncInfo->MBBMap[EntryBB];
Chris Lattner84bc5422007-12-31 04:13:23 +00005221 if (!RegInfo->livein_empty())
5222 for (MachineRegisterInfo::livein_iterator I = RegInfo->livein_begin(),
5223 E = RegInfo->livein_end(); I != E; ++I)
Evan Chengad2070c2007-02-10 02:43:39 +00005224 BB->addLiveIn(I->first);
5225
Duncan Sandsf4070822007-06-15 19:04:19 +00005226#ifndef NDEBUG
Dan Gohman7c3234c2008-08-27 23:52:12 +00005227 assert(FuncInfo->CatchInfoFound.size() == FuncInfo->CatchInfoLost.size() &&
Duncan Sandsf4070822007-06-15 19:04:19 +00005228 "Not all catch info was assigned to a landing pad!");
5229#endif
5230
Dan Gohman7c3234c2008-08-27 23:52:12 +00005231 FuncInfo->clear();
5232
Chris Lattner1c08c712005-01-07 07:47:53 +00005233 return true;
5234}
5235
Chris Lattner6833b062008-04-28 07:16:35 +00005236void SelectionDAGLowering::CopyValueToVirtualRegister(Value *V, unsigned Reg) {
Dan Gohman475871a2008-07-27 21:46:04 +00005237 SDValue Op = getValue(V);
Chris Lattner18c2f132005-01-13 20:50:02 +00005238 assert((Op.getOpcode() != ISD::CopyFromReg ||
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00005239 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
Chris Lattner18c2f132005-01-13 20:50:02 +00005240 "Copy from a reg to the same reg!");
Dan Gohman86e1ebf2008-03-27 19:56:19 +00005241 assert(!TargetRegisterInfo::isPhysicalRegister(Reg) && "Is a physreg");
Dan Gohmanb6f5b002007-06-28 23:29:44 +00005242
Dan Gohman23ce5022008-04-25 18:27:55 +00005243 RegsForValue RFV(TLI, Reg, V->getType());
Dan Gohman475871a2008-07-27 21:46:04 +00005244 SDValue Chain = DAG.getEntryNode();
Dan Gohman23ce5022008-04-25 18:27:55 +00005245 RFV.getCopyToRegs(Op, DAG, Chain, 0);
5246 PendingExports.push_back(Chain);
Chris Lattner1c08c712005-01-07 07:47:53 +00005247}
5248
Chris Lattner068a81e2005-01-17 17:15:02 +00005249void SelectionDAGISel::
Dan Gohman7c3234c2008-08-27 23:52:12 +00005250LowerArguments(BasicBlock *LLVMBB) {
Chris Lattner068a81e2005-01-17 17:15:02 +00005251 // If this is the entry block, emit arguments.
Evan Cheng15699fc2007-02-10 01:08:18 +00005252 Function &F = *LLVMBB->getParent();
Dan Gohman7c3234c2008-08-27 23:52:12 +00005253 SDValue OldRoot = SDL->DAG.getRoot();
Dan Gohman475871a2008-07-27 21:46:04 +00005254 SmallVector<SDValue, 16> Args;
Dan Gohman7c3234c2008-08-27 23:52:12 +00005255 TLI.LowerArguments(F, SDL->DAG, Args);
Chris Lattner068a81e2005-01-17 17:15:02 +00005256
Chris Lattnerbf209482005-10-30 19:42:35 +00005257 unsigned a = 0;
5258 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
Dan Gohmanf5025cf2008-06-09 21:19:23 +00005259 AI != E; ++AI) {
5260 SmallVector<MVT, 4> ValueVTs;
5261 ComputeValueVTs(TLI, AI->getType(), ValueVTs);
5262 unsigned NumValues = ValueVTs.size();
Chris Lattnerbf209482005-10-30 19:42:35 +00005263 if (!AI->use_empty()) {
Dan Gohman7c3234c2008-08-27 23:52:12 +00005264 SDL->setValue(AI, SDL->DAG.getMergeValues(&Args[a], NumValues));
Chris Lattnerbf209482005-10-30 19:42:35 +00005265 // If this argument is live outside of the entry block, insert a copy from
5266 // whereever we got it to the vreg that other BB's will reference it as.
Dan Gohman7c3234c2008-08-27 23:52:12 +00005267 DenseMap<const Value*, unsigned>::iterator VMI=FuncInfo->ValueMap.find(AI);
5268 if (VMI != FuncInfo->ValueMap.end()) {
5269 SDL->CopyValueToVirtualRegister(AI, VMI->second);
Chris Lattnerbf209482005-10-30 19:42:35 +00005270 }
Chris Lattner0afa8e32005-01-17 17:55:19 +00005271 }
Dan Gohmanf5025cf2008-06-09 21:19:23 +00005272 a += NumValues;
5273 }
Chris Lattnerbf209482005-10-30 19:42:35 +00005274
Chris Lattnerbf209482005-10-30 19:42:35 +00005275 // Finally, if the target has anything special to do, allow it to do so.
Chris Lattner96645412006-05-16 06:10:58 +00005276 // FIXME: this should insert code into the DAG!
Dan Gohman7c3234c2008-08-27 23:52:12 +00005277 EmitFunctionEntryCode(F, SDL->DAG.getMachineFunction());
Chris Lattner068a81e2005-01-17 17:15:02 +00005278}
5279
Duncan Sandsf4070822007-06-15 19:04:19 +00005280static void copyCatchInfo(BasicBlock *SrcBB, BasicBlock *DestBB,
5281 MachineModuleInfo *MMI, FunctionLoweringInfo &FLI) {
Duncan Sandsf4070822007-06-15 19:04:19 +00005282 for (BasicBlock::iterator I = SrcBB->begin(), E = --SrcBB->end(); I != E; ++I)
Duncan Sandscf26d7c2007-07-04 20:52:51 +00005283 if (isSelector(I)) {
Duncan Sandsf4070822007-06-15 19:04:19 +00005284 // Apply the catch info to DestBB.
5285 addCatchInfo(cast<CallInst>(*I), MMI, FLI.MBBMap[DestBB]);
5286#ifndef NDEBUG
Duncan Sands560a7372007-11-15 09:54:37 +00005287 if (!FLI.MBBMap[SrcBB]->isLandingPad())
5288 FLI.CatchInfoFound.insert(I);
Duncan Sandsf4070822007-06-15 19:04:19 +00005289#endif
5290 }
5291}
5292
Arnold Schwaighofer30e62c02008-04-30 09:16:33 +00005293/// IsFixedFrameObjectWithPosOffset - Check if object is a fixed frame object and
5294/// whether object offset >= 0.
5295static bool
Dan Gohman475871a2008-07-27 21:46:04 +00005296IsFixedFrameObjectWithPosOffset(MachineFrameInfo * MFI, SDValue Op) {
Arnold Schwaighofer30e62c02008-04-30 09:16:33 +00005297 if (!isa<FrameIndexSDNode>(Op)) return false;
5298
5299 FrameIndexSDNode * FrameIdxNode = dyn_cast<FrameIndexSDNode>(Op);
5300 int FrameIdx = FrameIdxNode->getIndex();
5301 return MFI->isFixedObjectIndex(FrameIdx) &&
5302 MFI->getObjectOffset(FrameIdx) >= 0;
5303}
5304
5305/// IsPossiblyOverwrittenArgumentOfTailCall - Check if the operand could
5306/// possibly be overwritten when lowering the outgoing arguments in a tail
5307/// call. Currently the implementation of this call is very conservative and
5308/// assumes all arguments sourcing from FORMAL_ARGUMENTS or a CopyFromReg with
5309/// virtual registers would be overwritten by direct lowering.
Dan Gohman475871a2008-07-27 21:46:04 +00005310static bool IsPossiblyOverwrittenArgumentOfTailCall(SDValue Op,
Arnold Schwaighofer30e62c02008-04-30 09:16:33 +00005311 MachineFrameInfo * MFI) {
5312 RegisterSDNode * OpReg = NULL;
5313 if (Op.getOpcode() == ISD::FORMAL_ARGUMENTS ||
5314 (Op.getOpcode()== ISD::CopyFromReg &&
5315 (OpReg = dyn_cast<RegisterSDNode>(Op.getOperand(1))) &&
5316 (OpReg->getReg() >= TargetRegisterInfo::FirstVirtualRegister)) ||
5317 (Op.getOpcode() == ISD::LOAD &&
5318 IsFixedFrameObjectWithPosOffset(MFI, Op.getOperand(1))) ||
5319 (Op.getOpcode() == ISD::MERGE_VALUES &&
Gabor Greif99a6cb92008-08-26 22:36:50 +00005320 Op.getOperand(Op.getResNo()).getOpcode() == ISD::LOAD &&
5321 IsFixedFrameObjectWithPosOffset(MFI, Op.getOperand(Op.getResNo()).
Arnold Schwaighofer30e62c02008-04-30 09:16:33 +00005322 getOperand(1))))
5323 return true;
5324 return false;
5325}
5326
Arnold Schwaighoferc85e1712007-10-11 19:40:01 +00005327/// CheckDAGForTailCallsAndFixThem - This Function looks for CALL nodes in the
Arnold Schwaighofer48abc5c2007-10-12 21:30:57 +00005328/// DAG and fixes their tailcall attribute operand.
Arnold Schwaighoferc85e1712007-10-11 19:40:01 +00005329static void CheckDAGForTailCallsAndFixThem(SelectionDAG &DAG,
5330 TargetLowering& TLI) {
5331 SDNode * Ret = NULL;
Dan Gohman475871a2008-07-27 21:46:04 +00005332 SDValue Terminator = DAG.getRoot();
Arnold Schwaighoferc85e1712007-10-11 19:40:01 +00005333
5334 // Find RET node.
5335 if (Terminator.getOpcode() == ISD::RET) {
Gabor Greifba36cb52008-08-28 21:40:38 +00005336 Ret = Terminator.getNode();
Arnold Schwaighoferc85e1712007-10-11 19:40:01 +00005337 }
5338
5339 // Fix tail call attribute of CALL nodes.
5340 for (SelectionDAG::allnodes_iterator BE = DAG.allnodes_begin(),
Dan Gohman0e5f1302008-07-07 23:02:41 +00005341 BI = DAG.allnodes_end(); BI != BE; ) {
5342 --BI;
Arnold Schwaighoferc85e1712007-10-11 19:40:01 +00005343 if (BI->getOpcode() == ISD::CALL) {
Dan Gohman475871a2008-07-27 21:46:04 +00005344 SDValue OpRet(Ret, 0);
5345 SDValue OpCall(BI, 0);
Arnold Schwaighoferc85e1712007-10-11 19:40:01 +00005346 bool isMarkedTailCall =
5347 cast<ConstantSDNode>(OpCall.getOperand(3))->getValue() != 0;
5348 // If CALL node has tail call attribute set to true and the call is not
5349 // eligible (no RET or the target rejects) the attribute is fixed to
Arnold Schwaighofer48abc5c2007-10-12 21:30:57 +00005350 // false. The TargetLowering::IsEligibleForTailCallOptimization function
Arnold Schwaighoferc85e1712007-10-11 19:40:01 +00005351 // must correctly identify tail call optimizable calls.
Arnold Schwaighofer30e62c02008-04-30 09:16:33 +00005352 if (!isMarkedTailCall) continue;
5353 if (Ret==NULL ||
5354 !TLI.IsEligibleForTailCallOptimization(OpCall, OpRet, DAG)) {
5355 // Not eligible. Mark CALL node as non tail call.
Dan Gohman475871a2008-07-27 21:46:04 +00005356 SmallVector<SDValue, 32> Ops;
Arnold Schwaighoferc85e1712007-10-11 19:40:01 +00005357 unsigned idx=0;
Gabor Greifba36cb52008-08-28 21:40:38 +00005358 for(SDNode::op_iterator I =OpCall.getNode()->op_begin(),
5359 E = OpCall.getNode()->op_end(); I != E; I++, idx++) {
Arnold Schwaighoferc85e1712007-10-11 19:40:01 +00005360 if (idx!=3)
5361 Ops.push_back(*I);
Arnold Schwaighofer30e62c02008-04-30 09:16:33 +00005362 else
Arnold Schwaighoferc85e1712007-10-11 19:40:01 +00005363 Ops.push_back(DAG.getConstant(false, TLI.getPointerTy()));
5364 }
5365 DAG.UpdateNodeOperands(OpCall, Ops.begin(), Ops.size());
Arnold Schwaighofer30e62c02008-04-30 09:16:33 +00005366 } else {
5367 // Look for tail call clobbered arguments. Emit a series of
5368 // copyto/copyfrom virtual register nodes to protect them.
Dan Gohman475871a2008-07-27 21:46:04 +00005369 SmallVector<SDValue, 32> Ops;
5370 SDValue Chain = OpCall.getOperand(0), InFlag;
Arnold Schwaighofer30e62c02008-04-30 09:16:33 +00005371 unsigned idx=0;
Gabor Greifba36cb52008-08-28 21:40:38 +00005372 for(SDNode::op_iterator I = OpCall.getNode()->op_begin(),
5373 E = OpCall.getNode()->op_end(); I != E; I++, idx++) {
Dan Gohman475871a2008-07-27 21:46:04 +00005374 SDValue Arg = *I;
Arnold Schwaighofer30e62c02008-04-30 09:16:33 +00005375 if (idx > 4 && (idx % 2)) {
5376 bool isByVal = cast<ARG_FLAGSSDNode>(OpCall.getOperand(idx+1))->
5377 getArgFlags().isByVal();
5378 MachineFunction &MF = DAG.getMachineFunction();
5379 MachineFrameInfo *MFI = MF.getFrameInfo();
5380 if (!isByVal &&
5381 IsPossiblyOverwrittenArgumentOfTailCall(Arg, MFI)) {
Duncan Sands83ec4b62008-06-06 12:08:01 +00005382 MVT VT = Arg.getValueType();
Arnold Schwaighofer30e62c02008-04-30 09:16:33 +00005383 unsigned VReg = MF.getRegInfo().
5384 createVirtualRegister(TLI.getRegClassFor(VT));
5385 Chain = DAG.getCopyToReg(Chain, VReg, Arg, InFlag);
5386 InFlag = Chain.getValue(1);
5387 Arg = DAG.getCopyFromReg(Chain, VReg, VT, InFlag);
5388 Chain = Arg.getValue(1);
5389 InFlag = Arg.getValue(2);
5390 }
5391 }
5392 Ops.push_back(Arg);
5393 }
5394 // Link in chain of CopyTo/CopyFromReg.
5395 Ops[0] = Chain;
5396 DAG.UpdateNodeOperands(OpCall, Ops.begin(), Ops.size());
Arnold Schwaighoferc85e1712007-10-11 19:40:01 +00005397 }
5398 }
5399 }
5400}
5401
Dan Gohmanf350b272008-08-23 02:25:05 +00005402/// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
5403/// ensure constants are generated when needed. Remember the virtual registers
5404/// that need to be added to the Machine PHI nodes as input. We cannot just
5405/// directly add them, because expansion might result in multiple MBB's for one
5406/// BB. As such, the start of the BB might correspond to a different MBB than
5407/// the end.
5408///
5409void
Dan Gohman7c3234c2008-08-27 23:52:12 +00005410SelectionDAGISel::HandlePHINodesInSuccessorBlocks(BasicBlock *LLVMBB) {
Chris Lattner8c494ab2006-10-27 23:50:33 +00005411 TerminatorInst *TI = LLVMBB->getTerminator();
Chris Lattner1c08c712005-01-07 07:47:53 +00005412
Dan Gohman7c3234c2008-08-27 23:52:12 +00005413 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
5414
Dan Gohman532dc2e2007-07-09 20:59:04 +00005415 // Check successor nodes' PHI nodes that expect a constant to be available
5416 // from this block.
Chris Lattner1c08c712005-01-07 07:47:53 +00005417 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
5418 BasicBlock *SuccBB = TI->getSuccessor(succ);
Chris Lattnerd5e93c02006-09-07 01:59:34 +00005419 if (!isa<PHINode>(SuccBB->begin())) continue;
Dan Gohman7c3234c2008-08-27 23:52:12 +00005420 MachineBasicBlock *SuccMBB = FuncInfo->MBBMap[SuccBB];
Chris Lattnerd5e93c02006-09-07 01:59:34 +00005421
Chris Lattner8c494ab2006-10-27 23:50:33 +00005422 // If this terminator has multiple identical successors (common for
5423 // switches), only handle each succ once.
Dan Gohman7c3234c2008-08-27 23:52:12 +00005424 if (!SuccsHandled.insert(SuccMBB)) continue;
Chris Lattner8c494ab2006-10-27 23:50:33 +00005425
5426 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
Chris Lattner1c08c712005-01-07 07:47:53 +00005427 PHINode *PN;
5428
5429 // At this point we know that there is a 1-1 correspondence between LLVM PHI
5430 // nodes and Machine PHI nodes, but the incoming operands have not been
5431 // emitted yet.
5432 for (BasicBlock::iterator I = SuccBB->begin();
Chris Lattner8c494ab2006-10-27 23:50:33 +00005433 (PN = dyn_cast<PHINode>(I)); ++I) {
5434 // Ignore dead phi's.
5435 if (PN->use_empty()) continue;
Dan Gohman7c3234c2008-08-27 23:52:12 +00005436
Chris Lattner8c494ab2006-10-27 23:50:33 +00005437 unsigned Reg;
5438 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
Dan Gohman7c3234c2008-08-27 23:52:12 +00005439
Chris Lattner8c494ab2006-10-27 23:50:33 +00005440 if (Constant *C = dyn_cast<Constant>(PHIOp)) {
Dan Gohman7c3234c2008-08-27 23:52:12 +00005441 unsigned &RegOut = SDL->ConstantsOut[C];
Chris Lattner8c494ab2006-10-27 23:50:33 +00005442 if (RegOut == 0) {
Dan Gohman7c3234c2008-08-27 23:52:12 +00005443 RegOut = FuncInfo->CreateRegForValue(C);
5444 SDL->CopyValueToVirtualRegister(C, RegOut);
Chris Lattner1c08c712005-01-07 07:47:53 +00005445 }
Chris Lattner8c494ab2006-10-27 23:50:33 +00005446 Reg = RegOut;
5447 } else {
Dan Gohman7c3234c2008-08-27 23:52:12 +00005448 Reg = FuncInfo->ValueMap[PHIOp];
Chris Lattner8c494ab2006-10-27 23:50:33 +00005449 if (Reg == 0) {
5450 assert(isa<AllocaInst>(PHIOp) &&
Dan Gohman7c3234c2008-08-27 23:52:12 +00005451 FuncInfo->StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
Chris Lattner8c494ab2006-10-27 23:50:33 +00005452 "Didn't codegen value into a register!??");
Dan Gohman7c3234c2008-08-27 23:52:12 +00005453 Reg = FuncInfo->CreateRegForValue(PHIOp);
5454 SDL->CopyValueToVirtualRegister(PHIOp, Reg);
Chris Lattner7e021512006-03-31 02:12:18 +00005455 }
Chris Lattner1c08c712005-01-07 07:47:53 +00005456 }
Chris Lattner8c494ab2006-10-27 23:50:33 +00005457
5458 // Remember that this register needs to added to the machine PHI node as
5459 // the input for this MBB.
Dan Gohman6f498b02008-08-04 23:42:46 +00005460 SmallVector<MVT, 4> ValueVTs;
5461 ComputeValueVTs(TLI, PN->getType(), ValueVTs);
5462 for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
5463 MVT VT = ValueVTs[vti];
5464 unsigned NumRegisters = TLI.getNumRegisters(VT);
5465 for (unsigned i = 0, e = NumRegisters; i != e; ++i)
Dan Gohman7c3234c2008-08-27 23:52:12 +00005466 SDL->PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
Dan Gohman6f498b02008-08-04 23:42:46 +00005467 Reg += NumRegisters;
5468 }
Chris Lattner8c494ab2006-10-27 23:50:33 +00005469 }
Chris Lattner1c08c712005-01-07 07:47:53 +00005470 }
Dan Gohman7c3234c2008-08-27 23:52:12 +00005471 SDL->ConstantsOut.clear();
Chris Lattner1c08c712005-01-07 07:47:53 +00005472
5473 // Lower the terminator after the copies are emitted.
Dan Gohman7c3234c2008-08-27 23:52:12 +00005474 SDL->visit(*LLVMBB->getTerminator());
Dan Gohmanf350b272008-08-23 02:25:05 +00005475}
5476
5477void SelectionDAGISel::SelectBasicBlock(BasicBlock *LLVMBB,
5478 BasicBlock::iterator Begin,
Dan Gohman5edd3612008-08-28 20:28:56 +00005479 BasicBlock::iterator End) {
Dan Gohman7c3234c2008-08-27 23:52:12 +00005480 SDL->setCurrentBasicBlock(BB);
Dan Gohmanf350b272008-08-23 02:25:05 +00005481
5482 MachineModuleInfo *MMI = CurDAG->getMachineModuleInfo();
5483
5484 if (MMI && BB->isLandingPad()) {
5485 // Add a label to mark the beginning of the landing pad. Deletion of the
5486 // landing pad can thus be detected via the MachineModuleInfo.
5487 unsigned LabelID = MMI->addLandingPad(BB);
5488 CurDAG->setRoot(CurDAG->getLabel(ISD::EH_LABEL,
5489 CurDAG->getEntryNode(), LabelID));
5490
5491 // Mark exception register as live in.
5492 unsigned Reg = TLI.getExceptionAddressRegister();
5493 if (Reg) BB->addLiveIn(Reg);
5494
5495 // Mark exception selector register as live in.
5496 Reg = TLI.getExceptionSelectorRegister();
5497 if (Reg) BB->addLiveIn(Reg);
5498
5499 // FIXME: Hack around an exception handling flaw (PR1508): the personality
5500 // function and list of typeids logically belong to the invoke (or, if you
5501 // like, the basic block containing the invoke), and need to be associated
5502 // with it in the dwarf exception handling tables. Currently however the
5503 // information is provided by an intrinsic (eh.selector) that can be moved
5504 // to unexpected places by the optimizers: if the unwind edge is critical,
5505 // then breaking it can result in the intrinsics being in the successor of
5506 // the landing pad, not the landing pad itself. This results in exceptions
5507 // not being caught because no typeids are associated with the invoke.
5508 // This may not be the only way things can go wrong, but it is the only way
5509 // we try to work around for the moment.
5510 BranchInst *Br = dyn_cast<BranchInst>(LLVMBB->getTerminator());
5511
5512 if (Br && Br->isUnconditional()) { // Critical edge?
5513 BasicBlock::iterator I, E;
5514 for (I = LLVMBB->begin(), E = --LLVMBB->end(); I != E; ++I)
5515 if (isSelector(I))
5516 break;
5517
5518 if (I == E)
5519 // No catch info found - try to extract some from the successor.
Dan Gohman7c3234c2008-08-27 23:52:12 +00005520 copyCatchInfo(Br->getSuccessor(0), LLVMBB, MMI, *FuncInfo);
Dan Gohmanf350b272008-08-23 02:25:05 +00005521 }
5522 }
5523
5524 // Lower all of the non-terminator instructions.
5525 for (BasicBlock::iterator I = Begin; I != End; ++I)
5526 if (!isa<TerminatorInst>(I))
Dan Gohman7c3234c2008-08-27 23:52:12 +00005527 SDL->visit(*I);
Dan Gohmanf350b272008-08-23 02:25:05 +00005528
5529 // Ensure that all instructions which are used outside of their defining
5530 // blocks are available as virtual registers. Invoke is handled elsewhere.
5531 for (BasicBlock::iterator I = Begin; I != End; ++I)
5532 if (!I->use_empty() && !isa<PHINode>(I) && !isa<InvokeInst>(I)) {
Dan Gohman7c3234c2008-08-27 23:52:12 +00005533 DenseMap<const Value*,unsigned>::iterator VMI =FuncInfo->ValueMap.find(I);
5534 if (VMI != FuncInfo->ValueMap.end())
5535 SDL->CopyValueToVirtualRegister(I, VMI->second);
Dan Gohmanf350b272008-08-23 02:25:05 +00005536 }
5537
5538 // Handle PHI nodes in successor blocks.
Dan Gohmand2ff6472008-09-02 20:17:56 +00005539 if (End == LLVMBB->end())
Dan Gohman7c3234c2008-08-27 23:52:12 +00005540 HandlePHINodesInSuccessorBlocks(LLVMBB);
Anton Korobeynikov4198c582007-04-09 12:31:58 +00005541
Chris Lattnera651cf62005-01-17 19:43:36 +00005542 // Make sure the root of the DAG is up-to-date.
Dan Gohman7c3234c2008-08-27 23:52:12 +00005543 CurDAG->setRoot(SDL->getControlRoot());
Arnold Schwaighoferc85e1712007-10-11 19:40:01 +00005544
5545 // Check whether calls in this block are real tail calls. Fix up CALL nodes
5546 // with correct tailcall attribute so that the target can rely on the tailcall
5547 // attribute indicating whether the call is really eligible for tail call
5548 // optimization.
Dan Gohmanf350b272008-08-23 02:25:05 +00005549 CheckDAGForTailCallsAndFixThem(*CurDAG, TLI);
5550
5551 // Final step, emit the lowered DAG as machine code.
5552 CodeGenAndEmitDAG();
Dan Gohman7c3234c2008-08-27 23:52:12 +00005553 SDL->clear();
Chris Lattner1c08c712005-01-07 07:47:53 +00005554}
5555
Dan Gohmanf350b272008-08-23 02:25:05 +00005556void SelectionDAGISel::ComputeLiveOutVRegInfo() {
Chris Lattneread0d882008-06-17 06:09:18 +00005557 SmallPtrSet<SDNode*, 128> VisitedNodes;
5558 SmallVector<SDNode*, 128> Worklist;
5559
Gabor Greifba36cb52008-08-28 21:40:38 +00005560 Worklist.push_back(CurDAG->getRoot().getNode());
Chris Lattneread0d882008-06-17 06:09:18 +00005561
5562 APInt Mask;
5563 APInt KnownZero;
5564 APInt KnownOne;
5565
5566 while (!Worklist.empty()) {
5567 SDNode *N = Worklist.back();
5568 Worklist.pop_back();
5569
5570 // If we've already seen this node, ignore it.
5571 if (!VisitedNodes.insert(N))
5572 continue;
5573
5574 // Otherwise, add all chain operands to the worklist.
5575 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
5576 if (N->getOperand(i).getValueType() == MVT::Other)
Gabor Greifba36cb52008-08-28 21:40:38 +00005577 Worklist.push_back(N->getOperand(i).getNode());
Chris Lattneread0d882008-06-17 06:09:18 +00005578
5579 // If this is a CopyToReg with a vreg dest, process it.
5580 if (N->getOpcode() != ISD::CopyToReg)
5581 continue;
5582
5583 unsigned DestReg = cast<RegisterSDNode>(N->getOperand(1))->getReg();
5584 if (!TargetRegisterInfo::isVirtualRegister(DestReg))
5585 continue;
5586
5587 // Ignore non-scalar or non-integer values.
Dan Gohman475871a2008-07-27 21:46:04 +00005588 SDValue Src = N->getOperand(2);
Chris Lattneread0d882008-06-17 06:09:18 +00005589 MVT SrcVT = Src.getValueType();
5590 if (!SrcVT.isInteger() || SrcVT.isVector())
5591 continue;
5592
Dan Gohmanf350b272008-08-23 02:25:05 +00005593 unsigned NumSignBits = CurDAG->ComputeNumSignBits(Src);
Chris Lattneread0d882008-06-17 06:09:18 +00005594 Mask = APInt::getAllOnesValue(SrcVT.getSizeInBits());
Dan Gohmanf350b272008-08-23 02:25:05 +00005595 CurDAG->ComputeMaskedBits(Src, Mask, KnownZero, KnownOne);
Chris Lattneread0d882008-06-17 06:09:18 +00005596
5597 // Only install this information if it tells us something.
5598 if (NumSignBits != 1 || KnownZero != 0 || KnownOne != 0) {
5599 DestReg -= TargetRegisterInfo::FirstVirtualRegister;
Dan Gohmanf350b272008-08-23 02:25:05 +00005600 FunctionLoweringInfo &FLI = CurDAG->getFunctionLoweringInfo();
Chris Lattneread0d882008-06-17 06:09:18 +00005601 if (DestReg >= FLI.LiveOutRegInfo.size())
5602 FLI.LiveOutRegInfo.resize(DestReg+1);
5603 FunctionLoweringInfo::LiveOutInfo &LOI = FLI.LiveOutRegInfo[DestReg];
5604 LOI.NumSignBits = NumSignBits;
5605 LOI.KnownOne = NumSignBits;
5606 LOI.KnownZero = NumSignBits;
5607 }
5608 }
5609}
5610
Dan Gohmanf350b272008-08-23 02:25:05 +00005611void SelectionDAGISel::CodeGenAndEmitDAG() {
Dan Gohman462dc7f2008-07-21 20:00:07 +00005612 std::string GroupName;
5613 if (TimePassesIsEnabled)
5614 GroupName = "Instruction Selection and Scheduling";
5615 std::string BlockName;
5616 if (ViewDAGCombine1 || ViewLegalizeTypesDAGs || ViewLegalizeDAGs ||
5617 ViewDAGCombine2 || ViewISelDAGs || ViewSchedDAGs || ViewSUnitDAGs)
Dan Gohmanf350b272008-08-23 02:25:05 +00005618 BlockName = CurDAG->getMachineFunction().getFunction()->getName() + ':' +
Dan Gohman462dc7f2008-07-21 20:00:07 +00005619 BB->getBasicBlock()->getName();
5620
5621 DOUT << "Initial selection DAG:\n";
Dan Gohmanf350b272008-08-23 02:25:05 +00005622 DEBUG(CurDAG->dump());
Dan Gohman462dc7f2008-07-21 20:00:07 +00005623
Dan Gohmanf350b272008-08-23 02:25:05 +00005624 if (ViewDAGCombine1) CurDAG->viewGraph("dag-combine1 input for " + BlockName);
Dan Gohman417e11b2007-10-08 15:12:17 +00005625
Chris Lattneraf21d552005-10-10 16:47:10 +00005626 // Run the DAG combiner in pre-legalize mode.
Evan Chengebffb662008-07-01 17:59:20 +00005627 if (TimePassesIsEnabled) {
Dan Gohman5e843682008-07-14 18:19:29 +00005628 NamedRegionTimer T("DAG Combining 1", GroupName);
Dan Gohmanf350b272008-08-23 02:25:05 +00005629 CurDAG->Combine(false, *AA, Fast);
Evan Chengebffb662008-07-01 17:59:20 +00005630 } else {
Dan Gohmanf350b272008-08-23 02:25:05 +00005631 CurDAG->Combine(false, *AA, Fast);
Evan Chengebffb662008-07-01 17:59:20 +00005632 }
Nate Begeman2300f552005-09-07 00:15:36 +00005633
Dan Gohman417e11b2007-10-08 15:12:17 +00005634 DOUT << "Optimized lowered selection DAG:\n";
Dan Gohmanf350b272008-08-23 02:25:05 +00005635 DEBUG(CurDAG->dump());
Duncan Sandsf00e74f2008-07-17 17:06:03 +00005636
Chris Lattner1c08c712005-01-07 07:47:53 +00005637 // Second step, hack on the DAG until it only uses operations and types that
5638 // the target supports.
Duncan Sandsf00e74f2008-07-17 17:06:03 +00005639 if (EnableLegalizeTypes) {// Enable this some day.
Dan Gohmanf350b272008-08-23 02:25:05 +00005640 if (ViewLegalizeTypesDAGs) CurDAG->viewGraph("legalize-types input for " +
5641 BlockName);
Dan Gohman462dc7f2008-07-21 20:00:07 +00005642
5643 if (TimePassesIsEnabled) {
5644 NamedRegionTimer T("Type Legalization", GroupName);
Dan Gohmanf350b272008-08-23 02:25:05 +00005645 CurDAG->LegalizeTypes();
Dan Gohman462dc7f2008-07-21 20:00:07 +00005646 } else {
Dan Gohmanf350b272008-08-23 02:25:05 +00005647 CurDAG->LegalizeTypes();
Dan Gohman462dc7f2008-07-21 20:00:07 +00005648 }
5649
5650 DOUT << "Type-legalized selection DAG:\n";
Dan Gohmanf350b272008-08-23 02:25:05 +00005651 DEBUG(CurDAG->dump());
Dan Gohman462dc7f2008-07-21 20:00:07 +00005652
Chris Lattner70587ea2008-07-10 23:37:50 +00005653 // TODO: enable a dag combine pass here.
5654 }
Duncan Sandsf00e74f2008-07-17 17:06:03 +00005655
Dan Gohmanf350b272008-08-23 02:25:05 +00005656 if (ViewLegalizeDAGs) CurDAG->viewGraph("legalize input for " + BlockName);
Dan Gohman462dc7f2008-07-21 20:00:07 +00005657
Evan Chengebffb662008-07-01 17:59:20 +00005658 if (TimePassesIsEnabled) {
Dan Gohman5e843682008-07-14 18:19:29 +00005659 NamedRegionTimer T("DAG Legalization", GroupName);
Dan Gohmanf350b272008-08-23 02:25:05 +00005660 CurDAG->Legalize();
Evan Chengebffb662008-07-01 17:59:20 +00005661 } else {
Dan Gohmanf350b272008-08-23 02:25:05 +00005662 CurDAG->Legalize();
Evan Chengebffb662008-07-01 17:59:20 +00005663 }
Nate Begemanf15485a2006-03-27 01:32:24 +00005664
Bill Wendling832171c2006-12-07 20:04:42 +00005665 DOUT << "Legalized selection DAG:\n";
Dan Gohmanf350b272008-08-23 02:25:05 +00005666 DEBUG(CurDAG->dump());
Nate Begemanf15485a2006-03-27 01:32:24 +00005667
Dan Gohmanf350b272008-08-23 02:25:05 +00005668 if (ViewDAGCombine2) CurDAG->viewGraph("dag-combine2 input for " + BlockName);
Dan Gohman462dc7f2008-07-21 20:00:07 +00005669
Chris Lattneraf21d552005-10-10 16:47:10 +00005670 // Run the DAG combiner in post-legalize mode.
Evan Chengebffb662008-07-01 17:59:20 +00005671 if (TimePassesIsEnabled) {
Dan Gohman5e843682008-07-14 18:19:29 +00005672 NamedRegionTimer T("DAG Combining 2", GroupName);
Dan Gohmanf350b272008-08-23 02:25:05 +00005673 CurDAG->Combine(true, *AA, Fast);
Evan Chengebffb662008-07-01 17:59:20 +00005674 } else {
Dan Gohmanf350b272008-08-23 02:25:05 +00005675 CurDAG->Combine(true, *AA, Fast);
Evan Chengebffb662008-07-01 17:59:20 +00005676 }
Nate Begeman2300f552005-09-07 00:15:36 +00005677
Dan Gohman417e11b2007-10-08 15:12:17 +00005678 DOUT << "Optimized legalized selection DAG:\n";
Dan Gohmanf350b272008-08-23 02:25:05 +00005679 DEBUG(CurDAG->dump());
Dan Gohman417e11b2007-10-08 15:12:17 +00005680
Dan Gohmanf350b272008-08-23 02:25:05 +00005681 if (ViewISelDAGs) CurDAG->viewGraph("isel input for " + BlockName);
Chris Lattneread0d882008-06-17 06:09:18 +00005682
Dan Gohman925a7e82008-08-13 19:47:40 +00005683 if (!Fast && EnableValueProp)
Dan Gohmanf350b272008-08-23 02:25:05 +00005684 ComputeLiveOutVRegInfo();
Evan Cheng552c4a82006-04-28 02:09:19 +00005685
Chris Lattnera33ef482005-03-30 01:10:47 +00005686 // Third, instruction select all of the operations to machine code, adding the
5687 // code to the MachineBasicBlock.
Evan Chengebffb662008-07-01 17:59:20 +00005688 if (TimePassesIsEnabled) {
Dan Gohman5e843682008-07-14 18:19:29 +00005689 NamedRegionTimer T("Instruction Selection", GroupName);
Dan Gohmanf350b272008-08-23 02:25:05 +00005690 InstructionSelect();
Evan Chengebffb662008-07-01 17:59:20 +00005691 } else {
Dan Gohmanf350b272008-08-23 02:25:05 +00005692 InstructionSelect();
Evan Chengebffb662008-07-01 17:59:20 +00005693 }
Evan Chengdb8d56b2008-06-30 20:45:06 +00005694
Dan Gohman462dc7f2008-07-21 20:00:07 +00005695 DOUT << "Selected selection DAG:\n";
Dan Gohmanf350b272008-08-23 02:25:05 +00005696 DEBUG(CurDAG->dump());
Dan Gohman462dc7f2008-07-21 20:00:07 +00005697
Dan Gohmanf350b272008-08-23 02:25:05 +00005698 if (ViewSchedDAGs) CurDAG->viewGraph("scheduler input for " + BlockName);
Dan Gohman462dc7f2008-07-21 20:00:07 +00005699
Dan Gohman5e843682008-07-14 18:19:29 +00005700 // Schedule machine code.
5701 ScheduleDAG *Scheduler;
5702 if (TimePassesIsEnabled) {
5703 NamedRegionTimer T("Instruction Scheduling", GroupName);
Dan Gohmanf350b272008-08-23 02:25:05 +00005704 Scheduler = Schedule();
Dan Gohman5e843682008-07-14 18:19:29 +00005705 } else {
Dan Gohmanf350b272008-08-23 02:25:05 +00005706 Scheduler = Schedule();
Dan Gohman5e843682008-07-14 18:19:29 +00005707 }
5708
Dan Gohman462dc7f2008-07-21 20:00:07 +00005709 if (ViewSUnitDAGs) Scheduler->viewGraph();
5710
Evan Chengdb8d56b2008-06-30 20:45:06 +00005711 // Emit machine code to BB. This can change 'BB' to the last block being
5712 // inserted into.
Evan Chengebffb662008-07-01 17:59:20 +00005713 if (TimePassesIsEnabled) {
Dan Gohman5e843682008-07-14 18:19:29 +00005714 NamedRegionTimer T("Instruction Creation", GroupName);
5715 BB = Scheduler->EmitSchedule();
Evan Chengebffb662008-07-01 17:59:20 +00005716 } else {
Dan Gohman5e843682008-07-14 18:19:29 +00005717 BB = Scheduler->EmitSchedule();
5718 }
5719
5720 // Free the scheduler state.
5721 if (TimePassesIsEnabled) {
5722 NamedRegionTimer T("Instruction Scheduling Cleanup", GroupName);
5723 delete Scheduler;
5724 } else {
5725 delete Scheduler;
Evan Chengebffb662008-07-01 17:59:20 +00005726 }
Evan Chengdb8d56b2008-06-30 20:45:06 +00005727
Bill Wendling832171c2006-12-07 20:04:42 +00005728 DOUT << "Selected machine code:\n";
Chris Lattner1c08c712005-01-07 07:47:53 +00005729 DEBUG(BB->dump());
Nate Begemanf15485a2006-03-27 01:32:24 +00005730}
Chris Lattner1c08c712005-01-07 07:47:53 +00005731
Dan Gohman7c3234c2008-08-27 23:52:12 +00005732void SelectionDAGISel::SelectAllBasicBlocks(Function &Fn, MachineFunction &MF) {
Evan Cheng39fd6e82008-08-07 00:43:25 +00005733 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I) {
5734 BasicBlock *LLVMBB = &*I;
Dan Gohman7c3234c2008-08-27 23:52:12 +00005735 BB = FuncInfo->MBBMap[LLVMBB];
Dan Gohmanf350b272008-08-23 02:25:05 +00005736
5737 BasicBlock::iterator Begin = LLVMBB->begin();
5738 BasicBlock::iterator End = LLVMBB->end();
Dan Gohman5edd3612008-08-28 20:28:56 +00005739
5740 // Lower any arguments needed in this block if this is the entry block.
5741 if (LLVMBB == &Fn.getEntryBlock())
5742 LowerArguments(LLVMBB);
Dan Gohmanf350b272008-08-23 02:25:05 +00005743
5744 // Before doing SelectionDAG ISel, see if FastISel has been requested.
5745 // FastISel doesn't support EH landing pads, which require special handling.
5746 if (EnableFastISel && !BB->isLandingPad()) {
Dan Gohman7c3234c2008-08-27 23:52:12 +00005747 if (FastISel *F = TLI.createFastISel(*FuncInfo->MF)) {
Dan Gohman5edd3612008-08-28 20:28:56 +00005748 // Emit code for any incoming arguments. This must happen before
5749 // beginning FastISel on the entry block.
5750 if (LLVMBB == &Fn.getEntryBlock()) {
5751 CurDAG->setRoot(SDL->getControlRoot());
5752 CodeGenAndEmitDAG();
5753 SDL->clear();
5754 }
5755 // Do FastISel on as many instructions as possible.
Dan Gohmanf350b272008-08-23 02:25:05 +00005756 while (Begin != End) {
Dan Gohman7c3234c2008-08-27 23:52:12 +00005757 Begin = F->SelectInstructions(Begin, End, FuncInfo->ValueMap,
5758 FuncInfo->MBBMap, BB);
Dan Gohmanf350b272008-08-23 02:25:05 +00005759
Dan Gohman99b21822008-08-28 23:21:34 +00005760 // If the "fast" selector selected the entire block, we're done.
Dan Gohmanf350b272008-08-23 02:25:05 +00005761 if (Begin == End)
Dan Gohmanf350b272008-08-23 02:25:05 +00005762 break;
5763
Dan Gohman99b21822008-08-28 23:21:34 +00005764 // Next, try calling the target to attempt to handle the instruction.
5765 if (F->TargetSelectInstruction(Begin, FuncInfo->ValueMap,
5766 FuncInfo->MBBMap, BB))
5767 continue;
5768
Dan Gohmanf350b272008-08-23 02:25:05 +00005769 // Handle certain instructions as single-LLVM-Instruction blocks.
5770 if (isa<CallInst>(Begin) || isa<LoadInst>(Begin) ||
5771 isa<StoreInst>(Begin)) {
5772 if (Begin->getType() != Type::VoidTy) {
Dan Gohman7c3234c2008-08-27 23:52:12 +00005773 unsigned &R = FuncInfo->ValueMap[Begin];
Dan Gohmanf350b272008-08-23 02:25:05 +00005774 if (!R)
Dan Gohman7c3234c2008-08-27 23:52:12 +00005775 R = FuncInfo->CreateRegForValue(Begin);
Dan Gohmanf350b272008-08-23 02:25:05 +00005776 }
5777
Dan Gohman5edd3612008-08-28 20:28:56 +00005778 SelectBasicBlock(LLVMBB, Begin, next(Begin));
Dan Gohmanf350b272008-08-23 02:25:05 +00005779 ++Begin;
Dan Gohmanf350b272008-08-23 02:25:05 +00005780 continue;
5781 }
5782
5783 if (!DisableFastISelAbort &&
5784 // For now, don't abort on non-conditional-branch terminators.
5785 (!isa<TerminatorInst>(Begin) ||
5786 (isa<BranchInst>(Begin) &&
5787 cast<BranchInst>(Begin)->isUnconditional()))) {
5788 // The "fast" selector couldn't handle something and bailed.
5789 // For the purpose of debugging, just abort.
5790#ifndef NDEBUG
Dan Gohman99b21822008-08-28 23:21:34 +00005791 Begin->dump();
Dan Gohmanf350b272008-08-23 02:25:05 +00005792#endif
5793 assert(0 && "FastISel didn't select the entire block");
5794 }
5795 break;
5796 }
5797 delete F;
5798 }
5799 }
5800
Dan Gohmand2ff6472008-09-02 20:17:56 +00005801 // Run SelectionDAG instruction selection on the remainder of the block
5802 // not handled by FastISel. If FastISel is not run, this is the entire
5803 // block. If FastISel is run and happens to handle all of the
5804 // LLVM Instructions in the block, [Begin,End) will be an empty range,
5805 // but we still need to run this so that
5806 // HandlePHINodesInSuccessorBlocks is called and any resulting code
5807 // is emitted.
5808 SelectBasicBlock(LLVMBB, Begin, End);
Dan Gohmanf350b272008-08-23 02:25:05 +00005809
Dan Gohman7c3234c2008-08-27 23:52:12 +00005810 FinishBasicBlock();
Evan Cheng39fd6e82008-08-07 00:43:25 +00005811 }
Dan Gohman0e5f1302008-07-07 23:02:41 +00005812}
5813
Dan Gohmanfed90b62008-07-28 21:51:04 +00005814void
Dan Gohman7c3234c2008-08-27 23:52:12 +00005815SelectionDAGISel::FinishBasicBlock() {
Dan Gohmanf350b272008-08-23 02:25:05 +00005816
5817 // Perform target specific isel post processing.
5818 InstructionSelectPostProcessing();
Nate Begemanf15485a2006-03-27 01:32:24 +00005819
Dan Gohmanf350b272008-08-23 02:25:05 +00005820 DOUT << "Target-post-processed machine code:\n";
5821 DEBUG(BB->dump());
Nate Begemanf15485a2006-03-27 01:32:24 +00005822
Anton Korobeynikov4198c582007-04-09 12:31:58 +00005823 DOUT << "Total amount of phi nodes to update: "
Dan Gohman7c3234c2008-08-27 23:52:12 +00005824 << SDL->PHINodesToUpdate.size() << "\n";
5825 DEBUG(for (unsigned i = 0, e = SDL->PHINodesToUpdate.size(); i != e; ++i)
5826 DOUT << "Node " << i << " : (" << SDL->PHINodesToUpdate[i].first
5827 << ", " << SDL->PHINodesToUpdate[i].second << ")\n";);
Nate Begemanf15485a2006-03-27 01:32:24 +00005828
Chris Lattnera33ef482005-03-30 01:10:47 +00005829 // Next, now that we know what the last MBB the LLVM BB expanded is, update
Chris Lattner1c08c712005-01-07 07:47:53 +00005830 // PHI nodes in successors.
Dan Gohman7c3234c2008-08-27 23:52:12 +00005831 if (SDL->SwitchCases.empty() &&
5832 SDL->JTCases.empty() &&
5833 SDL->BitTestCases.empty()) {
5834 for (unsigned i = 0, e = SDL->PHINodesToUpdate.size(); i != e; ++i) {
5835 MachineInstr *PHI = SDL->PHINodesToUpdate[i].first;
Nate Begemanf15485a2006-03-27 01:32:24 +00005836 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
5837 "This is not a machine PHI node that we are updating!");
Dan Gohman7c3234c2008-08-27 23:52:12 +00005838 PHI->addOperand(MachineOperand::CreateReg(SDL->PHINodesToUpdate[i].second,
Chris Lattner9ce2e9d2007-12-30 00:57:42 +00005839 false));
5840 PHI->addOperand(MachineOperand::CreateMBB(BB));
Nate Begemanf15485a2006-03-27 01:32:24 +00005841 }
Dan Gohman7c3234c2008-08-27 23:52:12 +00005842 SDL->PHINodesToUpdate.clear();
Nate Begemanf15485a2006-03-27 01:32:24 +00005843 return;
Chris Lattner1c08c712005-01-07 07:47:53 +00005844 }
Anton Korobeynikov4198c582007-04-09 12:31:58 +00005845
Dan Gohman7c3234c2008-08-27 23:52:12 +00005846 for (unsigned i = 0, e = SDL->BitTestCases.size(); i != e; ++i) {
Anton Korobeynikov4198c582007-04-09 12:31:58 +00005847 // Lower header first, if it wasn't already lowered
Dan Gohman7c3234c2008-08-27 23:52:12 +00005848 if (!SDL->BitTestCases[i].Emitted) {
Anton Korobeynikov4198c582007-04-09 12:31:58 +00005849 // Set the current basic block to the mbb we wish to insert the code into
Dan Gohman7c3234c2008-08-27 23:52:12 +00005850 BB = SDL->BitTestCases[i].Parent;
5851 SDL->setCurrentBasicBlock(BB);
Anton Korobeynikov4198c582007-04-09 12:31:58 +00005852 // Emit the code
Dan Gohman7c3234c2008-08-27 23:52:12 +00005853 SDL->visitBitTestHeader(SDL->BitTestCases[i]);
5854 CurDAG->setRoot(SDL->getRoot());
Dan Gohmanf350b272008-08-23 02:25:05 +00005855 CodeGenAndEmitDAG();
Dan Gohman7c3234c2008-08-27 23:52:12 +00005856 SDL->clear();
Anton Korobeynikov4198c582007-04-09 12:31:58 +00005857 }
5858
Dan Gohman7c3234c2008-08-27 23:52:12 +00005859 for (unsigned j = 0, ej = SDL->BitTestCases[i].Cases.size(); j != ej; ++j) {
Anton Korobeynikov4198c582007-04-09 12:31:58 +00005860 // Set the current basic block to the mbb we wish to insert the code into
Dan Gohman7c3234c2008-08-27 23:52:12 +00005861 BB = SDL->BitTestCases[i].Cases[j].ThisBB;
5862 SDL->setCurrentBasicBlock(BB);
Anton Korobeynikov4198c582007-04-09 12:31:58 +00005863 // Emit the code
5864 if (j+1 != ej)
Dan Gohman7c3234c2008-08-27 23:52:12 +00005865 SDL->visitBitTestCase(SDL->BitTestCases[i].Cases[j+1].ThisBB,
5866 SDL->BitTestCases[i].Reg,
5867 SDL->BitTestCases[i].Cases[j]);
Anton Korobeynikov4198c582007-04-09 12:31:58 +00005868 else
Dan Gohman7c3234c2008-08-27 23:52:12 +00005869 SDL->visitBitTestCase(SDL->BitTestCases[i].Default,
5870 SDL->BitTestCases[i].Reg,
5871 SDL->BitTestCases[i].Cases[j]);
Anton Korobeynikov4198c582007-04-09 12:31:58 +00005872
5873
Dan Gohman7c3234c2008-08-27 23:52:12 +00005874 CurDAG->setRoot(SDL->getRoot());
Dan Gohmanf350b272008-08-23 02:25:05 +00005875 CodeGenAndEmitDAG();
Dan Gohman7c3234c2008-08-27 23:52:12 +00005876 SDL->clear();
Anton Korobeynikov4198c582007-04-09 12:31:58 +00005877 }
5878
5879 // Update PHI Nodes
Dan Gohman7c3234c2008-08-27 23:52:12 +00005880 for (unsigned pi = 0, pe = SDL->PHINodesToUpdate.size(); pi != pe; ++pi) {
5881 MachineInstr *PHI = SDL->PHINodesToUpdate[pi].first;
Anton Korobeynikov4198c582007-04-09 12:31:58 +00005882 MachineBasicBlock *PHIBB = PHI->getParent();
5883 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
5884 "This is not a machine PHI node that we are updating!");
5885 // This is "default" BB. We have two jumps to it. From "header" BB and
5886 // from last "case" BB.
Dan Gohman7c3234c2008-08-27 23:52:12 +00005887 if (PHIBB == SDL->BitTestCases[i].Default) {
5888 PHI->addOperand(MachineOperand::CreateReg(SDL->PHINodesToUpdate[pi].second,
Chris Lattner9ce2e9d2007-12-30 00:57:42 +00005889 false));
Dan Gohman7c3234c2008-08-27 23:52:12 +00005890 PHI->addOperand(MachineOperand::CreateMBB(SDL->BitTestCases[i].Parent));
5891 PHI->addOperand(MachineOperand::CreateReg(SDL->PHINodesToUpdate[pi].second,
Chris Lattner9ce2e9d2007-12-30 00:57:42 +00005892 false));
Dan Gohman7c3234c2008-08-27 23:52:12 +00005893 PHI->addOperand(MachineOperand::CreateMBB(SDL->BitTestCases[i].Cases.
Chris Lattner9ce2e9d2007-12-30 00:57:42 +00005894 back().ThisBB));
Anton Korobeynikov4198c582007-04-09 12:31:58 +00005895 }
5896 // One of "cases" BB.
Dan Gohman7c3234c2008-08-27 23:52:12 +00005897 for (unsigned j = 0, ej = SDL->BitTestCases[i].Cases.size();
5898 j != ej; ++j) {
5899 MachineBasicBlock* cBB = SDL->BitTestCases[i].Cases[j].ThisBB;
Anton Korobeynikov4198c582007-04-09 12:31:58 +00005900 if (cBB->succ_end() !=
5901 std::find(cBB->succ_begin(),cBB->succ_end(), PHIBB)) {
Dan Gohman7c3234c2008-08-27 23:52:12 +00005902 PHI->addOperand(MachineOperand::CreateReg(SDL->PHINodesToUpdate[pi].second,
Chris Lattner9ce2e9d2007-12-30 00:57:42 +00005903 false));
5904 PHI->addOperand(MachineOperand::CreateMBB(cBB));
Anton Korobeynikov4198c582007-04-09 12:31:58 +00005905 }
5906 }
5907 }
5908 }
Dan Gohman7c3234c2008-08-27 23:52:12 +00005909 SDL->BitTestCases.clear();
Anton Korobeynikov4198c582007-04-09 12:31:58 +00005910
Nate Begeman9453eea2006-04-23 06:26:20 +00005911 // If the JumpTable record is filled in, then we need to emit a jump table.
5912 // Updating the PHI nodes is tricky in this case, since we need to determine
5913 // whether the PHI is a successor of the range check MBB or the jump table MBB
Dan Gohman7c3234c2008-08-27 23:52:12 +00005914 for (unsigned i = 0, e = SDL->JTCases.size(); i != e; ++i) {
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00005915 // Lower header first, if it wasn't already lowered
Dan Gohman7c3234c2008-08-27 23:52:12 +00005916 if (!SDL->JTCases[i].first.Emitted) {
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00005917 // Set the current basic block to the mbb we wish to insert the code into
Dan Gohman7c3234c2008-08-27 23:52:12 +00005918 BB = SDL->JTCases[i].first.HeaderBB;
5919 SDL->setCurrentBasicBlock(BB);
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00005920 // Emit the code
Dan Gohman7c3234c2008-08-27 23:52:12 +00005921 SDL->visitJumpTableHeader(SDL->JTCases[i].second, SDL->JTCases[i].first);
5922 CurDAG->setRoot(SDL->getRoot());
Dan Gohmanf350b272008-08-23 02:25:05 +00005923 CodeGenAndEmitDAG();
Dan Gohman7c3234c2008-08-27 23:52:12 +00005924 SDL->clear();
Anton Korobeynikov4198c582007-04-09 12:31:58 +00005925 }
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00005926
Nate Begeman37efe672006-04-22 18:53:45 +00005927 // Set the current basic block to the mbb we wish to insert the code into
Dan Gohman7c3234c2008-08-27 23:52:12 +00005928 BB = SDL->JTCases[i].second.MBB;
5929 SDL->setCurrentBasicBlock(BB);
Nate Begeman37efe672006-04-22 18:53:45 +00005930 // Emit the code
Dan Gohman7c3234c2008-08-27 23:52:12 +00005931 SDL->visitJumpTable(SDL->JTCases[i].second);
5932 CurDAG->setRoot(SDL->getRoot());
Dan Gohmanf350b272008-08-23 02:25:05 +00005933 CodeGenAndEmitDAG();
Dan Gohman7c3234c2008-08-27 23:52:12 +00005934 SDL->clear();
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00005935
Nate Begeman37efe672006-04-22 18:53:45 +00005936 // Update PHI Nodes
Dan Gohman7c3234c2008-08-27 23:52:12 +00005937 for (unsigned pi = 0, pe = SDL->PHINodesToUpdate.size(); pi != pe; ++pi) {
5938 MachineInstr *PHI = SDL->PHINodesToUpdate[pi].first;
Nate Begeman37efe672006-04-22 18:53:45 +00005939 MachineBasicBlock *PHIBB = PHI->getParent();
5940 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
5941 "This is not a machine PHI node that we are updating!");
Anton Korobeynikov4198c582007-04-09 12:31:58 +00005942 // "default" BB. We can go there only from header BB.
Dan Gohman7c3234c2008-08-27 23:52:12 +00005943 if (PHIBB == SDL->JTCases[i].second.Default) {
5944 PHI->addOperand(MachineOperand::CreateReg(SDL->PHINodesToUpdate[pi].second,
Chris Lattner9ce2e9d2007-12-30 00:57:42 +00005945 false));
Dan Gohman7c3234c2008-08-27 23:52:12 +00005946 PHI->addOperand(MachineOperand::CreateMBB(SDL->JTCases[i].first.HeaderBB));
Nate Begemanf4360a42006-05-03 03:48:02 +00005947 }
Anton Korobeynikov4198c582007-04-09 12:31:58 +00005948 // JT BB. Just iterate over successors here
Nate Begemanf4360a42006-05-03 03:48:02 +00005949 if (BB->succ_end() != std::find(BB->succ_begin(),BB->succ_end(), PHIBB)) {
Dan Gohman7c3234c2008-08-27 23:52:12 +00005950 PHI->addOperand(MachineOperand::CreateReg(SDL->PHINodesToUpdate[pi].second,
Chris Lattner9ce2e9d2007-12-30 00:57:42 +00005951 false));
5952 PHI->addOperand(MachineOperand::CreateMBB(BB));
Nate Begeman37efe672006-04-22 18:53:45 +00005953 }
5954 }
Nate Begeman37efe672006-04-22 18:53:45 +00005955 }
Dan Gohman7c3234c2008-08-27 23:52:12 +00005956 SDL->JTCases.clear();
Nate Begeman37efe672006-04-22 18:53:45 +00005957
Chris Lattnerb2e806e2006-10-22 23:00:53 +00005958 // If the switch block involved a branch to one of the actual successors, we
5959 // need to update PHI nodes in that block.
Dan Gohman7c3234c2008-08-27 23:52:12 +00005960 for (unsigned i = 0, e = SDL->PHINodesToUpdate.size(); i != e; ++i) {
5961 MachineInstr *PHI = SDL->PHINodesToUpdate[i].first;
Chris Lattnerb2e806e2006-10-22 23:00:53 +00005962 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
5963 "This is not a machine PHI node that we are updating!");
5964 if (BB->isSuccessor(PHI->getParent())) {
Dan Gohman7c3234c2008-08-27 23:52:12 +00005965 PHI->addOperand(MachineOperand::CreateReg(SDL->PHINodesToUpdate[i].second,
Chris Lattner9ce2e9d2007-12-30 00:57:42 +00005966 false));
5967 PHI->addOperand(MachineOperand::CreateMBB(BB));
Chris Lattnerb2e806e2006-10-22 23:00:53 +00005968 }
5969 }
5970
Nate Begemanf15485a2006-03-27 01:32:24 +00005971 // If we generated any switch lowering information, build and codegen any
5972 // additional DAGs necessary.
Dan Gohman7c3234c2008-08-27 23:52:12 +00005973 for (unsigned i = 0, e = SDL->SwitchCases.size(); i != e; ++i) {
Nate Begemanf15485a2006-03-27 01:32:24 +00005974 // Set the current basic block to the mbb we wish to insert the code into
Dan Gohman7c3234c2008-08-27 23:52:12 +00005975 BB = SDL->SwitchCases[i].ThisBB;
5976 SDL->setCurrentBasicBlock(BB);
Chris Lattnerd5e93c02006-09-07 01:59:34 +00005977
Nate Begemanf15485a2006-03-27 01:32:24 +00005978 // Emit the code
Dan Gohman7c3234c2008-08-27 23:52:12 +00005979 SDL->visitSwitchCase(SDL->SwitchCases[i]);
5980 CurDAG->setRoot(SDL->getRoot());
Dan Gohmanf350b272008-08-23 02:25:05 +00005981 CodeGenAndEmitDAG();
Dan Gohman7c3234c2008-08-27 23:52:12 +00005982 SDL->clear();
Chris Lattnerd5e93c02006-09-07 01:59:34 +00005983
5984 // Handle any PHI nodes in successors of this chunk, as if we were coming
5985 // from the original BB before switch expansion. Note that PHI nodes can
5986 // occur multiple times in PHINodesToUpdate. We have to be very careful to
5987 // handle them the right number of times.
Dan Gohman7c3234c2008-08-27 23:52:12 +00005988 while ((BB = SDL->SwitchCases[i].TrueBB)) { // Handle LHS and RHS.
Chris Lattnerd5e93c02006-09-07 01:59:34 +00005989 for (MachineBasicBlock::iterator Phi = BB->begin();
5990 Phi != BB->end() && Phi->getOpcode() == TargetInstrInfo::PHI; ++Phi){
5991 // This value for this PHI node is recorded in PHINodesToUpdate, get it.
5992 for (unsigned pn = 0; ; ++pn) {
Dan Gohman7c3234c2008-08-27 23:52:12 +00005993 assert(pn != SDL->PHINodesToUpdate.size() &&
5994 "Didn't find PHI entry!");
5995 if (SDL->PHINodesToUpdate[pn].first == Phi) {
5996 Phi->addOperand(MachineOperand::CreateReg(SDL->PHINodesToUpdate[pn].
Chris Lattner9ce2e9d2007-12-30 00:57:42 +00005997 second, false));
Dan Gohman7c3234c2008-08-27 23:52:12 +00005998 Phi->addOperand(MachineOperand::CreateMBB(SDL->SwitchCases[i].ThisBB));
Chris Lattnerd5e93c02006-09-07 01:59:34 +00005999 break;
6000 }
6001 }
Nate Begemanf15485a2006-03-27 01:32:24 +00006002 }
Chris Lattnerd5e93c02006-09-07 01:59:34 +00006003
6004 // Don't process RHS if same block as LHS.
Dan Gohman7c3234c2008-08-27 23:52:12 +00006005 if (BB == SDL->SwitchCases[i].FalseBB)
6006 SDL->SwitchCases[i].FalseBB = 0;
Chris Lattnerd5e93c02006-09-07 01:59:34 +00006007
6008 // If we haven't handled the RHS, do so now. Otherwise, we're done.
Dan Gohman7c3234c2008-08-27 23:52:12 +00006009 SDL->SwitchCases[i].TrueBB = SDL->SwitchCases[i].FalseBB;
6010 SDL->SwitchCases[i].FalseBB = 0;
Nate Begemanf15485a2006-03-27 01:32:24 +00006011 }
Dan Gohman7c3234c2008-08-27 23:52:12 +00006012 assert(SDL->SwitchCases[i].TrueBB == 0 && SDL->SwitchCases[i].FalseBB == 0);
Chris Lattnera33ef482005-03-30 01:10:47 +00006013 }
Dan Gohman7c3234c2008-08-27 23:52:12 +00006014 SDL->SwitchCases.clear();
6015
6016 SDL->PHINodesToUpdate.clear();
Chris Lattner1c08c712005-01-07 07:47:53 +00006017}
Evan Chenga9c20912006-01-21 02:32:06 +00006018
Jim Laskey13ec7022006-08-01 14:21:23 +00006019
Dan Gohman5e843682008-07-14 18:19:29 +00006020/// Schedule - Pick a safe ordering for instructions for each
Evan Chenga9c20912006-01-21 02:32:06 +00006021/// target node in the graph.
Dan Gohman5e843682008-07-14 18:19:29 +00006022///
Dan Gohmanf350b272008-08-23 02:25:05 +00006023ScheduleDAG *SelectionDAGISel::Schedule() {
Jim Laskeyeb577ba2006-08-02 12:30:23 +00006024 RegisterScheduler::FunctionPassCtor Ctor = RegisterScheduler::getDefault();
Jim Laskey13ec7022006-08-01 14:21:23 +00006025
6026 if (!Ctor) {
Jim Laskeyeb577ba2006-08-02 12:30:23 +00006027 Ctor = ISHeuristic;
Jim Laskey9373beb2006-08-01 19:14:14 +00006028 RegisterScheduler::setDefault(Ctor);
Evan Cheng4ef10862006-01-23 07:01:07 +00006029 }
Jim Laskey13ec7022006-08-01 14:21:23 +00006030
Dan Gohmanf350b272008-08-23 02:25:05 +00006031 ScheduleDAG *Scheduler = Ctor(this, CurDAG, BB, Fast);
Dan Gohman5e843682008-07-14 18:19:29 +00006032 Scheduler->Run();
Dan Gohman3e1a7ae2007-08-28 20:32:58 +00006033
Dan Gohman5e843682008-07-14 18:19:29 +00006034 return Scheduler;
Evan Chenga9c20912006-01-21 02:32:06 +00006035}
Chris Lattner0e43f2b2006-02-24 02:13:54 +00006036
Chris Lattner03fc53c2006-03-06 00:22:00 +00006037
Jim Laskey9ff542f2006-08-01 18:29:48 +00006038HazardRecognizer *SelectionDAGISel::CreateTargetHazardRecognizer() {
6039 return new HazardRecognizer();
6040}
6041
Chris Lattner75548062006-10-11 03:58:02 +00006042//===----------------------------------------------------------------------===//
6043// Helper functions used by the generated instruction selector.
6044//===----------------------------------------------------------------------===//
6045// Calls to these methods are generated by tblgen.
6046
6047/// CheckAndMask - The isel is trying to match something like (and X, 255). If
6048/// the dag combiner simplified the 255, we still want to match. RHS is the
6049/// actual value in the DAG on the RHS of an AND, and DesiredMaskS is the value
6050/// specified in the .td file (e.g. 255).
Dan Gohman475871a2008-07-27 21:46:04 +00006051bool SelectionDAGISel::CheckAndMask(SDValue LHS, ConstantSDNode *RHS,
Dan Gohmandc9b3d02007-07-24 23:00:27 +00006052 int64_t DesiredMaskS) const {
Dan Gohman2e68b6f2008-02-25 21:11:39 +00006053 const APInt &ActualMask = RHS->getAPIntValue();
6054 const APInt &DesiredMask = APInt(LHS.getValueSizeInBits(), DesiredMaskS);
Chris Lattner75548062006-10-11 03:58:02 +00006055
6056 // If the actual mask exactly matches, success!
6057 if (ActualMask == DesiredMask)
6058 return true;
6059
6060 // If the actual AND mask is allowing unallowed bits, this doesn't match.
Dan Gohman2e68b6f2008-02-25 21:11:39 +00006061 if (ActualMask.intersects(~DesiredMask))
Chris Lattner75548062006-10-11 03:58:02 +00006062 return false;
6063
6064 // Otherwise, the DAG Combiner may have proven that the value coming in is
6065 // either already zero or is not demanded. Check for known zero input bits.
Dan Gohman2e68b6f2008-02-25 21:11:39 +00006066 APInt NeededMask = DesiredMask & ~ActualMask;
Dan Gohmanea859be2007-06-22 14:59:07 +00006067 if (CurDAG->MaskedValueIsZero(LHS, NeededMask))
Chris Lattner75548062006-10-11 03:58:02 +00006068 return true;
6069
6070 // TODO: check to see if missing bits are just not demanded.
6071
6072 // Otherwise, this pattern doesn't match.
6073 return false;
6074}
6075
6076/// CheckOrMask - The isel is trying to match something like (or X, 255). If
6077/// the dag combiner simplified the 255, we still want to match. RHS is the
6078/// actual value in the DAG on the RHS of an OR, and DesiredMaskS is the value
6079/// specified in the .td file (e.g. 255).
Dan Gohman475871a2008-07-27 21:46:04 +00006080bool SelectionDAGISel::CheckOrMask(SDValue LHS, ConstantSDNode *RHS,
Dan Gohman2e68b6f2008-02-25 21:11:39 +00006081 int64_t DesiredMaskS) const {
6082 const APInt &ActualMask = RHS->getAPIntValue();
6083 const APInt &DesiredMask = APInt(LHS.getValueSizeInBits(), DesiredMaskS);
Chris Lattner75548062006-10-11 03:58:02 +00006084
6085 // If the actual mask exactly matches, success!
6086 if (ActualMask == DesiredMask)
6087 return true;
6088
6089 // If the actual AND mask is allowing unallowed bits, this doesn't match.
Dan Gohman2e68b6f2008-02-25 21:11:39 +00006090 if (ActualMask.intersects(~DesiredMask))
Chris Lattner75548062006-10-11 03:58:02 +00006091 return false;
6092
6093 // Otherwise, the DAG Combiner may have proven that the value coming in is
6094 // either already zero or is not demanded. Check for known zero input bits.
Dan Gohman2e68b6f2008-02-25 21:11:39 +00006095 APInt NeededMask = DesiredMask & ~ActualMask;
Chris Lattner75548062006-10-11 03:58:02 +00006096
Dan Gohman2e68b6f2008-02-25 21:11:39 +00006097 APInt KnownZero, KnownOne;
Dan Gohmanea859be2007-06-22 14:59:07 +00006098 CurDAG->ComputeMaskedBits(LHS, NeededMask, KnownZero, KnownOne);
Chris Lattner75548062006-10-11 03:58:02 +00006099
6100 // If all the missing bits in the or are already known to be set, match!
6101 if ((NeededMask & KnownOne) == NeededMask)
6102 return true;
6103
6104 // TODO: check to see if missing bits are just not demanded.
6105
6106 // Otherwise, this pattern doesn't match.
6107 return false;
6108}
6109
Jim Laskey9ff542f2006-08-01 18:29:48 +00006110
Chris Lattner0e43f2b2006-02-24 02:13:54 +00006111/// SelectInlineAsmMemoryOperands - Calls to this are automatically generated
6112/// by tblgen. Others should not call it.
6113void SelectionDAGISel::
Dan Gohmanf350b272008-08-23 02:25:05 +00006114SelectInlineAsmMemoryOperands(std::vector<SDValue> &Ops) {
Dan Gohman475871a2008-07-27 21:46:04 +00006115 std::vector<SDValue> InOps;
Chris Lattner0e43f2b2006-02-24 02:13:54 +00006116 std::swap(InOps, Ops);
6117
6118 Ops.push_back(InOps[0]); // input chain.
6119 Ops.push_back(InOps[1]); // input asm string.
6120
Chris Lattner0e43f2b2006-02-24 02:13:54 +00006121 unsigned i = 2, e = InOps.size();
6122 if (InOps[e-1].getValueType() == MVT::Flag)
6123 --e; // Don't process a flag operand if it is here.
6124
6125 while (i != e) {
6126 unsigned Flags = cast<ConstantSDNode>(InOps[i])->getValue();
6127 if ((Flags & 7) != 4 /*MEM*/) {
6128 // Just skip over this operand, copying the operands verbatim.
6129 Ops.insert(Ops.end(), InOps.begin()+i, InOps.begin()+i+(Flags >> 3) + 1);
6130 i += (Flags >> 3) + 1;
6131 } else {
6132 assert((Flags >> 3) == 1 && "Memory operand with multiple values?");
6133 // Otherwise, this is a memory operand. Ask the target to select it.
Dan Gohman475871a2008-07-27 21:46:04 +00006134 std::vector<SDValue> SelOps;
Dan Gohmanf350b272008-08-23 02:25:05 +00006135 if (SelectInlineAsmMemoryOperand(InOps[i+1], 'm', SelOps)) {
Bill Wendling832171c2006-12-07 20:04:42 +00006136 cerr << "Could not match memory address. Inline asm failure!\n";
Chris Lattner0e43f2b2006-02-24 02:13:54 +00006137 exit(1);
6138 }
6139
6140 // Add this to the output node.
Dan Gohmanf350b272008-08-23 02:25:05 +00006141 MVT IntPtrTy = CurDAG->getTargetLoweringInfo().getPointerTy();
6142 Ops.push_back(CurDAG->getTargetConstant(4/*MEM*/ | (SelOps.size() << 3),
6143 IntPtrTy));
Chris Lattner0e43f2b2006-02-24 02:13:54 +00006144 Ops.insert(Ops.end(), SelOps.begin(), SelOps.end());
6145 i += 2;
6146 }
6147 }
6148
6149 // Add the flag input back if present.
6150 if (e != InOps.size())
6151 Ops.push_back(InOps.back());
6152}
Devang Patel794fd752007-05-01 21:15:47 +00006153
Devang Patel19974732007-05-03 01:11:54 +00006154char SelectionDAGISel::ID = 0;