blob: e0ecda4613ad87812e2877d709c0f69cf94123bd [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
Dan Gohman7c3234c2008-08-27 23:52:12 +0000526namespace {
527
528/// CaseBlock - This structure is used to communicate between SDLowering and
529/// SDISel for the code generation of additional basic blocks needed by multi-
530/// case switch statements.
531struct CaseBlock {
532 CaseBlock(ISD::CondCode cc, Value *cmplhs, Value *cmprhs, Value *cmpmiddle,
533 MachineBasicBlock *truebb, MachineBasicBlock *falsebb,
534 MachineBasicBlock *me)
535 : CC(cc), CmpLHS(cmplhs), CmpMHS(cmpmiddle), CmpRHS(cmprhs),
536 TrueBB(truebb), FalseBB(falsebb), ThisBB(me) {}
537 // CC - the condition code to use for the case block's setcc node
538 ISD::CondCode CC;
539 // CmpLHS/CmpRHS/CmpMHS - The LHS/MHS/RHS of the comparison to emit.
540 // Emit by default LHS op RHS. MHS is used for range comparisons:
541 // If MHS is not null: (LHS <= MHS) and (MHS <= RHS).
542 Value *CmpLHS, *CmpMHS, *CmpRHS;
543 // TrueBB/FalseBB - the block to branch to if the setcc is true/false.
544 MachineBasicBlock *TrueBB, *FalseBB;
545 // ThisBB - the block into which to emit the code for the setcc and branches
546 MachineBasicBlock *ThisBB;
547};
548struct JumpTable {
549 JumpTable(unsigned R, unsigned J, MachineBasicBlock *M,
550 MachineBasicBlock *D): Reg(R), JTI(J), MBB(M), Default(D) {}
551
552 /// Reg - the virtual register containing the index of the jump table entry
553 //. to jump to.
554 unsigned Reg;
555 /// JTI - the JumpTableIndex for this jump table in the function.
556 unsigned JTI;
557 /// MBB - the MBB into which to emit the code for the indirect jump.
558 MachineBasicBlock *MBB;
559 /// Default - the MBB of the default bb, which is a successor of the range
560 /// check MBB. This is when updating PHI nodes in successors.
561 MachineBasicBlock *Default;
562};
563struct JumpTableHeader {
564 JumpTableHeader(uint64_t F, uint64_t L, Value* SV, MachineBasicBlock* H,
565 bool E = false):
566 First(F), Last(L), SValue(SV), HeaderBB(H), Emitted(E) {}
567 uint64_t First;
568 uint64_t Last;
569 Value *SValue;
570 MachineBasicBlock *HeaderBB;
571 bool Emitted;
572};
573typedef std::pair<JumpTableHeader, JumpTable> JumpTableBlock;
574
575struct BitTestCase {
576 BitTestCase(uint64_t M, MachineBasicBlock* T, MachineBasicBlock* Tr):
577 Mask(M), ThisBB(T), TargetBB(Tr) { }
578 uint64_t Mask;
579 MachineBasicBlock* ThisBB;
580 MachineBasicBlock* TargetBB;
581};
582
583typedef SmallVector<BitTestCase, 3> BitTestInfo;
584
585struct BitTestBlock {
586 BitTestBlock(uint64_t F, uint64_t R, Value* SV,
587 unsigned Rg, bool E,
588 MachineBasicBlock* P, MachineBasicBlock* D,
589 const BitTestInfo& C):
590 First(F), Range(R), SValue(SV), Reg(Rg), Emitted(E),
591 Parent(P), Default(D), Cases(C) { }
592 uint64_t First;
593 uint64_t Range;
594 Value *SValue;
595 unsigned Reg;
596 bool Emitted;
597 MachineBasicBlock *Parent;
598 MachineBasicBlock *Default;
599 BitTestInfo Cases;
600};
601
602} // end anonymous namespace
603
Chris Lattner1c08c712005-01-07 07:47:53 +0000604//===----------------------------------------------------------------------===//
605/// SelectionDAGLowering - This is the common target-independent lowering
606/// implementation that is parameterized by a TargetLowering object.
607/// Also, targets can overload any lowering method.
608///
609namespace llvm {
610class SelectionDAGLowering {
611 MachineBasicBlock *CurMBB;
612
Dan Gohman475871a2008-07-27 21:46:04 +0000613 DenseMap<const Value*, SDValue> NodeMap;
Chris Lattner1c08c712005-01-07 07:47:53 +0000614
Chris Lattnerd3948112005-01-17 22:19:26 +0000615 /// PendingLoads - Loads are not emitted to the program immediately. We bunch
616 /// them up and then emit token factor nodes when possible. This allows us to
617 /// get simple disambiguation between loads without worrying about alias
618 /// analysis.
Dan Gohman475871a2008-07-27 21:46:04 +0000619 SmallVector<SDValue, 8> PendingLoads;
Chris Lattnerd3948112005-01-17 22:19:26 +0000620
Dan Gohman86e1ebf2008-03-27 19:56:19 +0000621 /// PendingExports - CopyToReg nodes that copy values to virtual registers
622 /// for export to other blocks need to be emitted before any terminator
623 /// instruction, but they have no other ordering requirements. We bunch them
624 /// up and the emit a single tokenfactor for them just before terminator
625 /// instructions.
Dan Gohman7c3234c2008-08-27 23:52:12 +0000626 SmallVector<SDValue, 8> PendingExports;
Dan Gohman86e1ebf2008-03-27 19:56:19 +0000627
Anton Korobeynikov5502bf62007-04-04 21:14:49 +0000628 /// Case - A struct to record the Value for a switch case, and the
629 /// case's target basic block.
630 struct Case {
631 Constant* Low;
632 Constant* High;
633 MachineBasicBlock* BB;
634
635 Case() : Low(0), High(0), BB(0) { }
636 Case(Constant* low, Constant* high, MachineBasicBlock* bb) :
637 Low(low), High(high), BB(bb) { }
638 uint64_t size() const {
639 uint64_t rHigh = cast<ConstantInt>(High)->getSExtValue();
640 uint64_t rLow = cast<ConstantInt>(Low)->getSExtValue();
641 return (rHigh - rLow + 1ULL);
642 }
643 };
644
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000645 struct CaseBits {
646 uint64_t Mask;
647 MachineBasicBlock* BB;
648 unsigned Bits;
649
650 CaseBits(uint64_t mask, MachineBasicBlock* bb, unsigned bits):
651 Mask(mask), BB(bb), Bits(bits) { }
652 };
653
Anton Korobeynikov5502bf62007-04-04 21:14:49 +0000654 typedef std::vector<Case> CaseVector;
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000655 typedef std::vector<CaseBits> CaseBitsVector;
Anton Korobeynikov5502bf62007-04-04 21:14:49 +0000656 typedef CaseVector::iterator CaseItr;
657 typedef std::pair<CaseItr, CaseItr> CaseRange;
Nate Begemanf15485a2006-03-27 01:32:24 +0000658
659 /// CaseRec - A struct with ctor used in lowering switches to a binary tree
660 /// of conditional branches.
661 struct CaseRec {
662 CaseRec(MachineBasicBlock *bb, Constant *lt, Constant *ge, CaseRange r) :
663 CaseBB(bb), LT(lt), GE(ge), Range(r) {}
664
665 /// CaseBB - The MBB in which to emit the compare and branch
666 MachineBasicBlock *CaseBB;
667 /// LT, GE - If nonzero, we know the current case value must be less-than or
668 /// greater-than-or-equal-to these Constants.
669 Constant *LT;
670 Constant *GE;
671 /// Range - A pair of iterators representing the range of case values to be
672 /// processed at this point in the binary search tree.
673 CaseRange Range;
674 };
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +0000675
676 typedef std::vector<CaseRec> CaseRecVector;
Anton Korobeynikov5502bf62007-04-04 21:14:49 +0000677
678 /// The comparison function for sorting the switch case values in the vector.
679 /// WARNING: Case ranges should be disjoint!
Nate Begemanf15485a2006-03-27 01:32:24 +0000680 struct CaseCmp {
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000681 bool operator () (const Case& C1, const Case& C2) {
Anton Korobeynikov5502bf62007-04-04 21:14:49 +0000682 assert(isa<ConstantInt>(C1.Low) && isa<ConstantInt>(C2.High));
683 const ConstantInt* CI1 = cast<const ConstantInt>(C1.Low);
684 const ConstantInt* CI2 = cast<const ConstantInt>(C2.High);
685 return CI1->getValue().slt(CI2->getValue());
Nate Begemanf15485a2006-03-27 01:32:24 +0000686 }
687 };
Anton Korobeynikov5502bf62007-04-04 21:14:49 +0000688
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000689 struct CaseBitsCmp {
690 bool operator () (const CaseBits& C1, const CaseBits& C2) {
691 return C1.Bits > C2.Bits;
692 }
693 };
694
Anton Korobeynikov5502bf62007-04-04 21:14:49 +0000695 unsigned Clusterify(CaseVector& Cases, const SwitchInst &SI);
Nate Begemanf15485a2006-03-27 01:32:24 +0000696
Chris Lattner1c08c712005-01-07 07:47:53 +0000697public:
698 // TLI - This is information that describes the available target features we
699 // need for lowering. This indicates when operations are unavailable,
700 // implemented with a libcall, etc.
701 TargetLowering &TLI;
702 SelectionDAG &DAG;
Owen Andersona69571c2006-05-03 01:29:57 +0000703 const TargetData *TD;
Dan Gohman7c3234c2008-08-27 23:52:12 +0000704 AliasAnalysis *AA;
Chris Lattner1c08c712005-01-07 07:47:53 +0000705
Nate Begemanf15485a2006-03-27 01:32:24 +0000706 /// SwitchCases - Vector of CaseBlock structures used to communicate
707 /// SwitchInst code generation information.
Dan Gohman7c3234c2008-08-27 23:52:12 +0000708 std::vector<CaseBlock> SwitchCases;
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +0000709 /// JTCases - Vector of JumpTable structures used to communicate
710 /// SwitchInst code generation information.
Dan Gohman7c3234c2008-08-27 23:52:12 +0000711 std::vector<JumpTableBlock> JTCases;
712 /// BitTestCases - Vector of BitTestBlock structures used to communicate
713 /// SwitchInst code generation information.
714 std::vector<BitTestBlock> BitTestCases;
Nate Begemanf15485a2006-03-27 01:32:24 +0000715
Dan Gohman7c3234c2008-08-27 23:52:12 +0000716 std::vector<std::pair<MachineInstr*, unsigned> > PHINodesToUpdate;
717
718 // Emit PHI-node-operand constants only once even if used by multiple
719 // PHI nodes.
720 DenseMap<Constant*, unsigned> ConstantsOut;
721
Chris Lattner1c08c712005-01-07 07:47:53 +0000722 /// FuncInfo - Information about the function as a whole.
723 ///
724 FunctionLoweringInfo &FuncInfo;
Gordon Henriksence224772008-01-07 01:30:38 +0000725
Gordon Henriksen5eca0752008-08-17 18:44:35 +0000726 /// GFI - Garbage collection metadata for the function.
727 GCFunctionInfo *GFI;
Chris Lattner1c08c712005-01-07 07:47:53 +0000728
729 SelectionDAGLowering(SelectionDAG &dag, TargetLowering &tli,
Dan Gohman7c3234c2008-08-27 23:52:12 +0000730 FunctionLoweringInfo &funcinfo)
731 : TLI(tli), DAG(dag), FuncInfo(funcinfo) {
732 }
733
734 void init(GCFunctionInfo *gfi, AliasAnalysis &aa) {
735 AA = &aa;
736 GFI = gfi;
737 TD = DAG.getTarget().getTargetData();
738 }
739
740 /// clear - Clear out the curret SelectionDAG and the associated
741 /// state and prepare this SelectionDAGLowering object to be used
742 /// for a new block. This doesn't clear out information about
743 /// additional blocks that are needed to complete switch lowering
744 /// or PHI node updating; that information is cleared out as it is
745 /// consumed.
746 void clear() {
747 NodeMap.clear();
748 PendingLoads.clear();
749 PendingExports.clear();
750 DAG.clear();
Chris Lattner1c08c712005-01-07 07:47:53 +0000751 }
752
Dan Gohman86e1ebf2008-03-27 19:56:19 +0000753 /// getRoot - Return the current virtual root of the Selection DAG,
754 /// flushing any PendingLoad items. This must be done before emitting
755 /// a store or any other node that may need to be ordered after any
756 /// prior load instructions.
Chris Lattnera651cf62005-01-17 19:43:36 +0000757 ///
Dan Gohman475871a2008-07-27 21:46:04 +0000758 SDValue getRoot() {
Chris Lattnerd3948112005-01-17 22:19:26 +0000759 if (PendingLoads.empty())
760 return DAG.getRoot();
Misha Brukmanedf128a2005-04-21 22:36:52 +0000761
Chris Lattnerd3948112005-01-17 22:19:26 +0000762 if (PendingLoads.size() == 1) {
Dan Gohman475871a2008-07-27 21:46:04 +0000763 SDValue Root = PendingLoads[0];
Chris Lattnerd3948112005-01-17 22:19:26 +0000764 DAG.setRoot(Root);
765 PendingLoads.clear();
766 return Root;
767 }
768
769 // Otherwise, we have to make a token factor node.
Dan Gohman475871a2008-07-27 21:46:04 +0000770 SDValue Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
Chris Lattnerbd564bf2006-08-08 02:23:42 +0000771 &PendingLoads[0], PendingLoads.size());
Chris Lattnerd3948112005-01-17 22:19:26 +0000772 PendingLoads.clear();
773 DAG.setRoot(Root);
774 return Root;
Chris Lattnera651cf62005-01-17 19:43:36 +0000775 }
776
Dan Gohman86e1ebf2008-03-27 19:56:19 +0000777 /// getControlRoot - Similar to getRoot, but instead of flushing all the
778 /// PendingLoad items, flush all the PendingExports items. It is necessary
779 /// to do this before emitting a terminator instruction.
780 ///
Dan Gohman475871a2008-07-27 21:46:04 +0000781 SDValue getControlRoot() {
782 SDValue Root = DAG.getRoot();
Dan Gohman86e1ebf2008-03-27 19:56:19 +0000783
784 if (PendingExports.empty())
785 return Root;
786
787 // Turn all of the CopyToReg chains into one factored node.
788 if (Root.getOpcode() != ISD::EntryToken) {
789 unsigned i = 0, e = PendingExports.size();
790 for (; i != e; ++i) {
791 assert(PendingExports[i].Val->getNumOperands() > 1);
792 if (PendingExports[i].Val->getOperand(0) == Root)
793 break; // Don't add the root if we already indirectly depend on it.
794 }
795
796 if (i == e)
797 PendingExports.push_back(Root);
798 }
799
800 Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
801 &PendingExports[0],
802 PendingExports.size());
803 PendingExports.clear();
804 DAG.setRoot(Root);
805 return Root;
806 }
807
808 void CopyValueToVirtualRegister(Value *V, unsigned Reg);
Chris Lattner571e4342006-10-27 21:36:01 +0000809
Chris Lattner1c08c712005-01-07 07:47:53 +0000810 void visit(Instruction &I) { visit(I.getOpcode(), I); }
811
812 void visit(unsigned Opcode, User &I) {
Chris Lattner1e7aa5c2006-11-10 04:41:34 +0000813 // Note: this doesn't use InstVisitor, because it has to work with
814 // ConstantExpr's in addition to instructions.
Chris Lattner1c08c712005-01-07 07:47:53 +0000815 switch (Opcode) {
816 default: assert(0 && "Unknown instruction type encountered!");
817 abort();
818 // Build the switch statement using the Instruction.def file.
819#define HANDLE_INST(NUM, OPCODE, CLASS) \
820 case Instruction::OPCODE:return visit##OPCODE((CLASS&)I);
821#include "llvm/Instruction.def"
822 }
823 }
824
825 void setCurrentBasicBlock(MachineBasicBlock *MBB) { CurMBB = MBB; }
826
Dan Gohman475871a2008-07-27 21:46:04 +0000827 SDValue getValue(const Value *V);
Chris Lattner1c08c712005-01-07 07:47:53 +0000828
Dan Gohman475871a2008-07-27 21:46:04 +0000829 void setValue(const Value *V, SDValue NewN) {
830 SDValue &N = NodeMap[V];
Chris Lattner1c08c712005-01-07 07:47:53 +0000831 assert(N.Val == 0 && "Already set a value for this node!");
Chris Lattner0da331f2007-02-04 01:31:47 +0000832 N = NewN;
Chris Lattner1c08c712005-01-07 07:47:53 +0000833 }
Chris Lattner4e4b5762006-02-01 18:59:47 +0000834
Evan Cheng5c807602008-02-26 02:33:44 +0000835 void GetRegistersForValue(SDISelAsmOperandInfo &OpInfo, bool HasEarlyClobber,
Chris Lattnere7cf56a2007-04-30 21:11:17 +0000836 std::set<unsigned> &OutputRegs,
837 std::set<unsigned> &InputRegs);
Nate Begemanf15485a2006-03-27 01:32:24 +0000838
Chris Lattner571e4342006-10-27 21:36:01 +0000839 void FindMergedConditions(Value *Cond, MachineBasicBlock *TBB,
840 MachineBasicBlock *FBB, MachineBasicBlock *CurBB,
841 unsigned Opc);
Chris Lattner8c494ab2006-10-27 23:50:33 +0000842 bool isExportableFromCurrentBlock(Value *V, const BasicBlock *FromBB);
Chris Lattner571e4342006-10-27 21:36:01 +0000843 void ExportFromCurrentBlock(Value *V);
Dan Gohman475871a2008-07-27 21:46:04 +0000844 void LowerCallTo(CallSite CS, SDValue Callee, bool IsTailCall,
Anton Korobeynikov070280e2007-05-23 11:08:31 +0000845 MachineBasicBlock *LandingPad = NULL);
Duncan Sandsdc024672007-11-27 13:23:08 +0000846
Chris Lattner1c08c712005-01-07 07:47:53 +0000847 // Terminator instructions.
848 void visitRet(ReturnInst &I);
849 void visitBr(BranchInst &I);
Nate Begemanf15485a2006-03-27 01:32:24 +0000850 void visitSwitch(SwitchInst &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000851 void visitUnreachable(UnreachableInst &I) { /* noop */ }
852
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +0000853 // Helpers for visitSwitch
Anton Korobeynikovdd433212007-03-27 12:05:48 +0000854 bool handleSmallSwitchRange(CaseRec& CR,
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +0000855 CaseRecVector& WorkList,
856 Value* SV,
857 MachineBasicBlock* Default);
Anton Korobeynikovdd433212007-03-27 12:05:48 +0000858 bool handleJTSwitchCase(CaseRec& CR,
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +0000859 CaseRecVector& WorkList,
860 Value* SV,
861 MachineBasicBlock* Default);
Anton Korobeynikovdd433212007-03-27 12:05:48 +0000862 bool handleBTSplitSwitchCase(CaseRec& CR,
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +0000863 CaseRecVector& WorkList,
864 Value* SV,
865 MachineBasicBlock* Default);
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000866 bool handleBitTestsSwitchCase(CaseRec& CR,
867 CaseRecVector& WorkList,
868 Value* SV,
869 MachineBasicBlock* Default);
Dan Gohman7c3234c2008-08-27 23:52:12 +0000870 void visitSwitchCase(CaseBlock &CB);
871 void visitBitTestHeader(BitTestBlock &B);
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000872 void visitBitTestCase(MachineBasicBlock* NextMBB,
873 unsigned Reg,
Dan Gohman7c3234c2008-08-27 23:52:12 +0000874 BitTestCase &B);
875 void visitJumpTable(JumpTable &JT);
876 void visitJumpTableHeader(JumpTable &JT, JumpTableHeader &JTH);
Nate Begemanf15485a2006-03-27 01:32:24 +0000877
Chris Lattner1c08c712005-01-07 07:47:53 +0000878 // These all get lowered before this pass.
Jim Laskeyb180aa12007-02-21 22:53:45 +0000879 void visitInvoke(InvokeInst &I);
880 void visitUnwind(UnwindInst &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000881
Dan Gohman7f321562007-06-25 16:23:39 +0000882 void visitBinary(User &I, unsigned OpCode);
Nate Begemane21ea612005-11-18 07:42:56 +0000883 void visitShift(User &I, unsigned Opcode);
Nate Begeman5fbb5d22005-11-19 00:36:38 +0000884 void visitAdd(User &I) {
Dan Gohman7f321562007-06-25 16:23:39 +0000885 if (I.getType()->isFPOrFPVector())
886 visitBinary(I, ISD::FADD);
Reid Spencer1628cec2006-10-26 06:15:43 +0000887 else
Dan Gohman7f321562007-06-25 16:23:39 +0000888 visitBinary(I, ISD::ADD);
Chris Lattner01b3d732005-09-28 22:28:18 +0000889 }
Chris Lattnerb9fccc42005-04-02 05:04:50 +0000890 void visitSub(User &I);
Reid Spencer1628cec2006-10-26 06:15:43 +0000891 void visitMul(User &I) {
Dan Gohman7f321562007-06-25 16:23:39 +0000892 if (I.getType()->isFPOrFPVector())
893 visitBinary(I, ISD::FMUL);
Reid Spencer1628cec2006-10-26 06:15:43 +0000894 else
Dan Gohman7f321562007-06-25 16:23:39 +0000895 visitBinary(I, ISD::MUL);
Chris Lattner01b3d732005-09-28 22:28:18 +0000896 }
Dan Gohman7f321562007-06-25 16:23:39 +0000897 void visitURem(User &I) { visitBinary(I, ISD::UREM); }
898 void visitSRem(User &I) { visitBinary(I, ISD::SREM); }
899 void visitFRem(User &I) { visitBinary(I, ISD::FREM); }
900 void visitUDiv(User &I) { visitBinary(I, ISD::UDIV); }
901 void visitSDiv(User &I) { visitBinary(I, ISD::SDIV); }
902 void visitFDiv(User &I) { visitBinary(I, ISD::FDIV); }
903 void visitAnd (User &I) { visitBinary(I, ISD::AND); }
904 void visitOr (User &I) { visitBinary(I, ISD::OR); }
905 void visitXor (User &I) { visitBinary(I, ISD::XOR); }
Reid Spencer24d6da52007-01-21 00:29:26 +0000906 void visitShl (User &I) { visitShift(I, ISD::SHL); }
Reid Spencer3822ff52006-11-08 06:47:33 +0000907 void visitLShr(User &I) { visitShift(I, ISD::SRL); }
908 void visitAShr(User &I) { visitShift(I, ISD::SRA); }
Reid Spencer45fb3f32006-11-20 01:22:35 +0000909 void visitICmp(User &I);
910 void visitFCmp(User &I);
Nate Begemanb43e9c12008-05-12 19:40:03 +0000911 void visitVICmp(User &I);
912 void visitVFCmp(User &I);
Reid Spencer3da59db2006-11-27 01:05:10 +0000913 // Visit the conversion instructions
914 void visitTrunc(User &I);
915 void visitZExt(User &I);
916 void visitSExt(User &I);
917 void visitFPTrunc(User &I);
918 void visitFPExt(User &I);
919 void visitFPToUI(User &I);
920 void visitFPToSI(User &I);
921 void visitUIToFP(User &I);
922 void visitSIToFP(User &I);
923 void visitPtrToInt(User &I);
924 void visitIntToPtr(User &I);
925 void visitBitCast(User &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000926
Chris Lattner2bbd8102006-03-29 00:11:43 +0000927 void visitExtractElement(User &I);
928 void visitInsertElement(User &I);
Chris Lattner3e104b12006-04-08 04:15:24 +0000929 void visitShuffleVector(User &I);
Chris Lattnerc7029802006-03-18 01:44:44 +0000930
Dan Gohman1d685a42008-06-07 02:02:36 +0000931 void visitExtractValue(ExtractValueInst &I);
932 void visitInsertValue(InsertValueInst &I);
Dan Gohman041e2eb2008-05-15 19:50:34 +0000933
Chris Lattner1c08c712005-01-07 07:47:53 +0000934 void visitGetElementPtr(User &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000935 void visitSelect(User &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000936
937 void visitMalloc(MallocInst &I);
938 void visitFree(FreeInst &I);
939 void visitAlloca(AllocaInst &I);
940 void visitLoad(LoadInst &I);
941 void visitStore(StoreInst &I);
942 void visitPHI(PHINode &I) { } // PHI nodes are handled specially.
943 void visitCall(CallInst &I);
Duncan Sandsfd7b3262007-12-17 18:08:19 +0000944 void visitInlineAsm(CallSite CS);
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +0000945 const char *visitIntrinsicCall(CallInst &I, unsigned Intrinsic);
Chris Lattner0eade312006-03-24 02:22:33 +0000946 void visitTargetIntrinsic(CallInst &I, unsigned Intrinsic);
Chris Lattner1c08c712005-01-07 07:47:53 +0000947
Chris Lattner1c08c712005-01-07 07:47:53 +0000948 void visitVAStart(CallInst &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000949 void visitVAArg(VAArgInst &I);
950 void visitVAEnd(CallInst &I);
951 void visitVACopy(CallInst &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000952
Chris Lattner1c08c712005-01-07 07:47:53 +0000953 void visitUserOp1(Instruction &I) {
954 assert(0 && "UserOp1 should not exist at instruction selection time!");
955 abort();
956 }
957 void visitUserOp2(Instruction &I) {
958 assert(0 && "UserOp2 should not exist at instruction selection time!");
959 abort();
960 }
Mon P Wang63307c32008-05-05 19:05:59 +0000961
962private:
963 inline const char *implVisitBinaryAtomic(CallInst& I, ISD::NodeType Op);
964
Chris Lattner1c08c712005-01-07 07:47:53 +0000965};
966} // end namespace llvm
967
Dan Gohman6183f782007-07-05 20:12:34 +0000968
Duncan Sandsb988bac2008-02-11 20:58:28 +0000969/// getCopyFromParts - Create a value that contains the specified legal parts
970/// combined into the value they represent. If the parts combine to a type
971/// larger then ValueVT then AssertOp can be used to specify whether the extra
972/// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
Chris Lattner4468c1f2008-03-09 09:38:46 +0000973/// (ISD::AssertSext).
Dan Gohman475871a2008-07-27 21:46:04 +0000974static SDValue getCopyFromParts(SelectionDAG &DAG,
975 const SDValue *Parts,
Dan Gohman6183f782007-07-05 20:12:34 +0000976 unsigned NumParts,
Duncan Sands83ec4b62008-06-06 12:08:01 +0000977 MVT PartVT,
978 MVT ValueVT,
Chris Lattner4468c1f2008-03-09 09:38:46 +0000979 ISD::NodeType AssertOp = ISD::DELETED_NODE) {
Duncan Sands014e04a2008-02-12 20:46:31 +0000980 assert(NumParts > 0 && "No parts to assemble!");
981 TargetLowering &TLI = DAG.getTargetLoweringInfo();
Dan Gohman475871a2008-07-27 21:46:04 +0000982 SDValue Val = Parts[0];
Dan Gohman6183f782007-07-05 20:12:34 +0000983
Duncan Sands014e04a2008-02-12 20:46:31 +0000984 if (NumParts > 1) {
985 // Assemble the value from multiple parts.
Duncan Sands83ec4b62008-06-06 12:08:01 +0000986 if (!ValueVT.isVector()) {
987 unsigned PartBits = PartVT.getSizeInBits();
988 unsigned ValueBits = ValueVT.getSizeInBits();
Dan Gohman6183f782007-07-05 20:12:34 +0000989
Duncan Sands014e04a2008-02-12 20:46:31 +0000990 // Assemble the power of 2 part.
991 unsigned RoundParts = NumParts & (NumParts - 1) ?
992 1 << Log2_32(NumParts) : NumParts;
993 unsigned RoundBits = PartBits * RoundParts;
Duncan Sands83ec4b62008-06-06 12:08:01 +0000994 MVT RoundVT = RoundBits == ValueBits ?
995 ValueVT : MVT::getIntegerVT(RoundBits);
Dan Gohman475871a2008-07-27 21:46:04 +0000996 SDValue Lo, Hi;
Duncan Sands014e04a2008-02-12 20:46:31 +0000997
998 if (RoundParts > 2) {
Duncan Sands83ec4b62008-06-06 12:08:01 +0000999 MVT HalfVT = MVT::getIntegerVT(RoundBits/2);
Duncan Sands014e04a2008-02-12 20:46:31 +00001000 Lo = getCopyFromParts(DAG, Parts, RoundParts/2, PartVT, HalfVT);
1001 Hi = getCopyFromParts(DAG, Parts+RoundParts/2, RoundParts/2,
1002 PartVT, HalfVT);
Dan Gohman6183f782007-07-05 20:12:34 +00001003 } else {
Duncan Sands014e04a2008-02-12 20:46:31 +00001004 Lo = Parts[0];
1005 Hi = Parts[1];
Dan Gohman6183f782007-07-05 20:12:34 +00001006 }
Duncan Sands014e04a2008-02-12 20:46:31 +00001007 if (TLI.isBigEndian())
1008 std::swap(Lo, Hi);
1009 Val = DAG.getNode(ISD::BUILD_PAIR, RoundVT, Lo, Hi);
1010
1011 if (RoundParts < NumParts) {
1012 // Assemble the trailing non-power-of-2 part.
1013 unsigned OddParts = NumParts - RoundParts;
Duncan Sands83ec4b62008-06-06 12:08:01 +00001014 MVT OddVT = MVT::getIntegerVT(OddParts * PartBits);
Duncan Sands014e04a2008-02-12 20:46:31 +00001015 Hi = getCopyFromParts(DAG, Parts+RoundParts, OddParts, PartVT, OddVT);
1016
1017 // Combine the round and odd parts.
1018 Lo = Val;
1019 if (TLI.isBigEndian())
1020 std::swap(Lo, Hi);
Duncan Sands83ec4b62008-06-06 12:08:01 +00001021 MVT TotalVT = MVT::getIntegerVT(NumParts * PartBits);
Duncan Sands014e04a2008-02-12 20:46:31 +00001022 Hi = DAG.getNode(ISD::ANY_EXTEND, TotalVT, Hi);
1023 Hi = DAG.getNode(ISD::SHL, TotalVT, Hi,
Duncan Sands83ec4b62008-06-06 12:08:01 +00001024 DAG.getConstant(Lo.getValueType().getSizeInBits(),
Duncan Sands014e04a2008-02-12 20:46:31 +00001025 TLI.getShiftAmountTy()));
1026 Lo = DAG.getNode(ISD::ZERO_EXTEND, TotalVT, Lo);
1027 Val = DAG.getNode(ISD::OR, TotalVT, Lo, Hi);
1028 }
1029 } else {
1030 // Handle a multi-element vector.
Duncan Sands83ec4b62008-06-06 12:08:01 +00001031 MVT IntermediateVT, RegisterVT;
Duncan Sands014e04a2008-02-12 20:46:31 +00001032 unsigned NumIntermediates;
1033 unsigned NumRegs =
1034 TLI.getVectorTypeBreakdown(ValueVT, IntermediateVT, NumIntermediates,
1035 RegisterVT);
Duncan Sands014e04a2008-02-12 20:46:31 +00001036 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
Evan Cheng35213342008-05-14 20:29:30 +00001037 NumParts = NumRegs; // Silence a compiler warning.
Duncan Sands014e04a2008-02-12 20:46:31 +00001038 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
1039 assert(RegisterVT == Parts[0].getValueType() &&
1040 "Part type doesn't match part!");
1041
1042 // Assemble the parts into intermediate operands.
Dan Gohman475871a2008-07-27 21:46:04 +00001043 SmallVector<SDValue, 8> Ops(NumIntermediates);
Duncan Sands014e04a2008-02-12 20:46:31 +00001044 if (NumIntermediates == NumParts) {
1045 // If the register was not expanded, truncate or copy the value,
1046 // as appropriate.
1047 for (unsigned i = 0; i != NumParts; ++i)
1048 Ops[i] = getCopyFromParts(DAG, &Parts[i], 1,
1049 PartVT, IntermediateVT);
1050 } else if (NumParts > 0) {
1051 // If the intermediate type was expanded, build the intermediate operands
1052 // from the parts.
1053 assert(NumParts % NumIntermediates == 0 &&
1054 "Must expand into a divisible number of parts!");
1055 unsigned Factor = NumParts / NumIntermediates;
1056 for (unsigned i = 0; i != NumIntermediates; ++i)
1057 Ops[i] = getCopyFromParts(DAG, &Parts[i * Factor], Factor,
1058 PartVT, IntermediateVT);
1059 }
1060
1061 // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the intermediate
1062 // operands.
Duncan Sands83ec4b62008-06-06 12:08:01 +00001063 Val = DAG.getNode(IntermediateVT.isVector() ?
Duncan Sands014e04a2008-02-12 20:46:31 +00001064 ISD::CONCAT_VECTORS : ISD::BUILD_VECTOR,
1065 ValueVT, &Ops[0], NumIntermediates);
Dan Gohman6183f782007-07-05 20:12:34 +00001066 }
Dan Gohman6183f782007-07-05 20:12:34 +00001067 }
1068
Duncan Sands014e04a2008-02-12 20:46:31 +00001069 // There is now one part, held in Val. Correct it to match ValueVT.
1070 PartVT = Val.getValueType();
Dan Gohman6183f782007-07-05 20:12:34 +00001071
Duncan Sands014e04a2008-02-12 20:46:31 +00001072 if (PartVT == ValueVT)
1073 return Val;
Dan Gohman6183f782007-07-05 20:12:34 +00001074
Duncan Sands83ec4b62008-06-06 12:08:01 +00001075 if (PartVT.isVector()) {
1076 assert(ValueVT.isVector() && "Unknown vector conversion!");
Duncan Sands014e04a2008-02-12 20:46:31 +00001077 return DAG.getNode(ISD::BIT_CONVERT, ValueVT, Val);
Dan Gohman6183f782007-07-05 20:12:34 +00001078 }
Duncan Sands014e04a2008-02-12 20:46:31 +00001079
Duncan Sands83ec4b62008-06-06 12:08:01 +00001080 if (ValueVT.isVector()) {
1081 assert(ValueVT.getVectorElementType() == PartVT &&
1082 ValueVT.getVectorNumElements() == 1 &&
Duncan Sands014e04a2008-02-12 20:46:31 +00001083 "Only trivial scalar-to-vector conversions should get here!");
1084 return DAG.getNode(ISD::BUILD_VECTOR, ValueVT, Val);
1085 }
1086
Duncan Sands83ec4b62008-06-06 12:08:01 +00001087 if (PartVT.isInteger() &&
1088 ValueVT.isInteger()) {
Duncan Sands8e4eb092008-06-08 20:54:56 +00001089 if (ValueVT.bitsLT(PartVT)) {
Duncan Sands014e04a2008-02-12 20:46:31 +00001090 // For a truncate, see if we have any information to
1091 // indicate whether the truncated bits will always be
1092 // zero or sign-extension.
1093 if (AssertOp != ISD::DELETED_NODE)
1094 Val = DAG.getNode(AssertOp, PartVT, Val,
1095 DAG.getValueType(ValueVT));
1096 return DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
1097 } else {
1098 return DAG.getNode(ISD::ANY_EXTEND, ValueVT, Val);
1099 }
1100 }
1101
Duncan Sands83ec4b62008-06-06 12:08:01 +00001102 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
Duncan Sands8e4eb092008-06-08 20:54:56 +00001103 if (ValueVT.bitsLT(Val.getValueType()))
Chris Lattner4468c1f2008-03-09 09:38:46 +00001104 // FP_ROUND's are always exact here.
Chris Lattnerd43d85c2008-03-09 07:47:22 +00001105 return DAG.getNode(ISD::FP_ROUND, ValueVT, Val,
Chris Lattner4468c1f2008-03-09 09:38:46 +00001106 DAG.getIntPtrConstant(1));
Chris Lattnerd43d85c2008-03-09 07:47:22 +00001107 return DAG.getNode(ISD::FP_EXTEND, ValueVT, Val);
1108 }
Duncan Sands014e04a2008-02-12 20:46:31 +00001109
Duncan Sands83ec4b62008-06-06 12:08:01 +00001110 if (PartVT.getSizeInBits() == ValueVT.getSizeInBits())
Duncan Sands014e04a2008-02-12 20:46:31 +00001111 return DAG.getNode(ISD::BIT_CONVERT, ValueVT, Val);
1112
1113 assert(0 && "Unknown mismatch!");
Dan Gohman475871a2008-07-27 21:46:04 +00001114 return SDValue();
Dan Gohman6183f782007-07-05 20:12:34 +00001115}
1116
Duncan Sandsb988bac2008-02-11 20:58:28 +00001117/// getCopyToParts - Create a series of nodes that contain the specified value
1118/// split into legal parts. If the parts contain more bits than Val, then, for
1119/// integers, ExtendKind can be used to specify how to generate the extra bits.
Dan Gohman6183f782007-07-05 20:12:34 +00001120static void getCopyToParts(SelectionDAG &DAG,
Dan Gohman475871a2008-07-27 21:46:04 +00001121 SDValue Val,
1122 SDValue *Parts,
Dan Gohman6183f782007-07-05 20:12:34 +00001123 unsigned NumParts,
Duncan Sands83ec4b62008-06-06 12:08:01 +00001124 MVT PartVT,
Duncan Sandsb988bac2008-02-11 20:58:28 +00001125 ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
Dan Gohman25ac7e82007-08-10 14:59:38 +00001126 TargetLowering &TLI = DAG.getTargetLoweringInfo();
Duncan Sands83ec4b62008-06-06 12:08:01 +00001127 MVT PtrVT = TLI.getPointerTy();
1128 MVT ValueVT = Val.getValueType();
1129 unsigned PartBits = PartVT.getSizeInBits();
Duncan Sands014e04a2008-02-12 20:46:31 +00001130 assert(TLI.isTypeLegal(PartVT) && "Copying to an illegal type!");
Dan Gohman6183f782007-07-05 20:12:34 +00001131
Duncan Sands014e04a2008-02-12 20:46:31 +00001132 if (!NumParts)
1133 return;
1134
Duncan Sands83ec4b62008-06-06 12:08:01 +00001135 if (!ValueVT.isVector()) {
Duncan Sands014e04a2008-02-12 20:46:31 +00001136 if (PartVT == ValueVT) {
1137 assert(NumParts == 1 && "No-op copy with multiple parts!");
1138 Parts[0] = Val;
Dan Gohman6183f782007-07-05 20:12:34 +00001139 return;
1140 }
1141
Duncan Sands83ec4b62008-06-06 12:08:01 +00001142 if (NumParts * PartBits > ValueVT.getSizeInBits()) {
Duncan Sands014e04a2008-02-12 20:46:31 +00001143 // If the parts cover more bits than the value has, promote the value.
Duncan Sands83ec4b62008-06-06 12:08:01 +00001144 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
Duncan Sands014e04a2008-02-12 20:46:31 +00001145 assert(NumParts == 1 && "Do not know what to promote to!");
Dan Gohman6183f782007-07-05 20:12:34 +00001146 Val = DAG.getNode(ISD::FP_EXTEND, PartVT, Val);
Duncan Sands83ec4b62008-06-06 12:08:01 +00001147 } else if (PartVT.isInteger() && ValueVT.isInteger()) {
1148 ValueVT = MVT::getIntegerVT(NumParts * PartBits);
Duncan Sands014e04a2008-02-12 20:46:31 +00001149 Val = DAG.getNode(ExtendKind, ValueVT, Val);
1150 } else {
1151 assert(0 && "Unknown mismatch!");
1152 }
Duncan Sands83ec4b62008-06-06 12:08:01 +00001153 } else if (PartBits == ValueVT.getSizeInBits()) {
Duncan Sands014e04a2008-02-12 20:46:31 +00001154 // Different types of the same size.
1155 assert(NumParts == 1 && PartVT != ValueVT);
1156 Val = DAG.getNode(ISD::BIT_CONVERT, PartVT, Val);
Duncan Sands83ec4b62008-06-06 12:08:01 +00001157 } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
Duncan Sands014e04a2008-02-12 20:46:31 +00001158 // If the parts cover less bits than value has, truncate the value.
Duncan Sands83ec4b62008-06-06 12:08:01 +00001159 if (PartVT.isInteger() && ValueVT.isInteger()) {
1160 ValueVT = MVT::getIntegerVT(NumParts * PartBits);
Duncan Sands014e04a2008-02-12 20:46:31 +00001161 Val = DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
Dan Gohman6183f782007-07-05 20:12:34 +00001162 } else {
1163 assert(0 && "Unknown mismatch!");
1164 }
1165 }
Duncan Sands014e04a2008-02-12 20:46:31 +00001166
1167 // The value may have changed - recompute ValueVT.
1168 ValueVT = Val.getValueType();
Duncan Sands83ec4b62008-06-06 12:08:01 +00001169 assert(NumParts * PartBits == ValueVT.getSizeInBits() &&
Duncan Sands014e04a2008-02-12 20:46:31 +00001170 "Failed to tile the value with PartVT!");
1171
1172 if (NumParts == 1) {
1173 assert(PartVT == ValueVT && "Type conversion failed!");
1174 Parts[0] = Val;
1175 return;
1176 }
1177
1178 // Expand the value into multiple parts.
1179 if (NumParts & (NumParts - 1)) {
1180 // The number of parts is not a power of 2. Split off and copy the tail.
Duncan Sands83ec4b62008-06-06 12:08:01 +00001181 assert(PartVT.isInteger() && ValueVT.isInteger() &&
Duncan Sands014e04a2008-02-12 20:46:31 +00001182 "Do not know what to expand to!");
1183 unsigned RoundParts = 1 << Log2_32(NumParts);
1184 unsigned RoundBits = RoundParts * PartBits;
1185 unsigned OddParts = NumParts - RoundParts;
Dan Gohman475871a2008-07-27 21:46:04 +00001186 SDValue OddVal = DAG.getNode(ISD::SRL, ValueVT, Val,
Duncan Sands014e04a2008-02-12 20:46:31 +00001187 DAG.getConstant(RoundBits,
1188 TLI.getShiftAmountTy()));
1189 getCopyToParts(DAG, OddVal, Parts + RoundParts, OddParts, PartVT);
1190 if (TLI.isBigEndian())
1191 // The odd parts were reversed by getCopyToParts - unreverse them.
1192 std::reverse(Parts + RoundParts, Parts + NumParts);
1193 NumParts = RoundParts;
Duncan Sands83ec4b62008-06-06 12:08:01 +00001194 ValueVT = MVT::getIntegerVT(NumParts * PartBits);
Duncan Sands014e04a2008-02-12 20:46:31 +00001195 Val = DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
1196 }
1197
1198 // The number of parts is a power of 2. Repeatedly bisect the value using
1199 // EXTRACT_ELEMENT.
Duncan Sands25eb0432008-03-12 20:30:08 +00001200 Parts[0] = DAG.getNode(ISD::BIT_CONVERT,
Duncan Sands83ec4b62008-06-06 12:08:01 +00001201 MVT::getIntegerVT(ValueVT.getSizeInBits()),
Duncan Sands25eb0432008-03-12 20:30:08 +00001202 Val);
Duncan Sands014e04a2008-02-12 20:46:31 +00001203 for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
1204 for (unsigned i = 0; i < NumParts; i += StepSize) {
1205 unsigned ThisBits = StepSize * PartBits / 2;
Duncan Sands83ec4b62008-06-06 12:08:01 +00001206 MVT ThisVT = MVT::getIntegerVT (ThisBits);
Dan Gohman475871a2008-07-27 21:46:04 +00001207 SDValue &Part0 = Parts[i];
1208 SDValue &Part1 = Parts[i+StepSize/2];
Duncan Sands014e04a2008-02-12 20:46:31 +00001209
Duncan Sands25eb0432008-03-12 20:30:08 +00001210 Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, ThisVT, Part0,
1211 DAG.getConstant(1, PtrVT));
1212 Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, ThisVT, Part0,
1213 DAG.getConstant(0, PtrVT));
1214
1215 if (ThisBits == PartBits && ThisVT != PartVT) {
1216 Part0 = DAG.getNode(ISD::BIT_CONVERT, PartVT, Part0);
1217 Part1 = DAG.getNode(ISD::BIT_CONVERT, PartVT, Part1);
1218 }
Duncan Sands014e04a2008-02-12 20:46:31 +00001219 }
1220 }
1221
1222 if (TLI.isBigEndian())
1223 std::reverse(Parts, Parts + NumParts);
1224
1225 return;
1226 }
1227
1228 // Vector ValueVT.
1229 if (NumParts == 1) {
1230 if (PartVT != ValueVT) {
Duncan Sands83ec4b62008-06-06 12:08:01 +00001231 if (PartVT.isVector()) {
Duncan Sands014e04a2008-02-12 20:46:31 +00001232 Val = DAG.getNode(ISD::BIT_CONVERT, PartVT, Val);
1233 } else {
Duncan Sands83ec4b62008-06-06 12:08:01 +00001234 assert(ValueVT.getVectorElementType() == PartVT &&
1235 ValueVT.getVectorNumElements() == 1 &&
Duncan Sands014e04a2008-02-12 20:46:31 +00001236 "Only trivial vector-to-scalar conversions should get here!");
1237 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, PartVT, Val,
1238 DAG.getConstant(0, PtrVT));
1239 }
1240 }
1241
Dan Gohman6183f782007-07-05 20:12:34 +00001242 Parts[0] = Val;
1243 return;
1244 }
1245
1246 // Handle a multi-element vector.
Duncan Sands83ec4b62008-06-06 12:08:01 +00001247 MVT IntermediateVT, RegisterVT;
Dan Gohman6183f782007-07-05 20:12:34 +00001248 unsigned NumIntermediates;
1249 unsigned NumRegs =
1250 DAG.getTargetLoweringInfo()
1251 .getVectorTypeBreakdown(ValueVT, IntermediateVT, NumIntermediates,
1252 RegisterVT);
Duncan Sands83ec4b62008-06-06 12:08:01 +00001253 unsigned NumElements = ValueVT.getVectorNumElements();
Dan Gohman6183f782007-07-05 20:12:34 +00001254
1255 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
Evan Cheng35213342008-05-14 20:29:30 +00001256 NumParts = NumRegs; // Silence a compiler warning.
Dan Gohman6183f782007-07-05 20:12:34 +00001257 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
1258
1259 // Split the vector into intermediate operands.
Dan Gohman475871a2008-07-27 21:46:04 +00001260 SmallVector<SDValue, 8> Ops(NumIntermediates);
Dan Gohman6183f782007-07-05 20:12:34 +00001261 for (unsigned i = 0; i != NumIntermediates; ++i)
Duncan Sands83ec4b62008-06-06 12:08:01 +00001262 if (IntermediateVT.isVector())
Dan Gohman6183f782007-07-05 20:12:34 +00001263 Ops[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR,
1264 IntermediateVT, Val,
1265 DAG.getConstant(i * (NumElements / NumIntermediates),
Dan Gohman25ac7e82007-08-10 14:59:38 +00001266 PtrVT));
Dan Gohman6183f782007-07-05 20:12:34 +00001267 else
1268 Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
1269 IntermediateVT, Val,
Dan Gohman25ac7e82007-08-10 14:59:38 +00001270 DAG.getConstant(i, PtrVT));
Dan Gohman6183f782007-07-05 20:12:34 +00001271
1272 // Split the intermediate operands into legal parts.
1273 if (NumParts == NumIntermediates) {
1274 // If the register was not expanded, promote or copy the value,
1275 // as appropriate.
1276 for (unsigned i = 0; i != NumParts; ++i)
Dan Gohman532dc2e2007-07-09 20:59:04 +00001277 getCopyToParts(DAG, Ops[i], &Parts[i], 1, PartVT);
Dan Gohman6183f782007-07-05 20:12:34 +00001278 } else if (NumParts > 0) {
1279 // If the intermediate type was expanded, split each the value into
1280 // legal parts.
1281 assert(NumParts % NumIntermediates == 0 &&
1282 "Must expand into a divisible number of parts!");
1283 unsigned Factor = NumParts / NumIntermediates;
1284 for (unsigned i = 0; i != NumIntermediates; ++i)
Dan Gohman532dc2e2007-07-09 20:59:04 +00001285 getCopyToParts(DAG, Ops[i], &Parts[i * Factor], Factor, PartVT);
Dan Gohman6183f782007-07-05 20:12:34 +00001286 }
1287}
1288
1289
Dan Gohman475871a2008-07-27 21:46:04 +00001290SDValue SelectionDAGLowering::getValue(const Value *V) {
1291 SDValue &N = NodeMap[V];
Chris Lattner199862b2006-03-16 19:57:50 +00001292 if (N.Val) return N;
1293
Chris Lattner199862b2006-03-16 19:57:50 +00001294 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V))) {
Duncan Sands83ec4b62008-06-06 12:08:01 +00001295 MVT VT = TLI.getValueType(V->getType(), true);
Chris Lattnerb606dba2008-04-28 06:44:42 +00001296
1297 if (ConstantInt *CI = dyn_cast<ConstantInt>(C))
1298 return N = DAG.getConstant(CI->getValue(), VT);
1299
1300 if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
Chris Lattner199862b2006-03-16 19:57:50 +00001301 return N = DAG.getGlobalAddress(GV, VT);
Chris Lattnerb606dba2008-04-28 06:44:42 +00001302
1303 if (isa<ConstantPointerNull>(C))
Chris Lattner199862b2006-03-16 19:57:50 +00001304 return N = DAG.getConstant(0, TLI.getPointerTy());
Chris Lattnerb606dba2008-04-28 06:44:42 +00001305
1306 if (ConstantFP *CFP = dyn_cast<ConstantFP>(C))
1307 return N = DAG.getConstantFP(CFP->getValueAPF(), VT);
1308
Dan Gohman1d685a42008-06-07 02:02:36 +00001309 if (isa<UndefValue>(C) && !isa<VectorType>(V->getType()) &&
1310 !V->getType()->isAggregateType())
Chris Lattner6833b062008-04-28 07:16:35 +00001311 return N = DAG.getNode(ISD::UNDEF, VT);
Chris Lattnerb606dba2008-04-28 06:44:42 +00001312
1313 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
1314 visit(CE->getOpcode(), *CE);
Dan Gohman475871a2008-07-27 21:46:04 +00001315 SDValue N1 = NodeMap[V];
Chris Lattnerb606dba2008-04-28 06:44:42 +00001316 assert(N1.Val && "visit didn't populate the ValueMap!");
1317 return N1;
1318 }
1319
Dan Gohman1d685a42008-06-07 02:02:36 +00001320 if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
Dan Gohman475871a2008-07-27 21:46:04 +00001321 SmallVector<SDValue, 4> Constants;
Dan Gohman1d685a42008-06-07 02:02:36 +00001322 for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end();
1323 OI != OE; ++OI) {
1324 SDNode *Val = getValue(*OI).Val;
Duncan Sands4bdcb612008-07-02 17:40:58 +00001325 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
Dan Gohman475871a2008-07-27 21:46:04 +00001326 Constants.push_back(SDValue(Val, i));
Dan Gohman1d685a42008-06-07 02:02:36 +00001327 }
Duncan Sands4bdcb612008-07-02 17:40:58 +00001328 return DAG.getMergeValues(&Constants[0], Constants.size());
Dan Gohman1d685a42008-06-07 02:02:36 +00001329 }
1330
Dan Gohman1f565bc2008-08-04 23:30:41 +00001331 if (isa<StructType>(C->getType()) || isa<ArrayType>(C->getType())) {
Dan Gohman1d685a42008-06-07 02:02:36 +00001332 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
Dan Gohman1f565bc2008-08-04 23:30:41 +00001333 "Unknown struct or array constant!");
Dan Gohman1d685a42008-06-07 02:02:36 +00001334
Dan Gohman1f565bc2008-08-04 23:30:41 +00001335 SmallVector<MVT, 4> ValueVTs;
1336 ComputeValueVTs(TLI, C->getType(), ValueVTs);
1337 unsigned NumElts = ValueVTs.size();
Dan Gohman8a6ccb52008-06-09 15:21:47 +00001338 if (NumElts == 0)
Dan Gohman475871a2008-07-27 21:46:04 +00001339 return SDValue(); // empty struct
1340 SmallVector<SDValue, 4> Constants(NumElts);
Dan Gohman1f565bc2008-08-04 23:30:41 +00001341 for (unsigned i = 0; i != NumElts; ++i) {
1342 MVT EltVT = ValueVTs[i];
Dan Gohman1d685a42008-06-07 02:02:36 +00001343 if (isa<UndefValue>(C))
1344 Constants[i] = DAG.getNode(ISD::UNDEF, EltVT);
1345 else if (EltVT.isFloatingPoint())
1346 Constants[i] = DAG.getConstantFP(0, EltVT);
1347 else
1348 Constants[i] = DAG.getConstant(0, EltVT);
1349 }
Dan Gohman1f565bc2008-08-04 23:30:41 +00001350 return DAG.getMergeValues(&Constants[0], NumElts);
Dan Gohman1d685a42008-06-07 02:02:36 +00001351 }
1352
Chris Lattner6833b062008-04-28 07:16:35 +00001353 const VectorType *VecTy = cast<VectorType>(V->getType());
Chris Lattnerb606dba2008-04-28 06:44:42 +00001354 unsigned NumElements = VecTy->getNumElements();
Chris Lattnerb606dba2008-04-28 06:44:42 +00001355
Chris Lattner6833b062008-04-28 07:16:35 +00001356 // Now that we know the number and type of the elements, get that number of
1357 // elements into the Ops array based on what kind of constant it is.
Dan Gohman475871a2008-07-27 21:46:04 +00001358 SmallVector<SDValue, 16> Ops;
Chris Lattnerb606dba2008-04-28 06:44:42 +00001359 if (ConstantVector *CP = dyn_cast<ConstantVector>(C)) {
1360 for (unsigned i = 0; i != NumElements; ++i)
1361 Ops.push_back(getValue(CP->getOperand(i)));
1362 } else {
Chris Lattner6833b062008-04-28 07:16:35 +00001363 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
1364 "Unknown vector constant!");
Duncan Sands83ec4b62008-06-06 12:08:01 +00001365 MVT EltVT = TLI.getValueType(VecTy->getElementType());
Chris Lattner6833b062008-04-28 07:16:35 +00001366
Dan Gohman475871a2008-07-27 21:46:04 +00001367 SDValue Op;
Chris Lattner6833b062008-04-28 07:16:35 +00001368 if (isa<UndefValue>(C))
1369 Op = DAG.getNode(ISD::UNDEF, EltVT);
Duncan Sands83ec4b62008-06-06 12:08:01 +00001370 else if (EltVT.isFloatingPoint())
Chris Lattner6833b062008-04-28 07:16:35 +00001371 Op = DAG.getConstantFP(0, EltVT);
Chris Lattnerb606dba2008-04-28 06:44:42 +00001372 else
Chris Lattner6833b062008-04-28 07:16:35 +00001373 Op = DAG.getConstant(0, EltVT);
Chris Lattnerb606dba2008-04-28 06:44:42 +00001374 Ops.assign(NumElements, Op);
1375 }
1376
1377 // Create a BUILD_VECTOR node.
1378 return NodeMap[V] = DAG.getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
Chris Lattner199862b2006-03-16 19:57:50 +00001379 }
1380
Chris Lattnerb606dba2008-04-28 06:44:42 +00001381 // If this is a static alloca, generate it as the frameindex instead of
1382 // computation.
Chris Lattner199862b2006-03-16 19:57:50 +00001383 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
Dan Gohman6ecf5092008-08-23 02:44:46 +00001384 DenseMap<const AllocaInst*, int>::iterator SI =
Chris Lattnerb606dba2008-04-28 06:44:42 +00001385 FuncInfo.StaticAllocaMap.find(AI);
Chris Lattner199862b2006-03-16 19:57:50 +00001386 if (SI != FuncInfo.StaticAllocaMap.end())
1387 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
1388 }
1389
Chris Lattner251db182007-02-25 18:40:32 +00001390 unsigned InReg = FuncInfo.ValueMap[V];
1391 assert(InReg && "Value not in map!");
Chris Lattner199862b2006-03-16 19:57:50 +00001392
Chris Lattner6833b062008-04-28 07:16:35 +00001393 RegsForValue RFV(TLI, InReg, V->getType());
Dan Gohman475871a2008-07-27 21:46:04 +00001394 SDValue Chain = DAG.getEntryNode();
Dan Gohmanb6f5b002007-06-28 23:29:44 +00001395 return RFV.getCopyFromRegs(DAG, Chain, NULL);
Chris Lattner199862b2006-03-16 19:57:50 +00001396}
1397
1398
Chris Lattner1c08c712005-01-07 07:47:53 +00001399void SelectionDAGLowering::visitRet(ReturnInst &I) {
1400 if (I.getNumOperands() == 0) {
Dan Gohman86e1ebf2008-03-27 19:56:19 +00001401 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getControlRoot()));
Chris Lattner1c08c712005-01-07 07:47:53 +00001402 return;
1403 }
Chris Lattnerb606dba2008-04-28 06:44:42 +00001404
Dan Gohman475871a2008-07-27 21:46:04 +00001405 SmallVector<SDValue, 8> NewValues;
Dan Gohman86e1ebf2008-03-27 19:56:19 +00001406 NewValues.push_back(getControlRoot());
1407 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
Dan Gohman475871a2008-07-27 21:46:04 +00001408 SDValue RetOp = getValue(I.getOperand(i));
Duncan Sandsb988bac2008-02-11 20:58:28 +00001409
Dan Gohmanab8ec0a2008-06-20 01:29:26 +00001410 SmallVector<MVT, 4> ValueVTs;
1411 ComputeValueVTs(TLI, I.getOperand(i)->getType(), ValueVTs);
1412 for (unsigned j = 0, f = ValueVTs.size(); j != f; ++j) {
1413 MVT VT = ValueVTs[j];
Duncan Sandsb988bac2008-02-11 20:58:28 +00001414
Dan Gohmanab8ec0a2008-06-20 01:29:26 +00001415 // FIXME: C calling convention requires the return type to be promoted to
1416 // at least 32-bit. But this is not necessary for non-C calling conventions.
1417 if (VT.isInteger()) {
1418 MVT MinVT = TLI.getRegisterType(MVT::i32);
1419 if (VT.bitsLT(MinVT))
1420 VT = MinVT;
1421 }
Duncan Sandsb988bac2008-02-11 20:58:28 +00001422
Dan Gohmanab8ec0a2008-06-20 01:29:26 +00001423 unsigned NumParts = TLI.getNumRegisters(VT);
1424 MVT PartVT = TLI.getRegisterType(VT);
Dan Gohman475871a2008-07-27 21:46:04 +00001425 SmallVector<SDValue, 4> Parts(NumParts);
Dan Gohmanab8ec0a2008-06-20 01:29:26 +00001426 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
1427
1428 const Function *F = I.getParent()->getParent();
1429 if (F->paramHasAttr(0, ParamAttr::SExt))
1430 ExtendKind = ISD::SIGN_EXTEND;
1431 else if (F->paramHasAttr(0, ParamAttr::ZExt))
1432 ExtendKind = ISD::ZERO_EXTEND;
Duncan Sandsb988bac2008-02-11 20:58:28 +00001433
Gabor Greif99a6cb92008-08-26 22:36:50 +00001434 getCopyToParts(DAG, SDValue(RetOp.Val, RetOp.getResNo() + j),
Dan Gohmanab8ec0a2008-06-20 01:29:26 +00001435 &Parts[0], NumParts, PartVT, ExtendKind);
Duncan Sandsb988bac2008-02-11 20:58:28 +00001436
Dan Gohmanab8ec0a2008-06-20 01:29:26 +00001437 for (unsigned i = 0; i < NumParts; ++i) {
1438 NewValues.push_back(Parts[i]);
1439 NewValues.push_back(DAG.getArgFlags(ISD::ArgFlagsTy()));
1440 }
Nate Begemanee625572006-01-27 21:09:22 +00001441 }
Chris Lattner1c08c712005-01-07 07:47:53 +00001442 }
Chris Lattnerbd564bf2006-08-08 02:23:42 +00001443 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other,
1444 &NewValues[0], NewValues.size()));
Chris Lattner1c08c712005-01-07 07:47:53 +00001445}
1446
Chris Lattner571e4342006-10-27 21:36:01 +00001447/// ExportFromCurrentBlock - If this condition isn't known to be exported from
1448/// the current basic block, add it to ValueMap now so that we'll get a
1449/// CopyTo/FromReg.
1450void SelectionDAGLowering::ExportFromCurrentBlock(Value *V) {
1451 // No need to export constants.
1452 if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
1453
1454 // Already exported?
1455 if (FuncInfo.isExportedInst(V)) return;
1456
1457 unsigned Reg = FuncInfo.InitializeRegForValue(V);
Dan Gohman86e1ebf2008-03-27 19:56:19 +00001458 CopyValueToVirtualRegister(V, Reg);
Chris Lattner571e4342006-10-27 21:36:01 +00001459}
1460
Chris Lattner8c494ab2006-10-27 23:50:33 +00001461bool SelectionDAGLowering::isExportableFromCurrentBlock(Value *V,
1462 const BasicBlock *FromBB) {
1463 // The operands of the setcc have to be in this block. We don't know
1464 // how to export them from some other block.
1465 if (Instruction *VI = dyn_cast<Instruction>(V)) {
1466 // Can export from current BB.
1467 if (VI->getParent() == FromBB)
1468 return true;
1469
1470 // Is already exported, noop.
1471 return FuncInfo.isExportedInst(V);
1472 }
1473
1474 // If this is an argument, we can export it if the BB is the entry block or
1475 // if it is already exported.
1476 if (isa<Argument>(V)) {
1477 if (FromBB == &FromBB->getParent()->getEntryBlock())
1478 return true;
1479
1480 // Otherwise, can only export this if it is already exported.
1481 return FuncInfo.isExportedInst(V);
1482 }
1483
1484 // Otherwise, constants can always be exported.
1485 return true;
1486}
1487
Chris Lattner6a586c82006-10-29 21:01:20 +00001488static bool InBlock(const Value *V, const BasicBlock *BB) {
1489 if (const Instruction *I = dyn_cast<Instruction>(V))
1490 return I->getParent() == BB;
1491 return true;
1492}
1493
Chris Lattner571e4342006-10-27 21:36:01 +00001494/// FindMergedConditions - If Cond is an expression like
1495void SelectionDAGLowering::FindMergedConditions(Value *Cond,
1496 MachineBasicBlock *TBB,
1497 MachineBasicBlock *FBB,
1498 MachineBasicBlock *CurBB,
1499 unsigned Opc) {
Chris Lattner571e4342006-10-27 21:36:01 +00001500 // If this node is not part of the or/and tree, emit it as a branch.
Reid Spencere4d87aa2006-12-23 06:05:41 +00001501 Instruction *BOp = dyn_cast<Instruction>(Cond);
Chris Lattner571e4342006-10-27 21:36:01 +00001502
Reid Spencere4d87aa2006-12-23 06:05:41 +00001503 if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
1504 (unsigned)BOp->getOpcode() != Opc || !BOp->hasOneUse() ||
Chris Lattner6a586c82006-10-29 21:01:20 +00001505 BOp->getParent() != CurBB->getBasicBlock() ||
1506 !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
1507 !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
Chris Lattner571e4342006-10-27 21:36:01 +00001508 const BasicBlock *BB = CurBB->getBasicBlock();
1509
Reid Spencere4d87aa2006-12-23 06:05:41 +00001510 // If the leaf of the tree is a comparison, merge the condition into
1511 // the caseblock.
1512 if ((isa<ICmpInst>(Cond) || isa<FCmpInst>(Cond)) &&
1513 // The operands of the cmp have to be in this block. We don't know
Chris Lattner5a145f02006-10-29 18:23:37 +00001514 // how to export them from some other block. If this is the first block
1515 // of the sequence, no exporting is needed.
1516 (CurBB == CurMBB ||
1517 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
1518 isExportableFromCurrentBlock(BOp->getOperand(1), BB)))) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00001519 BOp = cast<Instruction>(Cond);
1520 ISD::CondCode Condition;
1521 if (ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
1522 switch (IC->getPredicate()) {
1523 default: assert(0 && "Unknown icmp predicate opcode!");
1524 case ICmpInst::ICMP_EQ: Condition = ISD::SETEQ; break;
1525 case ICmpInst::ICMP_NE: Condition = ISD::SETNE; break;
1526 case ICmpInst::ICMP_SLE: Condition = ISD::SETLE; break;
1527 case ICmpInst::ICMP_ULE: Condition = ISD::SETULE; break;
1528 case ICmpInst::ICMP_SGE: Condition = ISD::SETGE; break;
1529 case ICmpInst::ICMP_UGE: Condition = ISD::SETUGE; break;
1530 case ICmpInst::ICMP_SLT: Condition = ISD::SETLT; break;
1531 case ICmpInst::ICMP_ULT: Condition = ISD::SETULT; break;
1532 case ICmpInst::ICMP_SGT: Condition = ISD::SETGT; break;
1533 case ICmpInst::ICMP_UGT: Condition = ISD::SETUGT; break;
1534 }
1535 } else if (FCmpInst *FC = dyn_cast<FCmpInst>(Cond)) {
1536 ISD::CondCode FPC, FOC;
1537 switch (FC->getPredicate()) {
1538 default: assert(0 && "Unknown fcmp predicate opcode!");
1539 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
1540 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
1541 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
1542 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
1543 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
1544 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
1545 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
Chris Lattner6bf30ab2008-05-01 07:26:11 +00001546 case FCmpInst::FCMP_ORD: FOC = FPC = ISD::SETO; break;
1547 case FCmpInst::FCMP_UNO: FOC = FPC = ISD::SETUO; break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00001548 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
1549 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
1550 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
1551 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
1552 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
1553 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
1554 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
1555 }
1556 if (FiniteOnlyFPMath())
1557 Condition = FOC;
1558 else
1559 Condition = FPC;
1560 } else {
Chris Lattner0da331f2007-02-04 01:31:47 +00001561 Condition = ISD::SETEQ; // silence warning.
Reid Spencere4d87aa2006-12-23 06:05:41 +00001562 assert(0 && "Unknown compare instruction");
Chris Lattner571e4342006-10-27 21:36:01 +00001563 }
1564
Dan Gohman7c3234c2008-08-27 23:52:12 +00001565 CaseBlock CB(Condition, BOp->getOperand(0),
1566 BOp->getOperand(1), NULL, TBB, FBB, CurBB);
Chris Lattner571e4342006-10-27 21:36:01 +00001567 SwitchCases.push_back(CB);
1568 return;
1569 }
1570
1571 // Create a CaseBlock record representing this branch.
Dan Gohman7c3234c2008-08-27 23:52:12 +00001572 CaseBlock CB(ISD::SETEQ, Cond, ConstantInt::getTrue(),
1573 NULL, TBB, FBB, CurBB);
Chris Lattner571e4342006-10-27 21:36:01 +00001574 SwitchCases.push_back(CB);
Chris Lattner571e4342006-10-27 21:36:01 +00001575 return;
1576 }
1577
Chris Lattnerd2f9ee92006-10-27 21:54:23 +00001578
1579 // Create TmpBB after CurBB.
Chris Lattner571e4342006-10-27 21:36:01 +00001580 MachineFunction::iterator BBI = CurBB;
Dan Gohman0e5f1302008-07-07 23:02:41 +00001581 MachineFunction &MF = DAG.getMachineFunction();
1582 MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
1583 CurBB->getParent()->insert(++BBI, TmpBB);
Chris Lattner571e4342006-10-27 21:36:01 +00001584
Chris Lattnerd2f9ee92006-10-27 21:54:23 +00001585 if (Opc == Instruction::Or) {
1586 // Codegen X | Y as:
1587 // jmp_if_X TBB
1588 // jmp TmpBB
1589 // TmpBB:
1590 // jmp_if_Y TBB
1591 // jmp FBB
1592 //
Chris Lattner571e4342006-10-27 21:36:01 +00001593
Chris Lattnerd2f9ee92006-10-27 21:54:23 +00001594 // Emit the LHS condition.
1595 FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, Opc);
1596
1597 // Emit the RHS condition into TmpBB.
1598 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
1599 } else {
1600 assert(Opc == Instruction::And && "Unknown merge op!");
1601 // Codegen X & Y as:
1602 // jmp_if_X TmpBB
1603 // jmp FBB
1604 // TmpBB:
1605 // jmp_if_Y TBB
1606 // jmp FBB
1607 //
1608 // This requires creation of TmpBB after CurBB.
1609
1610 // Emit the LHS condition.
1611 FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, Opc);
1612
1613 // Emit the RHS condition into TmpBB.
1614 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
1615 }
Chris Lattner571e4342006-10-27 21:36:01 +00001616}
1617
Chris Lattnerdf19f272006-10-31 22:37:42 +00001618/// If the set of cases should be emitted as a series of branches, return true.
1619/// If we should emit this as a bunch of and/or'd together conditions, return
1620/// false.
1621static bool
Dan Gohman7c3234c2008-08-27 23:52:12 +00001622ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) {
Chris Lattnerdf19f272006-10-31 22:37:42 +00001623 if (Cases.size() != 2) return true;
1624
Chris Lattner0ccb5002006-10-31 23:06:00 +00001625 // If this is two comparisons of the same values or'd or and'd together, they
1626 // will get folded into a single comparison, so don't emit two blocks.
1627 if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
1628 Cases[0].CmpRHS == Cases[1].CmpRHS) ||
1629 (Cases[0].CmpRHS == Cases[1].CmpLHS &&
1630 Cases[0].CmpLHS == Cases[1].CmpRHS)) {
1631 return false;
1632 }
1633
Chris Lattnerdf19f272006-10-31 22:37:42 +00001634 return true;
1635}
1636
Chris Lattner1c08c712005-01-07 07:47:53 +00001637void SelectionDAGLowering::visitBr(BranchInst &I) {
1638 // Update machine-CFG edges.
1639 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
Chris Lattner1c08c712005-01-07 07:47:53 +00001640
1641 // Figure out which block is immediately after the current one.
1642 MachineBasicBlock *NextBlock = 0;
1643 MachineFunction::iterator BBI = CurMBB;
1644 if (++BBI != CurMBB->getParent()->end())
1645 NextBlock = BBI;
1646
1647 if (I.isUnconditional()) {
Owen Anderson2d389e82008-06-07 00:00:23 +00001648 // Update machine-CFG edges.
1649 CurMBB->addSuccessor(Succ0MBB);
1650
Chris Lattner1c08c712005-01-07 07:47:53 +00001651 // If this is not a fall-through branch, emit the branch.
1652 if (Succ0MBB != NextBlock)
Dan Gohman86e1ebf2008-03-27 19:56:19 +00001653 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getControlRoot(),
Misha Brukmandedf2bd2005-04-22 04:01:18 +00001654 DAG.getBasicBlock(Succ0MBB)));
Chris Lattner57ab6592006-10-24 17:57:59 +00001655 return;
1656 }
1657
1658 // If this condition is one of the special cases we handle, do special stuff
1659 // now.
1660 Value *CondVal = I.getCondition();
Chris Lattner57ab6592006-10-24 17:57:59 +00001661 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
Chris Lattner571e4342006-10-27 21:36:01 +00001662
1663 // If this is a series of conditions that are or'd or and'd together, emit
1664 // this as a sequence of branches instead of setcc's with and/or operations.
1665 // For example, instead of something like:
1666 // cmp A, B
1667 // C = seteq
1668 // cmp D, E
1669 // F = setle
1670 // or C, F
1671 // jnz foo
1672 // Emit:
1673 // cmp A, B
1674 // je foo
1675 // cmp D, E
1676 // jle foo
1677 //
1678 if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
1679 if (BOp->hasOneUse() &&
Chris Lattnerd2f9ee92006-10-27 21:54:23 +00001680 (BOp->getOpcode() == Instruction::And ||
Chris Lattner571e4342006-10-27 21:36:01 +00001681 BOp->getOpcode() == Instruction::Or)) {
1682 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, CurMBB, BOp->getOpcode());
Chris Lattner0ccb5002006-10-31 23:06:00 +00001683 // If the compares in later blocks need to use values not currently
1684 // exported from this block, export them now. This block should always
1685 // be the first entry.
1686 assert(SwitchCases[0].ThisBB == CurMBB && "Unexpected lowering!");
1687
Chris Lattnerdf19f272006-10-31 22:37:42 +00001688 // Allow some cases to be rejected.
1689 if (ShouldEmitAsBranches(SwitchCases)) {
Chris Lattnerdf19f272006-10-31 22:37:42 +00001690 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
1691 ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
1692 ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
1693 }
1694
1695 // Emit the branch for this block.
1696 visitSwitchCase(SwitchCases[0]);
1697 SwitchCases.erase(SwitchCases.begin());
1698 return;
Chris Lattner5a145f02006-10-29 18:23:37 +00001699 }
1700
Chris Lattner0ccb5002006-10-31 23:06:00 +00001701 // Okay, we decided not to do this, remove any inserted MBB's and clear
1702 // SwitchCases.
1703 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
Dan Gohman0e5f1302008-07-07 23:02:41 +00001704 CurMBB->getParent()->erase(SwitchCases[i].ThisBB);
Chris Lattner0ccb5002006-10-31 23:06:00 +00001705
Chris Lattnerdf19f272006-10-31 22:37:42 +00001706 SwitchCases.clear();
Chris Lattner571e4342006-10-27 21:36:01 +00001707 }
1708 }
Chris Lattner24525952006-10-24 18:07:37 +00001709
1710 // Create a CaseBlock record representing this branch.
Dan Gohman7c3234c2008-08-27 23:52:12 +00001711 CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(),
1712 NULL, Succ0MBB, Succ1MBB, CurMBB);
Chris Lattner24525952006-10-24 18:07:37 +00001713 // Use visitSwitchCase to actually insert the fast branch sequence for this
1714 // cond branch.
1715 visitSwitchCase(CB);
Chris Lattner1c08c712005-01-07 07:47:53 +00001716}
1717
Nate Begemanf15485a2006-03-27 01:32:24 +00001718/// visitSwitchCase - Emits the necessary code to represent a single node in
1719/// the binary search tree resulting from lowering a switch instruction.
Dan Gohman7c3234c2008-08-27 23:52:12 +00001720void SelectionDAGLowering::visitSwitchCase(CaseBlock &CB) {
Dan Gohman475871a2008-07-27 21:46:04 +00001721 SDValue Cond;
1722 SDValue CondLHS = getValue(CB.CmpLHS);
Chris Lattner57ab6592006-10-24 17:57:59 +00001723
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001724 // Build the setcc now.
1725 if (CB.CmpMHS == NULL) {
1726 // Fold "(X == true)" to X and "(X == false)" to !X to
1727 // handle common cases produced by branch lowering.
1728 if (CB.CmpRHS == ConstantInt::getTrue() && CB.CC == ISD::SETEQ)
1729 Cond = CondLHS;
1730 else if (CB.CmpRHS == ConstantInt::getFalse() && CB.CC == ISD::SETEQ) {
Dan Gohman475871a2008-07-27 21:46:04 +00001731 SDValue True = DAG.getConstant(1, CondLHS.getValueType());
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001732 Cond = DAG.getNode(ISD::XOR, CondLHS.getValueType(), CondLHS, True);
1733 } else
1734 Cond = DAG.getSetCC(MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
1735 } else {
1736 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001737
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001738 uint64_t Low = cast<ConstantInt>(CB.CmpLHS)->getSExtValue();
1739 uint64_t High = cast<ConstantInt>(CB.CmpRHS)->getSExtValue();
1740
Dan Gohman475871a2008-07-27 21:46:04 +00001741 SDValue CmpOp = getValue(CB.CmpMHS);
Duncan Sands83ec4b62008-06-06 12:08:01 +00001742 MVT VT = CmpOp.getValueType();
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001743
1744 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
1745 Cond = DAG.getSetCC(MVT::i1, CmpOp, DAG.getConstant(High, VT), ISD::SETLE);
1746 } else {
Dan Gohman475871a2008-07-27 21:46:04 +00001747 SDValue SUB = DAG.getNode(ISD::SUB, VT, CmpOp, DAG.getConstant(Low, VT));
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001748 Cond = DAG.getSetCC(MVT::i1, SUB,
1749 DAG.getConstant(High-Low, VT), ISD::SETULE);
1750 }
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001751 }
1752
Owen Anderson2d389e82008-06-07 00:00:23 +00001753 // Update successor info
1754 CurMBB->addSuccessor(CB.TrueBB);
1755 CurMBB->addSuccessor(CB.FalseBB);
1756
Nate Begemanf15485a2006-03-27 01:32:24 +00001757 // Set NextBlock to be the MBB immediately after the current one, if any.
1758 // This is used to avoid emitting unnecessary branches to the next block.
1759 MachineBasicBlock *NextBlock = 0;
1760 MachineFunction::iterator BBI = CurMBB;
1761 if (++BBI != CurMBB->getParent()->end())
1762 NextBlock = BBI;
1763
1764 // If the lhs block is the next block, invert the condition so that we can
1765 // fall through to the lhs instead of the rhs block.
Chris Lattner57ab6592006-10-24 17:57:59 +00001766 if (CB.TrueBB == NextBlock) {
1767 std::swap(CB.TrueBB, CB.FalseBB);
Dan Gohman475871a2008-07-27 21:46:04 +00001768 SDValue True = DAG.getConstant(1, Cond.getValueType());
Nate Begemanf15485a2006-03-27 01:32:24 +00001769 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
1770 }
Dan Gohman475871a2008-07-27 21:46:04 +00001771 SDValue BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, getControlRoot(), Cond,
Chris Lattner57ab6592006-10-24 17:57:59 +00001772 DAG.getBasicBlock(CB.TrueBB));
Owen Andersonbd3ba462008-08-04 23:54:43 +00001773
1774 // If the branch was constant folded, fix up the CFG.
1775 if (BrCond.getOpcode() == ISD::BR) {
Owen Anderson3bc9c6f2008-08-05 18:27:54 +00001776 CurMBB->removeSuccessor(CB.FalseBB);
Nate Begemanf15485a2006-03-27 01:32:24 +00001777 DAG.setRoot(BrCond);
Owen Andersonbd3ba462008-08-04 23:54:43 +00001778 } else {
1779 // Otherwise, go ahead and insert the false branch.
1780 if (BrCond == getControlRoot())
Owen Anderson3bc9c6f2008-08-05 18:27:54 +00001781 CurMBB->removeSuccessor(CB.TrueBB);
Owen Andersonbd3ba462008-08-04 23:54:43 +00001782
1783 if (CB.FalseBB == NextBlock)
1784 DAG.setRoot(BrCond);
1785 else
1786 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond,
1787 DAG.getBasicBlock(CB.FalseBB)));
1788 }
Nate Begemanf15485a2006-03-27 01:32:24 +00001789}
1790
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001791/// visitJumpTable - Emit JumpTable node in the current MBB
Dan Gohman7c3234c2008-08-27 23:52:12 +00001792void SelectionDAGLowering::visitJumpTable(JumpTable &JT) {
Nate Begeman37efe672006-04-22 18:53:45 +00001793 // Emit the code for the jump table
Scott Michelf147a8d2007-04-24 01:24:20 +00001794 assert(JT.Reg != -1U && "Should lower JT Header first!");
Duncan Sands83ec4b62008-06-06 12:08:01 +00001795 MVT PTy = TLI.getPointerTy();
Dan Gohman475871a2008-07-27 21:46:04 +00001796 SDValue Index = DAG.getCopyFromReg(getControlRoot(), JT.Reg, PTy);
1797 SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
Evan Cheng3d4ce112006-10-30 08:00:44 +00001798 DAG.setRoot(DAG.getNode(ISD::BR_JT, MVT::Other, Index.getValue(1),
1799 Table, Index));
1800 return;
Nate Begeman37efe672006-04-22 18:53:45 +00001801}
1802
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001803/// visitJumpTableHeader - This function emits necessary code to produce index
1804/// in the JumpTable from switch case.
Dan Gohman7c3234c2008-08-27 23:52:12 +00001805void SelectionDAGLowering::visitJumpTableHeader(JumpTable &JT,
1806 JumpTableHeader &JTH) {
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001807 // Subtract the lowest switch case value from the value being switched on
1808 // and conditional branch to default mbb if the result is greater than the
1809 // difference between smallest and largest cases.
Dan Gohman475871a2008-07-27 21:46:04 +00001810 SDValue SwitchOp = getValue(JTH.SValue);
Duncan Sands83ec4b62008-06-06 12:08:01 +00001811 MVT VT = SwitchOp.getValueType();
Dan Gohman475871a2008-07-27 21:46:04 +00001812 SDValue SUB = DAG.getNode(ISD::SUB, VT, SwitchOp,
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001813 DAG.getConstant(JTH.First, VT));
1814
1815 // The SDNode we just created, which holds the value being switched on
1816 // minus the the smallest case value, needs to be copied to a virtual
1817 // register so it can be used as an index into the jump table in a
1818 // subsequent basic block. This value may be smaller or larger than the
1819 // target's pointer type, and therefore require extension or truncating.
Duncan Sands8e4eb092008-06-08 20:54:56 +00001820 if (VT.bitsGT(TLI.getPointerTy()))
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001821 SwitchOp = DAG.getNode(ISD::TRUNCATE, TLI.getPointerTy(), SUB);
1822 else
1823 SwitchOp = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(), SUB);
1824
1825 unsigned JumpTableReg = FuncInfo.MakeReg(TLI.getPointerTy());
Dan Gohman475871a2008-07-27 21:46:04 +00001826 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), JumpTableReg, SwitchOp);
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001827 JT.Reg = JumpTableReg;
1828
1829 // Emit the range check for the jump table, and branch to the default
1830 // block for the switch statement if the value being switched on exceeds
1831 // the largest case in the switch.
Dan Gohman475871a2008-07-27 21:46:04 +00001832 SDValue CMP = DAG.getSetCC(TLI.getSetCCResultType(SUB), SUB,
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001833 DAG.getConstant(JTH.Last-JTH.First,VT),
1834 ISD::SETUGT);
1835
1836 // Set NextBlock to be the MBB immediately after the current one, if any.
1837 // This is used to avoid emitting unnecessary branches to the next block.
1838 MachineBasicBlock *NextBlock = 0;
1839 MachineFunction::iterator BBI = CurMBB;
1840 if (++BBI != CurMBB->getParent()->end())
1841 NextBlock = BBI;
1842
Dan Gohman475871a2008-07-27 21:46:04 +00001843 SDValue BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, CopyTo, CMP,
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001844 DAG.getBasicBlock(JT.Default));
1845
1846 if (JT.MBB == NextBlock)
1847 DAG.setRoot(BrCond);
1848 else
1849 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond,
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001850 DAG.getBasicBlock(JT.MBB)));
1851
1852 return;
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001853}
1854
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001855/// visitBitTestHeader - This function emits necessary code to produce value
1856/// suitable for "bit tests"
Dan Gohman7c3234c2008-08-27 23:52:12 +00001857void SelectionDAGLowering::visitBitTestHeader(BitTestBlock &B) {
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001858 // Subtract the minimum value
Dan Gohman475871a2008-07-27 21:46:04 +00001859 SDValue SwitchOp = getValue(B.SValue);
Duncan Sands83ec4b62008-06-06 12:08:01 +00001860 MVT VT = SwitchOp.getValueType();
Dan Gohman475871a2008-07-27 21:46:04 +00001861 SDValue SUB = DAG.getNode(ISD::SUB, VT, SwitchOp,
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001862 DAG.getConstant(B.First, VT));
1863
1864 // Check range
Dan Gohman475871a2008-07-27 21:46:04 +00001865 SDValue RangeCmp = DAG.getSetCC(TLI.getSetCCResultType(SUB), SUB,
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001866 DAG.getConstant(B.Range, VT),
1867 ISD::SETUGT);
1868
Dan Gohman475871a2008-07-27 21:46:04 +00001869 SDValue ShiftOp;
Duncan Sands8e4eb092008-06-08 20:54:56 +00001870 if (VT.bitsGT(TLI.getShiftAmountTy()))
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001871 ShiftOp = DAG.getNode(ISD::TRUNCATE, TLI.getShiftAmountTy(), SUB);
1872 else
1873 ShiftOp = DAG.getNode(ISD::ZERO_EXTEND, TLI.getShiftAmountTy(), SUB);
1874
1875 // Make desired shift
Dan Gohman475871a2008-07-27 21:46:04 +00001876 SDValue SwitchVal = DAG.getNode(ISD::SHL, TLI.getPointerTy(),
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001877 DAG.getConstant(1, TLI.getPointerTy()),
1878 ShiftOp);
1879
1880 unsigned SwitchReg = FuncInfo.MakeReg(TLI.getPointerTy());
Dan Gohman475871a2008-07-27 21:46:04 +00001881 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), SwitchReg, SwitchVal);
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001882 B.Reg = SwitchReg;
1883
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001884 // Set NextBlock to be the MBB immediately after the current one, if any.
1885 // This is used to avoid emitting unnecessary branches to the next block.
1886 MachineBasicBlock *NextBlock = 0;
1887 MachineFunction::iterator BBI = CurMBB;
1888 if (++BBI != CurMBB->getParent()->end())
1889 NextBlock = BBI;
1890
1891 MachineBasicBlock* MBB = B.Cases[0].ThisBB;
Owen Anderson2d389e82008-06-07 00:00:23 +00001892
1893 CurMBB->addSuccessor(B.Default);
1894 CurMBB->addSuccessor(MBB);
1895
Dan Gohman475871a2008-07-27 21:46:04 +00001896 SDValue BrRange = DAG.getNode(ISD::BRCOND, MVT::Other, CopyTo, RangeCmp,
Owen Anderson2d389e82008-06-07 00:00:23 +00001897 DAG.getBasicBlock(B.Default));
1898
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001899 if (MBB == NextBlock)
1900 DAG.setRoot(BrRange);
1901 else
1902 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, CopyTo,
1903 DAG.getBasicBlock(MBB)));
1904
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001905 return;
1906}
1907
1908/// visitBitTestCase - this function produces one "bit test"
1909void SelectionDAGLowering::visitBitTestCase(MachineBasicBlock* NextMBB,
1910 unsigned Reg,
Dan Gohman7c3234c2008-08-27 23:52:12 +00001911 BitTestCase &B) {
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001912 // Emit bit tests and jumps
Dan Gohman475871a2008-07-27 21:46:04 +00001913 SDValue SwitchVal = DAG.getCopyFromReg(getControlRoot(), Reg,
Chris Lattneread0d882008-06-17 06:09:18 +00001914 TLI.getPointerTy());
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001915
Dan Gohman475871a2008-07-27 21:46:04 +00001916 SDValue AndOp = DAG.getNode(ISD::AND, TLI.getPointerTy(), SwitchVal,
Chris Lattneread0d882008-06-17 06:09:18 +00001917 DAG.getConstant(B.Mask, TLI.getPointerTy()));
Dan Gohman475871a2008-07-27 21:46:04 +00001918 SDValue AndCmp = DAG.getSetCC(TLI.getSetCCResultType(AndOp), AndOp,
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001919 DAG.getConstant(0, TLI.getPointerTy()),
1920 ISD::SETNE);
Owen Anderson2d389e82008-06-07 00:00:23 +00001921
1922 CurMBB->addSuccessor(B.TargetBB);
1923 CurMBB->addSuccessor(NextMBB);
1924
Dan Gohman475871a2008-07-27 21:46:04 +00001925 SDValue BrAnd = DAG.getNode(ISD::BRCOND, MVT::Other, getControlRoot(),
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001926 AndCmp, DAG.getBasicBlock(B.TargetBB));
1927
1928 // Set NextBlock to be the MBB immediately after the current one, if any.
1929 // This is used to avoid emitting unnecessary branches to the next block.
1930 MachineBasicBlock *NextBlock = 0;
1931 MachineFunction::iterator BBI = CurMBB;
1932 if (++BBI != CurMBB->getParent()->end())
1933 NextBlock = BBI;
1934
1935 if (NextMBB == NextBlock)
1936 DAG.setRoot(BrAnd);
1937 else
1938 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrAnd,
1939 DAG.getBasicBlock(NextMBB)));
1940
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001941 return;
1942}
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001943
Jim Laskeyb180aa12007-02-21 22:53:45 +00001944void SelectionDAGLowering::visitInvoke(InvokeInst &I) {
1945 // Retrieve successors.
1946 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
Duncan Sandsf19f6bb2007-06-13 05:51:31 +00001947 MachineBasicBlock *LandingPad = FuncInfo.MBBMap[I.getSuccessor(1)];
Duncan Sands9fac0b52007-06-06 10:05:18 +00001948
Duncan Sandsfd7b3262007-12-17 18:08:19 +00001949 if (isa<InlineAsm>(I.getCalledValue()))
1950 visitInlineAsm(&I);
1951 else
Duncan Sands6f74b482007-12-19 09:48:52 +00001952 LowerCallTo(&I, getValue(I.getOperand(0)), false, LandingPad);
Duncan Sands9fac0b52007-06-06 10:05:18 +00001953
Duncan Sandsf19f6bb2007-06-13 05:51:31 +00001954 // If the value of the invoke is used outside of its defining block, make it
1955 // available as a virtual register.
1956 if (!I.use_empty()) {
1957 DenseMap<const Value*, unsigned>::iterator VMI = FuncInfo.ValueMap.find(&I);
1958 if (VMI != FuncInfo.ValueMap.end())
Dan Gohman86e1ebf2008-03-27 19:56:19 +00001959 CopyValueToVirtualRegister(&I, VMI->second);
Jim Laskey183f47f2007-02-25 21:43:59 +00001960 }
Duncan Sandsf19f6bb2007-06-13 05:51:31 +00001961
Duncan Sandsf19f6bb2007-06-13 05:51:31 +00001962 // Update successor info
1963 CurMBB->addSuccessor(Return);
1964 CurMBB->addSuccessor(LandingPad);
Owen Anderson2d389e82008-06-07 00:00:23 +00001965
1966 // Drop into normal successor.
1967 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getControlRoot(),
1968 DAG.getBasicBlock(Return)));
Jim Laskeyb180aa12007-02-21 22:53:45 +00001969}
1970
1971void SelectionDAGLowering::visitUnwind(UnwindInst &I) {
1972}
1973
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001974/// handleSmallSwitchCaseRange - Emit a series of specific tests (suitable for
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001975/// small case ranges).
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001976bool SelectionDAGLowering::handleSmallSwitchRange(CaseRec& CR,
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001977 CaseRecVector& WorkList,
1978 Value* SV,
1979 MachineBasicBlock* Default) {
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001980 Case& BackCase = *(CR.Range.second-1);
1981
1982 // Size is the number of Cases represented by this range.
1983 unsigned Size = CR.Range.second - CR.Range.first;
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001984 if (Size > 3)
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001985 return false;
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001986
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001987 // Get the MachineFunction which holds the current MBB. This is used when
1988 // inserting any additional MBBs necessary to represent the switch.
1989 MachineFunction *CurMF = CurMBB->getParent();
1990
1991 // Figure out which block is immediately after the current one.
1992 MachineBasicBlock *NextBlock = 0;
1993 MachineFunction::iterator BBI = CR.CaseBB;
1994
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001995 if (++BBI != CurMBB->getParent()->end())
1996 NextBlock = BBI;
1997
1998 // TODO: If any two of the cases has the same destination, and if one value
1999 // is the same as the other, but has one bit unset that the other has set,
2000 // use bit manipulation to do two compares at once. For example:
2001 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
2002
2003 // Rearrange the case blocks so that the last one falls through if possible.
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002004 if (NextBlock && Default != NextBlock && BackCase.BB != NextBlock) {
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00002005 // The last case block won't fall through into 'NextBlock' if we emit the
2006 // branches in this order. See if rearranging a case value would help.
2007 for (CaseItr I = CR.Range.first, E = CR.Range.second-1; I != E; ++I) {
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002008 if (I->BB == NextBlock) {
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00002009 std::swap(*I, BackCase);
2010 break;
2011 }
2012 }
2013 }
2014
2015 // Create a CaseBlock record representing a conditional branch to
2016 // the Case's target mbb if the value being switched on SV is equal
2017 // to C.
2018 MachineBasicBlock *CurBlock = CR.CaseBB;
2019 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I) {
2020 MachineBasicBlock *FallThrough;
2021 if (I != E-1) {
Dan Gohman0e5f1302008-07-07 23:02:41 +00002022 FallThrough = CurMF->CreateMachineBasicBlock(CurBlock->getBasicBlock());
2023 CurMF->insert(BBI, FallThrough);
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00002024 } else {
2025 // If the last case doesn't match, go to the default block.
2026 FallThrough = Default;
2027 }
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002028
2029 Value *RHS, *LHS, *MHS;
2030 ISD::CondCode CC;
2031 if (I->High == I->Low) {
2032 // This is just small small case range :) containing exactly 1 case
2033 CC = ISD::SETEQ;
2034 LHS = SV; RHS = I->High; MHS = NULL;
2035 } else {
2036 CC = ISD::SETLE;
2037 LHS = I->Low; MHS = SV; RHS = I->High;
2038 }
Dan Gohman7c3234c2008-08-27 23:52:12 +00002039 CaseBlock CB(CC, LHS, RHS, MHS, I->BB, FallThrough, CurBlock);
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00002040
2041 // If emitting the first comparison, just call visitSwitchCase to emit the
2042 // code into the current block. Otherwise, push the CaseBlock onto the
2043 // vector to be later processed by SDISel, and insert the node's MBB
2044 // before the next MBB.
2045 if (CurBlock == CurMBB)
2046 visitSwitchCase(CB);
2047 else
2048 SwitchCases.push_back(CB);
2049
2050 CurBlock = FallThrough;
2051 }
Anton Korobeynikovdd433212007-03-27 12:05:48 +00002052
2053 return true;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00002054}
2055
Anton Korobeynikov7294b582007-05-09 20:07:08 +00002056static inline bool areJTsAllowed(const TargetLowering &TLI) {
Dale Johannesen72324642008-07-31 18:13:12 +00002057 return !DisableJumpTables &&
2058 (TLI.isOperationLegal(ISD::BR_JT, MVT::Other) ||
2059 TLI.isOperationLegal(ISD::BRIND, MVT::Other));
Anton Korobeynikov7294b582007-05-09 20:07:08 +00002060}
2061
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00002062/// handleJTSwitchCase - Emit jumptable for current switch case range
Anton Korobeynikovdd433212007-03-27 12:05:48 +00002063bool SelectionDAGLowering::handleJTSwitchCase(CaseRec& CR,
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00002064 CaseRecVector& WorkList,
2065 Value* SV,
2066 MachineBasicBlock* Default) {
Anton Korobeynikovdd433212007-03-27 12:05:48 +00002067 Case& FrontCase = *CR.Range.first;
2068 Case& BackCase = *(CR.Range.second-1);
2069
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002070 int64_t First = cast<ConstantInt>(FrontCase.Low)->getSExtValue();
2071 int64_t Last = cast<ConstantInt>(BackCase.High)->getSExtValue();
2072
2073 uint64_t TSize = 0;
2074 for (CaseItr I = CR.Range.first, E = CR.Range.second;
2075 I!=E; ++I)
2076 TSize += I->size();
Anton Korobeynikovdd433212007-03-27 12:05:48 +00002077
Anton Korobeynikov7294b582007-05-09 20:07:08 +00002078 if (!areJTsAllowed(TLI) || TSize <= 3)
Anton Korobeynikovdd433212007-03-27 12:05:48 +00002079 return false;
2080
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002081 double Density = (double)TSize / (double)((Last - First) + 1ULL);
2082 if (Density < 0.4)
Anton Korobeynikovdd433212007-03-27 12:05:48 +00002083 return false;
2084
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002085 DOUT << "Lowering jump table\n"
2086 << "First entry: " << First << ". Last entry: " << Last << "\n"
Anton Korobeynikov4198c582007-04-09 12:31:58 +00002087 << "Size: " << TSize << ". Density: " << Density << "\n\n";
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002088
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00002089 // Get the MachineFunction which holds the current MBB. This is used when
2090 // inserting any additional MBBs necessary to represent the switch.
Anton Korobeynikovdd433212007-03-27 12:05:48 +00002091 MachineFunction *CurMF = CurMBB->getParent();
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00002092
2093 // Figure out which block is immediately after the current one.
2094 MachineBasicBlock *NextBlock = 0;
2095 MachineFunction::iterator BBI = CR.CaseBB;
2096
2097 if (++BBI != CurMBB->getParent()->end())
2098 NextBlock = BBI;
2099
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00002100 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
2101
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00002102 // Create a new basic block to hold the code for loading the address
2103 // of the jump table, and jumping to it. Update successor information;
2104 // we will either branch to the default case for the switch, or the jump
2105 // table.
Dan Gohman0e5f1302008-07-07 23:02:41 +00002106 MachineBasicBlock *JumpTableBB = CurMF->CreateMachineBasicBlock(LLVMBB);
2107 CurMF->insert(BBI, JumpTableBB);
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00002108 CR.CaseBB->addSuccessor(Default);
2109 CR.CaseBB->addSuccessor(JumpTableBB);
2110
2111 // Build a vector of destination BBs, corresponding to each target
Anton Korobeynikov4198c582007-04-09 12:31:58 +00002112 // of the jump table. If the value of the jump table slot corresponds to
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00002113 // a case statement, push the case's BB onto the vector, otherwise, push
2114 // the default BB.
2115 std::vector<MachineBasicBlock*> DestBBs;
2116 int64_t TEI = First;
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002117 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++TEI) {
2118 int64_t Low = cast<ConstantInt>(I->Low)->getSExtValue();
2119 int64_t High = cast<ConstantInt>(I->High)->getSExtValue();
2120
2121 if ((Low <= TEI) && (TEI <= High)) {
2122 DestBBs.push_back(I->BB);
2123 if (TEI==High)
2124 ++I;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00002125 } else {
2126 DestBBs.push_back(Default);
2127 }
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002128 }
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00002129
2130 // Update successor info. Add one edge to each unique successor.
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002131 BitVector SuccsHandled(CR.CaseBB->getParent()->getNumBlockIDs());
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00002132 for (std::vector<MachineBasicBlock*>::iterator I = DestBBs.begin(),
2133 E = DestBBs.end(); I != E; ++I) {
2134 if (!SuccsHandled[(*I)->getNumber()]) {
2135 SuccsHandled[(*I)->getNumber()] = true;
2136 JumpTableBB->addSuccessor(*I);
2137 }
2138 }
2139
2140 // Create a jump table index for this jump table, or return an existing
2141 // one.
2142 unsigned JTI = CurMF->getJumpTableInfo()->getJumpTableIndex(DestBBs);
2143
2144 // Set the jump table information so that we can codegen it as a second
2145 // MachineBasicBlock
Dan Gohman7c3234c2008-08-27 23:52:12 +00002146 JumpTable JT(-1U, JTI, JumpTableBB, Default);
2147 JumpTableHeader JTH(First, Last, SV, CR.CaseBB, (CR.CaseBB == CurMBB));
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00002148 if (CR.CaseBB == CurMBB)
2149 visitJumpTableHeader(JT, JTH);
2150
Dan Gohman7c3234c2008-08-27 23:52:12 +00002151 JTCases.push_back(JumpTableBlock(JTH, JT));
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00002152
Anton Korobeynikovdd433212007-03-27 12:05:48 +00002153 return true;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00002154}
2155
2156/// handleBTSplitSwitchCase - emit comparison and split binary search tree into
2157/// 2 subtrees.
Anton Korobeynikovdd433212007-03-27 12:05:48 +00002158bool SelectionDAGLowering::handleBTSplitSwitchCase(CaseRec& CR,
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00002159 CaseRecVector& WorkList,
2160 Value* SV,
2161 MachineBasicBlock* Default) {
2162 // Get the MachineFunction which holds the current MBB. This is used when
2163 // inserting any additional MBBs necessary to represent the switch.
2164 MachineFunction *CurMF = CurMBB->getParent();
2165
2166 // Figure out which block is immediately after the current one.
2167 MachineBasicBlock *NextBlock = 0;
2168 MachineFunction::iterator BBI = CR.CaseBB;
2169
2170 if (++BBI != CurMBB->getParent()->end())
2171 NextBlock = BBI;
2172
2173 Case& FrontCase = *CR.Range.first;
2174 Case& BackCase = *(CR.Range.second-1);
2175 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
2176
2177 // Size is the number of Cases represented by this range.
2178 unsigned Size = CR.Range.second - CR.Range.first;
2179
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002180 int64_t First = cast<ConstantInt>(FrontCase.Low)->getSExtValue();
2181 int64_t Last = cast<ConstantInt>(BackCase.High)->getSExtValue();
Anton Korobeynikov4198c582007-04-09 12:31:58 +00002182 double FMetric = 0;
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002183 CaseItr Pivot = CR.Range.first + Size/2;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00002184
2185 // Select optimal pivot, maximizing sum density of LHS and RHS. This will
2186 // (heuristically) allow us to emit JumpTable's later.
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002187 uint64_t TSize = 0;
2188 for (CaseItr I = CR.Range.first, E = CR.Range.second;
2189 I!=E; ++I)
2190 TSize += I->size();
2191
2192 uint64_t LSize = FrontCase.size();
2193 uint64_t RSize = TSize-LSize;
Anton Korobeynikov4198c582007-04-09 12:31:58 +00002194 DOUT << "Selecting best pivot: \n"
2195 << "First: " << First << ", Last: " << Last <<"\n"
2196 << "LSize: " << LSize << ", RSize: " << RSize << "\n";
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00002197 for (CaseItr I = CR.Range.first, J=I+1, E = CR.Range.second;
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002198 J!=E; ++I, ++J) {
2199 int64_t LEnd = cast<ConstantInt>(I->High)->getSExtValue();
2200 int64_t RBegin = cast<ConstantInt>(J->Low)->getSExtValue();
Anton Korobeynikov4198c582007-04-09 12:31:58 +00002201 assert((RBegin-LEnd>=1) && "Invalid case distance");
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00002202 double LDensity = (double)LSize / (double)((LEnd - First) + 1ULL);
2203 double RDensity = (double)RSize / (double)((Last - RBegin) + 1ULL);
Anton Korobeynikov54e2b142007-04-09 21:57:03 +00002204 double Metric = Log2_64(RBegin-LEnd)*(LDensity+RDensity);
Anton Korobeynikov4198c582007-04-09 12:31:58 +00002205 // Should always split in some non-trivial place
2206 DOUT <<"=>Step\n"
2207 << "LEnd: " << LEnd << ", RBegin: " << RBegin << "\n"
2208 << "LDensity: " << LDensity << ", RDensity: " << RDensity << "\n"
2209 << "Metric: " << Metric << "\n";
2210 if (FMetric < Metric) {
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00002211 Pivot = J;
Anton Korobeynikov4198c582007-04-09 12:31:58 +00002212 FMetric = Metric;
2213 DOUT << "Current metric set to: " << FMetric << "\n";
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00002214 }
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002215
2216 LSize += J->size();
2217 RSize -= J->size();
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00002218 }
Anton Korobeynikov7294b582007-05-09 20:07:08 +00002219 if (areJTsAllowed(TLI)) {
2220 // If our case is dense we *really* should handle it earlier!
2221 assert((FMetric > 0) && "Should handle dense range earlier!");
2222 } else {
2223 Pivot = CR.Range.first + Size/2;
2224 }
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00002225
2226 CaseRange LHSR(CR.Range.first, Pivot);
2227 CaseRange RHSR(Pivot, CR.Range.second);
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002228 Constant *C = Pivot->Low;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00002229 MachineBasicBlock *FalseBB = 0, *TrueBB = 0;
2230
2231 // We know that we branch to the LHS if the Value being switched on is
2232 // less than the Pivot value, C. We use this to optimize our binary
2233 // tree a bit, by recognizing that if SV is greater than or equal to the
2234 // LHS's Case Value, and that Case Value is exactly one less than the
2235 // Pivot's Value, then we can branch directly to the LHS's Target,
2236 // rather than creating a leaf node for it.
2237 if ((LHSR.second - LHSR.first) == 1 &&
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002238 LHSR.first->High == CR.GE &&
2239 cast<ConstantInt>(C)->getSExtValue() ==
2240 (cast<ConstantInt>(CR.GE)->getSExtValue() + 1LL)) {
2241 TrueBB = LHSR.first->BB;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00002242 } else {
Dan Gohman0e5f1302008-07-07 23:02:41 +00002243 TrueBB = CurMF->CreateMachineBasicBlock(LLVMBB);
2244 CurMF->insert(BBI, TrueBB);
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00002245 WorkList.push_back(CaseRec(TrueBB, C, CR.GE, LHSR));
2246 }
2247
2248 // Similar to the optimization above, if the Value being switched on is
2249 // known to be less than the Constant CR.LT, and the current Case Value
2250 // is CR.LT - 1, then we can branch directly to the target block for
2251 // the current Case Value, rather than emitting a RHS leaf node for it.
2252 if ((RHSR.second - RHSR.first) == 1 && CR.LT &&
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002253 cast<ConstantInt>(RHSR.first->Low)->getSExtValue() ==
2254 (cast<ConstantInt>(CR.LT)->getSExtValue() - 1LL)) {
2255 FalseBB = RHSR.first->BB;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00002256 } else {
Dan Gohman0e5f1302008-07-07 23:02:41 +00002257 FalseBB = CurMF->CreateMachineBasicBlock(LLVMBB);
2258 CurMF->insert(BBI, FalseBB);
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00002259 WorkList.push_back(CaseRec(FalseBB,CR.LT,C,RHSR));
2260 }
2261
2262 // Create a CaseBlock record representing a conditional branch to
2263 // the LHS node if the value being switched on SV is less than C.
2264 // Otherwise, branch to LHS.
Dan Gohman7c3234c2008-08-27 23:52:12 +00002265 CaseBlock CB(ISD::SETLT, SV, C, NULL, TrueBB, FalseBB, CR.CaseBB);
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00002266
2267 if (CR.CaseBB == CurMBB)
2268 visitSwitchCase(CB);
2269 else
2270 SwitchCases.push_back(CB);
Anton Korobeynikovdd433212007-03-27 12:05:48 +00002271
2272 return true;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00002273}
2274
Anton Korobeynikov4198c582007-04-09 12:31:58 +00002275/// handleBitTestsSwitchCase - if current case range has few destination and
2276/// range span less, than machine word bitwidth, encode case range into series
2277/// of masks and emit bit tests with these masks.
2278bool SelectionDAGLowering::handleBitTestsSwitchCase(CaseRec& CR,
2279 CaseRecVector& WorkList,
2280 Value* SV,
Chris Lattner3ff98172007-04-14 02:26:56 +00002281 MachineBasicBlock* Default){
Duncan Sands83ec4b62008-06-06 12:08:01 +00002282 unsigned IntPtrBits = TLI.getPointerTy().getSizeInBits();
Anton Korobeynikov4198c582007-04-09 12:31:58 +00002283
2284 Case& FrontCase = *CR.Range.first;
2285 Case& BackCase = *(CR.Range.second-1);
2286
2287 // Get the MachineFunction which holds the current MBB. This is used when
2288 // inserting any additional MBBs necessary to represent the switch.
2289 MachineFunction *CurMF = CurMBB->getParent();
2290
2291 unsigned numCmps = 0;
2292 for (CaseItr I = CR.Range.first, E = CR.Range.second;
2293 I!=E; ++I) {
2294 // Single case counts one, case range - two.
2295 if (I->Low == I->High)
2296 numCmps +=1;
2297 else
2298 numCmps +=2;
2299 }
2300
2301 // Count unique destinations
2302 SmallSet<MachineBasicBlock*, 4> Dests;
2303 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
2304 Dests.insert(I->BB);
2305 if (Dests.size() > 3)
2306 // Don't bother the code below, if there are too much unique destinations
2307 return false;
2308 }
2309 DOUT << "Total number of unique destinations: " << Dests.size() << "\n"
2310 << "Total number of comparisons: " << numCmps << "\n";
2311
2312 // Compute span of values.
2313 Constant* minValue = FrontCase.Low;
2314 Constant* maxValue = BackCase.High;
2315 uint64_t range = cast<ConstantInt>(maxValue)->getSExtValue() -
2316 cast<ConstantInt>(minValue)->getSExtValue();
2317 DOUT << "Compare range: " << range << "\n"
2318 << "Low bound: " << cast<ConstantInt>(minValue)->getSExtValue() << "\n"
2319 << "High bound: " << cast<ConstantInt>(maxValue)->getSExtValue() << "\n";
2320
Anton Korobeynikovab8fd402007-04-26 20:44:04 +00002321 if (range>=IntPtrBits ||
Anton Korobeynikov4198c582007-04-09 12:31:58 +00002322 (!(Dests.size() == 1 && numCmps >= 3) &&
2323 !(Dests.size() == 2 && numCmps >= 5) &&
2324 !(Dests.size() >= 3 && numCmps >= 6)))
2325 return false;
2326
2327 DOUT << "Emitting bit tests\n";
2328 int64_t lowBound = 0;
2329
2330 // Optimize the case where all the case values fit in a
2331 // word without having to subtract minValue. In this case,
2332 // we can optimize away the subtraction.
2333 if (cast<ConstantInt>(minValue)->getSExtValue() >= 0 &&
Anton Korobeynikove01017b2007-04-14 13:25:55 +00002334 cast<ConstantInt>(maxValue)->getSExtValue() < IntPtrBits) {
Anton Korobeynikov4198c582007-04-09 12:31:58 +00002335 range = cast<ConstantInt>(maxValue)->getSExtValue();
2336 } else {
2337 lowBound = cast<ConstantInt>(minValue)->getSExtValue();
2338 }
2339
2340 CaseBitsVector CasesBits;
2341 unsigned i, count = 0;
2342
2343 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
2344 MachineBasicBlock* Dest = I->BB;
2345 for (i = 0; i < count; ++i)
2346 if (Dest == CasesBits[i].BB)
2347 break;
2348
2349 if (i == count) {
2350 assert((count < 3) && "Too much destinations to test!");
2351 CasesBits.push_back(CaseBits(0, Dest, 0));
2352 count++;
2353 }
2354
2355 uint64_t lo = cast<ConstantInt>(I->Low)->getSExtValue() - lowBound;
2356 uint64_t hi = cast<ConstantInt>(I->High)->getSExtValue() - lowBound;
2357
2358 for (uint64_t j = lo; j <= hi; j++) {
Anton Korobeynikove01017b2007-04-14 13:25:55 +00002359 CasesBits[i].Mask |= 1ULL << j;
Anton Korobeynikov4198c582007-04-09 12:31:58 +00002360 CasesBits[i].Bits++;
2361 }
2362
2363 }
2364 std::sort(CasesBits.begin(), CasesBits.end(), CaseBitsCmp());
2365
Dan Gohman7c3234c2008-08-27 23:52:12 +00002366 BitTestInfo BTC;
Anton Korobeynikov4198c582007-04-09 12:31:58 +00002367
2368 // Figure out which block is immediately after the current one.
2369 MachineFunction::iterator BBI = CR.CaseBB;
2370 ++BBI;
2371
2372 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
2373
2374 DOUT << "Cases:\n";
2375 for (unsigned i = 0, e = CasesBits.size(); i!=e; ++i) {
2376 DOUT << "Mask: " << CasesBits[i].Mask << ", Bits: " << CasesBits[i].Bits
2377 << ", BB: " << CasesBits[i].BB << "\n";
2378
Dan Gohman0e5f1302008-07-07 23:02:41 +00002379 MachineBasicBlock *CaseBB = CurMF->CreateMachineBasicBlock(LLVMBB);
2380 CurMF->insert(BBI, CaseBB);
Dan Gohman7c3234c2008-08-27 23:52:12 +00002381 BTC.push_back(BitTestCase(CasesBits[i].Mask,
2382 CaseBB,
2383 CasesBits[i].BB));
Anton Korobeynikov4198c582007-04-09 12:31:58 +00002384 }
2385
Dan Gohman7c3234c2008-08-27 23:52:12 +00002386 BitTestBlock BTB(lowBound, range, SV,
2387 -1U, (CR.CaseBB == CurMBB),
2388 CR.CaseBB, Default, BTC);
Anton Korobeynikov4198c582007-04-09 12:31:58 +00002389
2390 if (CR.CaseBB == CurMBB)
2391 visitBitTestHeader(BTB);
2392
2393 BitTestCases.push_back(BTB);
2394
2395 return true;
2396}
2397
2398
Dan Gohman86e1ebf2008-03-27 19:56:19 +00002399/// Clusterify - Transform simple list of Cases into list of CaseRange's
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002400unsigned SelectionDAGLowering::Clusterify(CaseVector& Cases,
2401 const SwitchInst& SI) {
2402 unsigned numCmps = 0;
2403
2404 // Start with "simple" cases
2405 for (unsigned i = 1; i < SI.getNumSuccessors(); ++i) {
2406 MachineBasicBlock *SMBB = FuncInfo.MBBMap[SI.getSuccessor(i)];
2407 Cases.push_back(Case(SI.getSuccessorValue(i),
2408 SI.getSuccessorValue(i),
2409 SMBB));
2410 }
Chris Lattnerb3d9cdb2007-11-27 06:14:32 +00002411 std::sort(Cases.begin(), Cases.end(), CaseCmp());
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002412
2413 // Merge case into clusters
2414 if (Cases.size()>=2)
David Greenea2a48852007-06-29 03:42:23 +00002415 // Must recompute end() each iteration because it may be
2416 // invalidated by erase if we hold on to it
Chris Lattner27a6c732007-11-24 07:07:01 +00002417 for (CaseItr I=Cases.begin(), J=++(Cases.begin()); J!=Cases.end(); ) {
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002418 int64_t nextValue = cast<ConstantInt>(J->Low)->getSExtValue();
2419 int64_t currentValue = cast<ConstantInt>(I->High)->getSExtValue();
2420 MachineBasicBlock* nextBB = J->BB;
2421 MachineBasicBlock* currentBB = I->BB;
2422
2423 // If the two neighboring cases go to the same destination, merge them
2424 // into a single case.
2425 if ((nextValue-currentValue==1) && (currentBB == nextBB)) {
2426 I->High = J->High;
2427 J = Cases.erase(J);
2428 } else {
2429 I = J++;
2430 }
2431 }
2432
2433 for (CaseItr I=Cases.begin(), E=Cases.end(); I!=E; ++I, ++numCmps) {
2434 if (I->Low != I->High)
2435 // A range counts double, since it requires two compares.
2436 ++numCmps;
2437 }
2438
2439 return numCmps;
2440}
2441
2442void SelectionDAGLowering::visitSwitch(SwitchInst &SI) {
Nate Begemanf15485a2006-03-27 01:32:24 +00002443 // Figure out which block is immediately after the current one.
2444 MachineBasicBlock *NextBlock = 0;
2445 MachineFunction::iterator BBI = CurMBB;
Bill Wendlingc70ddad2006-10-19 21:46:38 +00002446
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002447 MachineBasicBlock *Default = FuncInfo.MBBMap[SI.getDefaultDest()];
Chris Lattnerd2c1d222006-10-22 21:36:53 +00002448
Nate Begemanf15485a2006-03-27 01:32:24 +00002449 // If there is only the default destination, branch to it if it is not the
2450 // next basic block. Otherwise, just fall through.
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002451 if (SI.getNumOperands() == 2) {
Nate Begemanf15485a2006-03-27 01:32:24 +00002452 // Update machine-CFG edges.
Bill Wendlingc70ddad2006-10-19 21:46:38 +00002453
Nate Begemanf15485a2006-03-27 01:32:24 +00002454 // If this is not a fall-through branch, emit the branch.
Owen Anderson2d389e82008-06-07 00:00:23 +00002455 CurMBB->addSuccessor(Default);
Chris Lattnerd2c1d222006-10-22 21:36:53 +00002456 if (Default != NextBlock)
Dan Gohman86e1ebf2008-03-27 19:56:19 +00002457 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getControlRoot(),
Chris Lattnerd2c1d222006-10-22 21:36:53 +00002458 DAG.getBasicBlock(Default)));
Owen Anderson2d389e82008-06-07 00:00:23 +00002459
Nate Begemanf15485a2006-03-27 01:32:24 +00002460 return;
2461 }
2462
2463 // If there are any non-default case statements, create a vector of Cases
2464 // representing each one, and sort the vector so that we can efficiently
2465 // create a binary search tree from them.
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002466 CaseVector Cases;
2467 unsigned numCmps = Clusterify(Cases, SI);
2468 DOUT << "Clusterify finished. Total clusters: " << Cases.size()
2469 << ". Total compares: " << numCmps << "\n";
Bill Wendlingc70ddad2006-10-19 21:46:38 +00002470
Nate Begemanf15485a2006-03-27 01:32:24 +00002471 // Get the Value to be switched on and default basic blocks, which will be
2472 // inserted into CaseBlock records, representing basic blocks in the binary
2473 // search tree.
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002474 Value *SV = SI.getOperand(0);
Nate Begeman37efe672006-04-22 18:53:45 +00002475
Nate Begemanf15485a2006-03-27 01:32:24 +00002476 // Push the initial CaseRec onto the worklist
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00002477 CaseRecVector WorkList;
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00002478 WorkList.push_back(CaseRec(CurMBB,0,0,CaseRange(Cases.begin(),Cases.end())));
2479
2480 while (!WorkList.empty()) {
Nate Begemanf15485a2006-03-27 01:32:24 +00002481 // Grab a record representing a case range to process off the worklist
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00002482 CaseRec CR = WorkList.back();
2483 WorkList.pop_back();
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00002484
Anton Korobeynikov4198c582007-04-09 12:31:58 +00002485 if (handleBitTestsSwitchCase(CR, WorkList, SV, Default))
2486 continue;
2487
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00002488 // If the range has few cases (two or less) emit a series of specific
2489 // tests.
Anton Korobeynikovdd433212007-03-27 12:05:48 +00002490 if (handleSmallSwitchRange(CR, WorkList, SV, Default))
2491 continue;
2492
Anton Korobeynikov4198c582007-04-09 12:31:58 +00002493 // If the switch has more than 5 blocks, and at least 40% dense, and the
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00002494 // target supports indirect branches, then emit a jump table rather than
2495 // lowering the switch to a binary tree of conditional branches.
Anton Korobeynikovdd433212007-03-27 12:05:48 +00002496 if (handleJTSwitchCase(CR, WorkList, SV, Default))
2497 continue;
2498
2499 // Emit binary tree. We need to pick a pivot, and push left and right ranges
2500 // onto the worklist. Leafs are handled via handleSmallSwitchRange() call.
2501 handleBTSplitSwitchCase(CR, WorkList, SV, Default);
Nate Begemanf15485a2006-03-27 01:32:24 +00002502 }
2503}
2504
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00002505
Chris Lattnerb9fccc42005-04-02 05:04:50 +00002506void SelectionDAGLowering::visitSub(User &I) {
2507 // -0.0 - X --> fneg
Reid Spencer24d6da52007-01-21 00:29:26 +00002508 const Type *Ty = I.getType();
Reid Spencer9d6565a2007-02-15 02:26:10 +00002509 if (isa<VectorType>(Ty)) {
Dan Gohman7f321562007-06-25 16:23:39 +00002510 if (ConstantVector *CV = dyn_cast<ConstantVector>(I.getOperand(0))) {
2511 const VectorType *DestTy = cast<VectorType>(I.getType());
2512 const Type *ElTy = DestTy->getElementType();
Evan Chengc45453f2007-06-29 21:44:35 +00002513 if (ElTy->isFloatingPoint()) {
2514 unsigned VL = DestTy->getNumElements();
Dale Johannesen9e3d3ab2007-09-14 22:26:36 +00002515 std::vector<Constant*> NZ(VL, ConstantFP::getNegativeZero(ElTy));
Evan Chengc45453f2007-06-29 21:44:35 +00002516 Constant *CNZ = ConstantVector::get(&NZ[0], NZ.size());
2517 if (CV == CNZ) {
Dan Gohman475871a2008-07-27 21:46:04 +00002518 SDValue Op2 = getValue(I.getOperand(1));
Evan Chengc45453f2007-06-29 21:44:35 +00002519 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
2520 return;
2521 }
Dan Gohman7f321562007-06-25 16:23:39 +00002522 }
2523 }
2524 }
2525 if (Ty->isFloatingPoint()) {
Chris Lattner01b3d732005-09-28 22:28:18 +00002526 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
Dale Johannesen9e3d3ab2007-09-14 22:26:36 +00002527 if (CFP->isExactlyValue(ConstantFP::getNegativeZero(Ty)->getValueAPF())) {
Dan Gohman475871a2008-07-27 21:46:04 +00002528 SDValue Op2 = getValue(I.getOperand(1));
Chris Lattner01b3d732005-09-28 22:28:18 +00002529 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
2530 return;
2531 }
Dan Gohman7f321562007-06-25 16:23:39 +00002532 }
2533
2534 visitBinary(I, Ty->isFPOrFPVector() ? ISD::FSUB : ISD::SUB);
Chris Lattnerb9fccc42005-04-02 05:04:50 +00002535}
2536
Dan Gohman7f321562007-06-25 16:23:39 +00002537void SelectionDAGLowering::visitBinary(User &I, unsigned OpCode) {
Dan Gohman475871a2008-07-27 21:46:04 +00002538 SDValue Op1 = getValue(I.getOperand(0));
2539 SDValue Op2 = getValue(I.getOperand(1));
Reid Spencer24d6da52007-01-21 00:29:26 +00002540
2541 setValue(&I, DAG.getNode(OpCode, Op1.getValueType(), Op1, Op2));
Reid Spencer1628cec2006-10-26 06:15:43 +00002542}
2543
Nate Begemane21ea612005-11-18 07:42:56 +00002544void SelectionDAGLowering::visitShift(User &I, unsigned Opcode) {
Dan Gohman475871a2008-07-27 21:46:04 +00002545 SDValue Op1 = getValue(I.getOperand(0));
2546 SDValue Op2 = getValue(I.getOperand(1));
Nate Begeman5bc1ea02008-07-29 15:49:41 +00002547 if (!isa<VectorType>(I.getType())) {
2548 if (TLI.getShiftAmountTy().bitsLT(Op2.getValueType()))
2549 Op2 = DAG.getNode(ISD::TRUNCATE, TLI.getShiftAmountTy(), Op2);
2550 else if (TLI.getShiftAmountTy().bitsGT(Op2.getValueType()))
2551 Op2 = DAG.getNode(ISD::ANY_EXTEND, TLI.getShiftAmountTy(), Op2);
2552 }
Nate Begemane21ea612005-11-18 07:42:56 +00002553
Chris Lattner1c08c712005-01-07 07:47:53 +00002554 setValue(&I, DAG.getNode(Opcode, Op1.getValueType(), Op1, Op2));
2555}
2556
Reid Spencer45fb3f32006-11-20 01:22:35 +00002557void SelectionDAGLowering::visitICmp(User &I) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002558 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
2559 if (ICmpInst *IC = dyn_cast<ICmpInst>(&I))
2560 predicate = IC->getPredicate();
2561 else if (ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
2562 predicate = ICmpInst::Predicate(IC->getPredicate());
Dan Gohman475871a2008-07-27 21:46:04 +00002563 SDValue Op1 = getValue(I.getOperand(0));
2564 SDValue Op2 = getValue(I.getOperand(1));
Reid Spencer45fb3f32006-11-20 01:22:35 +00002565 ISD::CondCode Opcode;
Reid Spencere4d87aa2006-12-23 06:05:41 +00002566 switch (predicate) {
Reid Spencer45fb3f32006-11-20 01:22:35 +00002567 case ICmpInst::ICMP_EQ : Opcode = ISD::SETEQ; break;
2568 case ICmpInst::ICMP_NE : Opcode = ISD::SETNE; break;
2569 case ICmpInst::ICMP_UGT : Opcode = ISD::SETUGT; break;
2570 case ICmpInst::ICMP_UGE : Opcode = ISD::SETUGE; break;
2571 case ICmpInst::ICMP_ULT : Opcode = ISD::SETULT; break;
2572 case ICmpInst::ICMP_ULE : Opcode = ISD::SETULE; break;
2573 case ICmpInst::ICMP_SGT : Opcode = ISD::SETGT; break;
2574 case ICmpInst::ICMP_SGE : Opcode = ISD::SETGE; break;
2575 case ICmpInst::ICMP_SLT : Opcode = ISD::SETLT; break;
2576 case ICmpInst::ICMP_SLE : Opcode = ISD::SETLE; break;
2577 default:
2578 assert(!"Invalid ICmp predicate value");
2579 Opcode = ISD::SETEQ;
2580 break;
2581 }
2582 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Opcode));
2583}
2584
2585void SelectionDAGLowering::visitFCmp(User &I) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002586 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
2587 if (FCmpInst *FC = dyn_cast<FCmpInst>(&I))
2588 predicate = FC->getPredicate();
2589 else if (ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
2590 predicate = FCmpInst::Predicate(FC->getPredicate());
Dan Gohman475871a2008-07-27 21:46:04 +00002591 SDValue Op1 = getValue(I.getOperand(0));
2592 SDValue Op2 = getValue(I.getOperand(1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00002593 ISD::CondCode Condition, FOC, FPC;
2594 switch (predicate) {
2595 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
2596 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
2597 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
2598 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
2599 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
2600 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
2601 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
Dan Gohmancba3b442008-05-01 23:40:44 +00002602 case FCmpInst::FCMP_ORD: FOC = FPC = ISD::SETO; break;
2603 case FCmpInst::FCMP_UNO: FOC = FPC = ISD::SETUO; break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00002604 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
2605 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
2606 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
2607 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
2608 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
2609 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
2610 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
2611 default:
2612 assert(!"Invalid FCmp predicate value");
2613 FOC = FPC = ISD::SETFALSE;
2614 break;
2615 }
2616 if (FiniteOnlyFPMath())
2617 Condition = FOC;
2618 else
2619 Condition = FPC;
2620 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Condition));
Chris Lattner1c08c712005-01-07 07:47:53 +00002621}
2622
Nate Begemanb43e9c12008-05-12 19:40:03 +00002623void SelectionDAGLowering::visitVICmp(User &I) {
2624 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
2625 if (VICmpInst *IC = dyn_cast<VICmpInst>(&I))
2626 predicate = IC->getPredicate();
2627 else if (ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
2628 predicate = ICmpInst::Predicate(IC->getPredicate());
Dan Gohman475871a2008-07-27 21:46:04 +00002629 SDValue Op1 = getValue(I.getOperand(0));
2630 SDValue Op2 = getValue(I.getOperand(1));
Nate Begemanb43e9c12008-05-12 19:40:03 +00002631 ISD::CondCode Opcode;
2632 switch (predicate) {
2633 case ICmpInst::ICMP_EQ : Opcode = ISD::SETEQ; break;
2634 case ICmpInst::ICMP_NE : Opcode = ISD::SETNE; break;
2635 case ICmpInst::ICMP_UGT : Opcode = ISD::SETUGT; break;
2636 case ICmpInst::ICMP_UGE : Opcode = ISD::SETUGE; break;
2637 case ICmpInst::ICMP_ULT : Opcode = ISD::SETULT; break;
2638 case ICmpInst::ICMP_ULE : Opcode = ISD::SETULE; break;
2639 case ICmpInst::ICMP_SGT : Opcode = ISD::SETGT; break;
2640 case ICmpInst::ICMP_SGE : Opcode = ISD::SETGE; break;
2641 case ICmpInst::ICMP_SLT : Opcode = ISD::SETLT; break;
2642 case ICmpInst::ICMP_SLE : Opcode = ISD::SETLE; break;
2643 default:
2644 assert(!"Invalid ICmp predicate value");
2645 Opcode = ISD::SETEQ;
2646 break;
2647 }
2648 setValue(&I, DAG.getVSetCC(Op1.getValueType(), Op1, Op2, Opcode));
2649}
2650
2651void SelectionDAGLowering::visitVFCmp(User &I) {
2652 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
2653 if (VFCmpInst *FC = dyn_cast<VFCmpInst>(&I))
2654 predicate = FC->getPredicate();
2655 else if (ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
2656 predicate = FCmpInst::Predicate(FC->getPredicate());
Dan Gohman475871a2008-07-27 21:46:04 +00002657 SDValue Op1 = getValue(I.getOperand(0));
2658 SDValue Op2 = getValue(I.getOperand(1));
Nate Begemanb43e9c12008-05-12 19:40:03 +00002659 ISD::CondCode Condition, FOC, FPC;
2660 switch (predicate) {
2661 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
2662 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
2663 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
2664 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
2665 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
2666 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
2667 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
2668 case FCmpInst::FCMP_ORD: FOC = FPC = ISD::SETO; break;
2669 case FCmpInst::FCMP_UNO: FOC = FPC = ISD::SETUO; break;
2670 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
2671 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
2672 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
2673 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
2674 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
2675 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
2676 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
2677 default:
2678 assert(!"Invalid VFCmp predicate value");
2679 FOC = FPC = ISD::SETFALSE;
2680 break;
2681 }
2682 if (FiniteOnlyFPMath())
2683 Condition = FOC;
2684 else
2685 Condition = FPC;
2686
Duncan Sands83ec4b62008-06-06 12:08:01 +00002687 MVT DestVT = TLI.getValueType(I.getType());
Nate Begemanb43e9c12008-05-12 19:40:03 +00002688
2689 setValue(&I, DAG.getVSetCC(DestVT, Op1, Op2, Condition));
2690}
2691
Chris Lattner1c08c712005-01-07 07:47:53 +00002692void SelectionDAGLowering::visitSelect(User &I) {
Dan Gohman475871a2008-07-27 21:46:04 +00002693 SDValue Cond = getValue(I.getOperand(0));
2694 SDValue TrueVal = getValue(I.getOperand(1));
2695 SDValue FalseVal = getValue(I.getOperand(2));
Dan Gohman7f321562007-06-25 16:23:39 +00002696 setValue(&I, DAG.getNode(ISD::SELECT, TrueVal.getValueType(), Cond,
2697 TrueVal, FalseVal));
Chris Lattner1c08c712005-01-07 07:47:53 +00002698}
2699
Reid Spencer3da59db2006-11-27 01:05:10 +00002700
2701void SelectionDAGLowering::visitTrunc(User &I) {
2702 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
Dan Gohman475871a2008-07-27 21:46:04 +00002703 SDValue N = getValue(I.getOperand(0));
Duncan Sands83ec4b62008-06-06 12:08:01 +00002704 MVT DestVT = TLI.getValueType(I.getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00002705 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
2706}
2707
2708void SelectionDAGLowering::visitZExt(User &I) {
2709 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2710 // ZExt also can't be a cast to bool for same reason. So, nothing much to do
Dan Gohman475871a2008-07-27 21:46:04 +00002711 SDValue N = getValue(I.getOperand(0));
Duncan Sands83ec4b62008-06-06 12:08:01 +00002712 MVT DestVT = TLI.getValueType(I.getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00002713 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
2714}
2715
2716void SelectionDAGLowering::visitSExt(User &I) {
2717 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2718 // SExt also can't be a cast to bool for same reason. So, nothing much to do
Dan Gohman475871a2008-07-27 21:46:04 +00002719 SDValue N = getValue(I.getOperand(0));
Duncan Sands83ec4b62008-06-06 12:08:01 +00002720 MVT DestVT = TLI.getValueType(I.getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00002721 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, DestVT, N));
2722}
2723
2724void SelectionDAGLowering::visitFPTrunc(User &I) {
2725 // FPTrunc is never a no-op cast, no need to check
Dan Gohman475871a2008-07-27 21:46:04 +00002726 SDValue N = getValue(I.getOperand(0));
Duncan Sands83ec4b62008-06-06 12:08:01 +00002727 MVT DestVT = TLI.getValueType(I.getType());
Chris Lattner0bd48932008-01-17 07:00:52 +00002728 setValue(&I, DAG.getNode(ISD::FP_ROUND, DestVT, N, DAG.getIntPtrConstant(0)));
Reid Spencer3da59db2006-11-27 01:05:10 +00002729}
2730
2731void SelectionDAGLowering::visitFPExt(User &I){
2732 // FPTrunc is never a no-op cast, no need to check
Dan Gohman475871a2008-07-27 21:46:04 +00002733 SDValue N = getValue(I.getOperand(0));
Duncan Sands83ec4b62008-06-06 12:08:01 +00002734 MVT DestVT = TLI.getValueType(I.getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00002735 setValue(&I, DAG.getNode(ISD::FP_EXTEND, DestVT, N));
2736}
2737
2738void SelectionDAGLowering::visitFPToUI(User &I) {
2739 // FPToUI is never a no-op cast, no need to check
Dan Gohman475871a2008-07-27 21:46:04 +00002740 SDValue N = getValue(I.getOperand(0));
Duncan Sands83ec4b62008-06-06 12:08:01 +00002741 MVT DestVT = TLI.getValueType(I.getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00002742 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, DestVT, N));
2743}
2744
2745void SelectionDAGLowering::visitFPToSI(User &I) {
2746 // FPToSI is never a no-op cast, no need to check
Dan Gohman475871a2008-07-27 21:46:04 +00002747 SDValue N = getValue(I.getOperand(0));
Duncan Sands83ec4b62008-06-06 12:08:01 +00002748 MVT DestVT = TLI.getValueType(I.getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00002749 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, DestVT, N));
2750}
2751
2752void SelectionDAGLowering::visitUIToFP(User &I) {
2753 // UIToFP is never a no-op cast, no need to check
Dan Gohman475871a2008-07-27 21:46:04 +00002754 SDValue N = getValue(I.getOperand(0));
Duncan Sands83ec4b62008-06-06 12:08:01 +00002755 MVT DestVT = TLI.getValueType(I.getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00002756 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, DestVT, N));
2757}
2758
2759void SelectionDAGLowering::visitSIToFP(User &I){
2760 // UIToFP is never a no-op cast, no need to check
Dan Gohman475871a2008-07-27 21:46:04 +00002761 SDValue N = getValue(I.getOperand(0));
Duncan Sands83ec4b62008-06-06 12:08:01 +00002762 MVT DestVT = TLI.getValueType(I.getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00002763 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, DestVT, N));
2764}
2765
2766void SelectionDAGLowering::visitPtrToInt(User &I) {
2767 // What to do depends on the size of the integer and the size of the pointer.
2768 // We can either truncate, zero extend, or no-op, accordingly.
Dan Gohman475871a2008-07-27 21:46:04 +00002769 SDValue N = getValue(I.getOperand(0));
Duncan Sands83ec4b62008-06-06 12:08:01 +00002770 MVT SrcVT = N.getValueType();
2771 MVT DestVT = TLI.getValueType(I.getType());
Dan Gohman475871a2008-07-27 21:46:04 +00002772 SDValue Result;
Duncan Sands8e4eb092008-06-08 20:54:56 +00002773 if (DestVT.bitsLT(SrcVT))
Reid Spencer3da59db2006-11-27 01:05:10 +00002774 Result = DAG.getNode(ISD::TRUNCATE, DestVT, N);
2775 else
2776 // Note: ZERO_EXTEND can handle cases where the sizes are equal too
2777 Result = DAG.getNode(ISD::ZERO_EXTEND, DestVT, N);
2778 setValue(&I, Result);
2779}
Chris Lattner1c08c712005-01-07 07:47:53 +00002780
Reid Spencer3da59db2006-11-27 01:05:10 +00002781void SelectionDAGLowering::visitIntToPtr(User &I) {
2782 // What to do depends on the size of the integer and the size of the pointer.
2783 // We can either truncate, zero extend, or no-op, accordingly.
Dan Gohman475871a2008-07-27 21:46:04 +00002784 SDValue N = getValue(I.getOperand(0));
Duncan Sands83ec4b62008-06-06 12:08:01 +00002785 MVT SrcVT = N.getValueType();
2786 MVT DestVT = TLI.getValueType(I.getType());
Duncan Sands8e4eb092008-06-08 20:54:56 +00002787 if (DestVT.bitsLT(SrcVT))
Reid Spencer3da59db2006-11-27 01:05:10 +00002788 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
2789 else
2790 // Note: ZERO_EXTEND can handle cases where the sizes are equal too
2791 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
2792}
2793
2794void SelectionDAGLowering::visitBitCast(User &I) {
Dan Gohman475871a2008-07-27 21:46:04 +00002795 SDValue N = getValue(I.getOperand(0));
Duncan Sands83ec4b62008-06-06 12:08:01 +00002796 MVT DestVT = TLI.getValueType(I.getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00002797
2798 // BitCast assures us that source and destination are the same size so this
2799 // is either a BIT_CONVERT or a no-op.
2800 if (DestVT != N.getValueType())
2801 setValue(&I, DAG.getNode(ISD::BIT_CONVERT, DestVT, N)); // convert types
2802 else
2803 setValue(&I, N); // noop cast.
Chris Lattner1c08c712005-01-07 07:47:53 +00002804}
2805
Chris Lattner2bbd8102006-03-29 00:11:43 +00002806void SelectionDAGLowering::visitInsertElement(User &I) {
Dan Gohman475871a2008-07-27 21:46:04 +00002807 SDValue InVec = getValue(I.getOperand(0));
2808 SDValue InVal = getValue(I.getOperand(1));
2809 SDValue InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
Chris Lattnerc7029802006-03-18 01:44:44 +00002810 getValue(I.getOperand(2)));
2811
Dan Gohman7f321562007-06-25 16:23:39 +00002812 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT,
2813 TLI.getValueType(I.getType()),
2814 InVec, InVal, InIdx));
Chris Lattnerc7029802006-03-18 01:44:44 +00002815}
2816
Chris Lattner2bbd8102006-03-29 00:11:43 +00002817void SelectionDAGLowering::visitExtractElement(User &I) {
Dan Gohman475871a2008-07-27 21:46:04 +00002818 SDValue InVec = getValue(I.getOperand(0));
2819 SDValue InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
Chris Lattner384504c2006-03-21 20:44:12 +00002820 getValue(I.getOperand(1)));
Dan Gohman7f321562007-06-25 16:23:39 +00002821 setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
Chris Lattner384504c2006-03-21 20:44:12 +00002822 TLI.getValueType(I.getType()), InVec, InIdx));
2823}
Chris Lattnerc7029802006-03-18 01:44:44 +00002824
Chris Lattner3e104b12006-04-08 04:15:24 +00002825void SelectionDAGLowering::visitShuffleVector(User &I) {
Dan Gohman475871a2008-07-27 21:46:04 +00002826 SDValue V1 = getValue(I.getOperand(0));
2827 SDValue V2 = getValue(I.getOperand(1));
2828 SDValue Mask = getValue(I.getOperand(2));
Chris Lattner3e104b12006-04-08 04:15:24 +00002829
Dan Gohman7f321562007-06-25 16:23:39 +00002830 setValue(&I, DAG.getNode(ISD::VECTOR_SHUFFLE,
2831 TLI.getValueType(I.getType()),
2832 V1, V2, Mask));
Chris Lattner3e104b12006-04-08 04:15:24 +00002833}
2834
Dan Gohman1d685a42008-06-07 02:02:36 +00002835void SelectionDAGLowering::visitInsertValue(InsertValueInst &I) {
2836 const Value *Op0 = I.getOperand(0);
2837 const Value *Op1 = I.getOperand(1);
2838 const Type *AggTy = I.getType();
2839 const Type *ValTy = Op1->getType();
2840 bool IntoUndef = isa<UndefValue>(Op0);
2841 bool FromUndef = isa<UndefValue>(Op1);
2842
2843 unsigned LinearIndex = ComputeLinearIndex(TLI, AggTy,
2844 I.idx_begin(), I.idx_end());
2845
2846 SmallVector<MVT, 4> AggValueVTs;
2847 ComputeValueVTs(TLI, AggTy, AggValueVTs);
2848 SmallVector<MVT, 4> ValValueVTs;
2849 ComputeValueVTs(TLI, ValTy, ValValueVTs);
2850
2851 unsigned NumAggValues = AggValueVTs.size();
2852 unsigned NumValValues = ValValueVTs.size();
Dan Gohman475871a2008-07-27 21:46:04 +00002853 SmallVector<SDValue, 4> Values(NumAggValues);
Dan Gohman1d685a42008-06-07 02:02:36 +00002854
Dan Gohman475871a2008-07-27 21:46:04 +00002855 SDValue Agg = getValue(Op0);
2856 SDValue Val = getValue(Op1);
Dan Gohman1d685a42008-06-07 02:02:36 +00002857 unsigned i = 0;
2858 // Copy the beginning value(s) from the original aggregate.
2859 for (; i != LinearIndex; ++i)
2860 Values[i] = IntoUndef ? DAG.getNode(ISD::UNDEF, AggValueVTs[i]) :
Gabor Greif99a6cb92008-08-26 22:36:50 +00002861 SDValue(Agg.Val, Agg.getResNo() + i);
Dan Gohman1d685a42008-06-07 02:02:36 +00002862 // Copy values from the inserted value(s).
2863 for (; i != LinearIndex + NumValValues; ++i)
2864 Values[i] = FromUndef ? DAG.getNode(ISD::UNDEF, AggValueVTs[i]) :
Gabor Greif99a6cb92008-08-26 22:36:50 +00002865 SDValue(Val.Val, Val.getResNo() + i - LinearIndex);
Dan Gohman1d685a42008-06-07 02:02:36 +00002866 // Copy remaining value(s) from the original aggregate.
2867 for (; i != NumAggValues; ++i)
2868 Values[i] = IntoUndef ? DAG.getNode(ISD::UNDEF, AggValueVTs[i]) :
Gabor Greif99a6cb92008-08-26 22:36:50 +00002869 SDValue(Agg.Val, Agg.getResNo() + i);
Dan Gohman1d685a42008-06-07 02:02:36 +00002870
Duncan Sandsf9516202008-06-30 10:19:09 +00002871 setValue(&I, DAG.getMergeValues(DAG.getVTList(&AggValueVTs[0], NumAggValues),
2872 &Values[0], NumAggValues));
Dan Gohman041e2eb2008-05-15 19:50:34 +00002873}
2874
Dan Gohman1d685a42008-06-07 02:02:36 +00002875void SelectionDAGLowering::visitExtractValue(ExtractValueInst &I) {
2876 const Value *Op0 = I.getOperand(0);
2877 const Type *AggTy = Op0->getType();
2878 const Type *ValTy = I.getType();
2879 bool OutOfUndef = isa<UndefValue>(Op0);
2880
2881 unsigned LinearIndex = ComputeLinearIndex(TLI, AggTy,
2882 I.idx_begin(), I.idx_end());
2883
2884 SmallVector<MVT, 4> ValValueVTs;
2885 ComputeValueVTs(TLI, ValTy, ValValueVTs);
2886
2887 unsigned NumValValues = ValValueVTs.size();
Dan Gohman475871a2008-07-27 21:46:04 +00002888 SmallVector<SDValue, 4> Values(NumValValues);
Dan Gohman1d685a42008-06-07 02:02:36 +00002889
Dan Gohman475871a2008-07-27 21:46:04 +00002890 SDValue Agg = getValue(Op0);
Dan Gohman1d685a42008-06-07 02:02:36 +00002891 // Copy out the selected value(s).
2892 for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
2893 Values[i - LinearIndex] =
Gabor Greif99a6cb92008-08-26 22:36:50 +00002894 OutOfUndef ? DAG.getNode(ISD::UNDEF, Agg.Val->getValueType(Agg.getResNo() + i)) :
2895 SDValue(Agg.Val, Agg.getResNo() + i);
Dan Gohman1d685a42008-06-07 02:02:36 +00002896
Duncan Sandsf9516202008-06-30 10:19:09 +00002897 setValue(&I, DAG.getMergeValues(DAG.getVTList(&ValValueVTs[0], NumValValues),
2898 &Values[0], NumValValues));
Dan Gohman041e2eb2008-05-15 19:50:34 +00002899}
2900
Chris Lattner3e104b12006-04-08 04:15:24 +00002901
Chris Lattner1c08c712005-01-07 07:47:53 +00002902void SelectionDAGLowering::visitGetElementPtr(User &I) {
Dan Gohman475871a2008-07-27 21:46:04 +00002903 SDValue N = getValue(I.getOperand(0));
Chris Lattner1c08c712005-01-07 07:47:53 +00002904 const Type *Ty = I.getOperand(0)->getType();
Chris Lattner1c08c712005-01-07 07:47:53 +00002905
2906 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
2907 OI != E; ++OI) {
2908 Value *Idx = *OI;
Chris Lattnerc88d8e92005-12-05 07:10:48 +00002909 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002910 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
Chris Lattner1c08c712005-01-07 07:47:53 +00002911 if (Field) {
2912 // N = N + Offset
Chris Lattnerb1919e22007-02-10 19:55:17 +00002913 uint64_t Offset = TD->getStructLayout(StTy)->getElementOffset(Field);
Chris Lattner1c08c712005-01-07 07:47:53 +00002914 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
Chris Lattner0bd48932008-01-17 07:00:52 +00002915 DAG.getIntPtrConstant(Offset));
Chris Lattner1c08c712005-01-07 07:47:53 +00002916 }
2917 Ty = StTy->getElementType(Field);
2918 } else {
2919 Ty = cast<SequentialType>(Ty)->getElementType();
Chris Lattner7cc47772005-01-07 21:56:57 +00002920
Chris Lattner7c0104b2005-11-09 04:45:33 +00002921 // If this is a constant subscript, handle it quickly.
2922 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002923 if (CI->getZExtValue() == 0) continue;
Reid Spencer47857812006-12-31 05:55:36 +00002924 uint64_t Offs =
Dale Johannesena7ac2bd2007-10-01 23:08:35 +00002925 TD->getABITypeSize(Ty)*cast<ConstantInt>(CI)->getSExtValue();
Chris Lattner0bd48932008-01-17 07:00:52 +00002926 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
2927 DAG.getIntPtrConstant(Offs));
Chris Lattner7c0104b2005-11-09 04:45:33 +00002928 continue;
Chris Lattner1c08c712005-01-07 07:47:53 +00002929 }
Chris Lattner7c0104b2005-11-09 04:45:33 +00002930
2931 // N = N + Idx * ElementSize;
Dale Johannesena7ac2bd2007-10-01 23:08:35 +00002932 uint64_t ElementSize = TD->getABITypeSize(Ty);
Dan Gohman475871a2008-07-27 21:46:04 +00002933 SDValue IdxN = getValue(Idx);
Chris Lattner7c0104b2005-11-09 04:45:33 +00002934
2935 // If the index is smaller or larger than intptr_t, truncate or extend
2936 // it.
Evan Cheng83785c82008-08-20 22:45:34 +00002937 if (IdxN.getValueType().bitsLT(N.getValueType()))
Reid Spencer47857812006-12-31 05:55:36 +00002938 IdxN = DAG.getNode(ISD::SIGN_EXTEND, N.getValueType(), IdxN);
Evan Cheng83785c82008-08-20 22:45:34 +00002939 else if (IdxN.getValueType().bitsGT(N.getValueType()))
Chris Lattner7c0104b2005-11-09 04:45:33 +00002940 IdxN = DAG.getNode(ISD::TRUNCATE, N.getValueType(), IdxN);
2941
2942 // If this is a multiply by a power of two, turn it into a shl
2943 // immediately. This is a very common case.
Dan Gohman66799062008-08-23 01:06:51 +00002944 if (ElementSize != 1) {
2945 if (isPowerOf2_64(ElementSize)) {
2946 unsigned Amt = Log2_64(ElementSize);
2947 IdxN = DAG.getNode(ISD::SHL, N.getValueType(), IdxN,
2948 DAG.getConstant(Amt, TLI.getShiftAmountTy()));
2949 } else {
2950 SDValue Scale = DAG.getIntPtrConstant(ElementSize);
2951 IdxN = DAG.getNode(ISD::MUL, N.getValueType(), IdxN, Scale);
2952 }
Chris Lattner7c0104b2005-11-09 04:45:33 +00002953 }
Dan Gohman66799062008-08-23 01:06:51 +00002954
Chris Lattner7c0104b2005-11-09 04:45:33 +00002955 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
Chris Lattner1c08c712005-01-07 07:47:53 +00002956 }
2957 }
2958 setValue(&I, N);
2959}
2960
2961void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
2962 // If this is a fixed sized alloca in the entry block of the function,
2963 // allocate it statically on the stack.
2964 if (FuncInfo.StaticAllocaMap.count(&I))
2965 return; // getValue will auto-populate this.
2966
2967 const Type *Ty = I.getAllocatedType();
Duncan Sands514ab342007-11-01 20:53:16 +00002968 uint64_t TySize = TLI.getTargetData()->getABITypeSize(Ty);
Chris Lattner58092e32007-01-20 22:35:55 +00002969 unsigned Align =
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00002970 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
Chris Lattner58092e32007-01-20 22:35:55 +00002971 I.getAlignment());
Chris Lattner1c08c712005-01-07 07:47:53 +00002972
Dan Gohman475871a2008-07-27 21:46:04 +00002973 SDValue AllocSize = getValue(I.getArraySize());
Duncan Sands83ec4b62008-06-06 12:08:01 +00002974 MVT IntPtr = TLI.getPointerTy();
Duncan Sands8e4eb092008-06-08 20:54:56 +00002975 if (IntPtr.bitsLT(AllocSize.getValueType()))
Chris Lattner68cd65e2005-01-22 23:04:37 +00002976 AllocSize = DAG.getNode(ISD::TRUNCATE, IntPtr, AllocSize);
Duncan Sands8e4eb092008-06-08 20:54:56 +00002977 else if (IntPtr.bitsGT(AllocSize.getValueType()))
Chris Lattner68cd65e2005-01-22 23:04:37 +00002978 AllocSize = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, AllocSize);
Chris Lattner1c08c712005-01-07 07:47:53 +00002979
Chris Lattner68cd65e2005-01-22 23:04:37 +00002980 AllocSize = DAG.getNode(ISD::MUL, IntPtr, AllocSize,
Chris Lattner0bd48932008-01-17 07:00:52 +00002981 DAG.getIntPtrConstant(TySize));
Chris Lattner1c08c712005-01-07 07:47:53 +00002982
Evan Cheng45157792007-08-16 23:46:29 +00002983 // Handle alignment. If the requested alignment is less than or equal to
2984 // the stack alignment, ignore it. If the size is greater than or equal to
2985 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
Chris Lattner1c08c712005-01-07 07:47:53 +00002986 unsigned StackAlign =
2987 TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
Evan Cheng45157792007-08-16 23:46:29 +00002988 if (Align <= StackAlign)
Chris Lattner1c08c712005-01-07 07:47:53 +00002989 Align = 0;
Evan Cheng45157792007-08-16 23:46:29 +00002990
2991 // Round the size of the allocation up to the stack alignment size
2992 // by add SA-1 to the size.
2993 AllocSize = DAG.getNode(ISD::ADD, AllocSize.getValueType(), AllocSize,
Chris Lattner0bd48932008-01-17 07:00:52 +00002994 DAG.getIntPtrConstant(StackAlign-1));
Evan Cheng45157792007-08-16 23:46:29 +00002995 // Mask out the low bits for alignment purposes.
2996 AllocSize = DAG.getNode(ISD::AND, AllocSize.getValueType(), AllocSize,
Chris Lattner0bd48932008-01-17 07:00:52 +00002997 DAG.getIntPtrConstant(~(uint64_t)(StackAlign-1)));
Chris Lattner1c08c712005-01-07 07:47:53 +00002998
Dan Gohman475871a2008-07-27 21:46:04 +00002999 SDValue Ops[] = { getRoot(), AllocSize, DAG.getIntPtrConstant(Align) };
Duncan Sands83ec4b62008-06-06 12:08:01 +00003000 const MVT *VTs = DAG.getNodeValueTypes(AllocSize.getValueType(),
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00003001 MVT::Other);
Dan Gohman475871a2008-07-27 21:46:04 +00003002 SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, VTs, 2, Ops, 3);
Chris Lattner0da331f2007-02-04 01:31:47 +00003003 setValue(&I, DSA);
3004 DAG.setRoot(DSA.getValue(1));
Chris Lattner1c08c712005-01-07 07:47:53 +00003005
3006 // Inform the Frame Information that we have just allocated a variable-sized
3007 // object.
3008 CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
3009}
3010
Chris Lattner1c08c712005-01-07 07:47:53 +00003011void SelectionDAGLowering::visitLoad(LoadInst &I) {
Dan Gohman8a6ccb52008-06-09 15:21:47 +00003012 const Value *SV = I.getOperand(0);
Dan Gohman475871a2008-07-27 21:46:04 +00003013 SDValue Ptr = getValue(SV);
Dan Gohman8a6ccb52008-06-09 15:21:47 +00003014
3015 const Type *Ty = I.getType();
3016 bool isVolatile = I.isVolatile();
3017 unsigned Alignment = I.getAlignment();
3018
3019 SmallVector<MVT, 4> ValueVTs;
3020 SmallVector<uint64_t, 4> Offsets;
3021 ComputeValueVTs(TLI, Ty, ValueVTs, &Offsets);
3022 unsigned NumValues = ValueVTs.size();
3023 if (NumValues == 0)
3024 return;
Misha Brukmanedf128a2005-04-21 22:36:52 +00003025
Dan Gohman475871a2008-07-27 21:46:04 +00003026 SDValue Root;
Dan Gohman8b4588f2008-07-25 00:04:14 +00003027 bool ConstantMemory = false;
Chris Lattnerd3948112005-01-17 22:19:26 +00003028 if (I.isVolatile())
Dan Gohman8b4588f2008-07-25 00:04:14 +00003029 // Serialize volatile loads with other side effects.
Chris Lattnerd3948112005-01-17 22:19:26 +00003030 Root = getRoot();
Dan Gohman7c3234c2008-08-27 23:52:12 +00003031 else if (AA->pointsToConstantMemory(SV)) {
Dan Gohman8b4588f2008-07-25 00:04:14 +00003032 // Do not serialize (non-volatile) loads of constant memory with anything.
3033 Root = DAG.getEntryNode();
3034 ConstantMemory = true;
3035 } else {
Chris Lattnerd3948112005-01-17 22:19:26 +00003036 // Do not serialize non-volatile loads against each other.
3037 Root = DAG.getRoot();
3038 }
Chris Lattner28b5b1c2006-03-15 22:19:46 +00003039
Dan Gohman475871a2008-07-27 21:46:04 +00003040 SmallVector<SDValue, 4> Values(NumValues);
3041 SmallVector<SDValue, 4> Chains(NumValues);
Dan Gohman1d685a42008-06-07 02:02:36 +00003042 MVT PtrVT = Ptr.getValueType();
3043 for (unsigned i = 0; i != NumValues; ++i) {
Dan Gohman475871a2008-07-27 21:46:04 +00003044 SDValue L = DAG.getLoad(ValueVTs[i], Root,
Dan Gohman1d685a42008-06-07 02:02:36 +00003045 DAG.getNode(ISD::ADD, PtrVT, Ptr,
3046 DAG.getConstant(Offsets[i], PtrVT)),
3047 SV, Offsets[i],
3048 isVolatile, Alignment);
3049 Values[i] = L;
3050 Chains[i] = L.getValue(1);
3051 }
Chris Lattner28b5b1c2006-03-15 22:19:46 +00003052
Dan Gohman8b4588f2008-07-25 00:04:14 +00003053 if (!ConstantMemory) {
Dan Gohman475871a2008-07-27 21:46:04 +00003054 SDValue Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
Dan Gohman8b4588f2008-07-25 00:04:14 +00003055 &Chains[0], NumValues);
3056 if (isVolatile)
3057 DAG.setRoot(Chain);
3058 else
3059 PendingLoads.push_back(Chain);
3060 }
Dan Gohman1d685a42008-06-07 02:02:36 +00003061
Duncan Sandsf9516202008-06-30 10:19:09 +00003062 setValue(&I, DAG.getMergeValues(DAG.getVTList(&ValueVTs[0], NumValues),
3063 &Values[0], NumValues));
Chris Lattner1c08c712005-01-07 07:47:53 +00003064}
3065
3066
3067void SelectionDAGLowering::visitStore(StoreInst &I) {
3068 Value *SrcV = I.getOperand(0);
Dan Gohman1d685a42008-06-07 02:02:36 +00003069 Value *PtrV = I.getOperand(1);
Dan Gohman1d685a42008-06-07 02:02:36 +00003070
3071 SmallVector<MVT, 4> ValueVTs;
3072 SmallVector<uint64_t, 4> Offsets;
3073 ComputeValueVTs(TLI, SrcV->getType(), ValueVTs, &Offsets);
3074 unsigned NumValues = ValueVTs.size();
Dan Gohman8a6ccb52008-06-09 15:21:47 +00003075 if (NumValues == 0)
3076 return;
Dan Gohman1d685a42008-06-07 02:02:36 +00003077
Dan Gohman90d33ee2008-07-30 18:36:51 +00003078 // Get the lowered operands. Note that we do this after
3079 // checking if NumResults is zero, because with zero results
3080 // the operands won't have values in the map.
3081 SDValue Src = getValue(SrcV);
3082 SDValue Ptr = getValue(PtrV);
3083
Dan Gohman475871a2008-07-27 21:46:04 +00003084 SDValue Root = getRoot();
3085 SmallVector<SDValue, 4> Chains(NumValues);
Dan Gohman1d685a42008-06-07 02:02:36 +00003086 MVT PtrVT = Ptr.getValueType();
3087 bool isVolatile = I.isVolatile();
3088 unsigned Alignment = I.getAlignment();
3089 for (unsigned i = 0; i != NumValues; ++i)
Gabor Greif99a6cb92008-08-26 22:36:50 +00003090 Chains[i] = DAG.getStore(Root, SDValue(Src.Val, Src.getResNo() + i),
Dan Gohman1d685a42008-06-07 02:02:36 +00003091 DAG.getNode(ISD::ADD, PtrVT, Ptr,
3092 DAG.getConstant(Offsets[i], PtrVT)),
3093 PtrV, Offsets[i],
3094 isVolatile, Alignment);
3095
3096 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other, &Chains[0], NumValues));
Chris Lattner1c08c712005-01-07 07:47:53 +00003097}
3098
Chris Lattner0eade312006-03-24 02:22:33 +00003099/// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
3100/// node.
3101void SelectionDAGLowering::visitTargetIntrinsic(CallInst &I,
3102 unsigned Intrinsic) {
Duncan Sandsa3355ff2007-12-03 20:06:50 +00003103 bool HasChain = !I.doesNotAccessMemory();
3104 bool OnlyLoad = HasChain && I.onlyReadsMemory();
3105
Chris Lattner0eade312006-03-24 02:22:33 +00003106 // Build the operand list.
Dan Gohman475871a2008-07-27 21:46:04 +00003107 SmallVector<SDValue, 8> Ops;
Chris Lattnere58a7802006-04-02 03:41:14 +00003108 if (HasChain) { // If this intrinsic has side-effects, chainify it.
3109 if (OnlyLoad) {
3110 // We don't need to serialize loads against other loads.
3111 Ops.push_back(DAG.getRoot());
3112 } else {
3113 Ops.push_back(getRoot());
3114 }
3115 }
Chris Lattner0eade312006-03-24 02:22:33 +00003116
3117 // Add the intrinsic ID as an integer operand.
3118 Ops.push_back(DAG.getConstant(Intrinsic, TLI.getPointerTy()));
3119
3120 // Add all operands of the call to the operand list.
3121 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
Dan Gohman475871a2008-07-27 21:46:04 +00003122 SDValue Op = getValue(I.getOperand(i));
Chris Lattner0eade312006-03-24 02:22:33 +00003123 assert(TLI.isTypeLegal(Op.getValueType()) &&
3124 "Intrinsic uses a non-legal type?");
3125 Ops.push_back(Op);
3126 }
3127
Duncan Sands83ec4b62008-06-06 12:08:01 +00003128 std::vector<MVT> VTs;
Chris Lattner0eade312006-03-24 02:22:33 +00003129 if (I.getType() != Type::VoidTy) {
Duncan Sands83ec4b62008-06-06 12:08:01 +00003130 MVT VT = TLI.getValueType(I.getType());
3131 if (VT.isVector()) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00003132 const VectorType *DestTy = cast<VectorType>(I.getType());
Duncan Sands83ec4b62008-06-06 12:08:01 +00003133 MVT EltVT = TLI.getValueType(DestTy->getElementType());
Chris Lattner0eade312006-03-24 02:22:33 +00003134
Duncan Sands83ec4b62008-06-06 12:08:01 +00003135 VT = MVT::getVectorVT(EltVT, DestTy->getNumElements());
Chris Lattner0eade312006-03-24 02:22:33 +00003136 assert(VT != MVT::Other && "Intrinsic uses a non-legal type?");
3137 }
3138
3139 assert(TLI.isTypeLegal(VT) && "Intrinsic uses a non-legal type?");
3140 VTs.push_back(VT);
3141 }
3142 if (HasChain)
3143 VTs.push_back(MVT::Other);
3144
Duncan Sands83ec4b62008-06-06 12:08:01 +00003145 const MVT *VTList = DAG.getNodeValueTypes(VTs);
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00003146
Chris Lattner0eade312006-03-24 02:22:33 +00003147 // Create the node.
Dan Gohman475871a2008-07-27 21:46:04 +00003148 SDValue Result;
Chris Lattner48b61a72006-03-28 00:40:33 +00003149 if (!HasChain)
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00003150 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VTList, VTs.size(),
3151 &Ops[0], Ops.size());
Chris Lattner48b61a72006-03-28 00:40:33 +00003152 else if (I.getType() != Type::VoidTy)
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00003153 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, VTList, VTs.size(),
3154 &Ops[0], Ops.size());
Chris Lattner48b61a72006-03-28 00:40:33 +00003155 else
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00003156 Result = DAG.getNode(ISD::INTRINSIC_VOID, VTList, VTs.size(),
3157 &Ops[0], Ops.size());
Chris Lattner48b61a72006-03-28 00:40:33 +00003158
Chris Lattnere58a7802006-04-02 03:41:14 +00003159 if (HasChain) {
Dan Gohman475871a2008-07-27 21:46:04 +00003160 SDValue Chain = Result.getValue(Result.Val->getNumValues()-1);
Chris Lattnere58a7802006-04-02 03:41:14 +00003161 if (OnlyLoad)
3162 PendingLoads.push_back(Chain);
3163 else
3164 DAG.setRoot(Chain);
3165 }
Chris Lattner0eade312006-03-24 02:22:33 +00003166 if (I.getType() != Type::VoidTy) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00003167 if (const VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
Duncan Sands83ec4b62008-06-06 12:08:01 +00003168 MVT VT = TLI.getValueType(PTy);
Dan Gohman7f321562007-06-25 16:23:39 +00003169 Result = DAG.getNode(ISD::BIT_CONVERT, VT, Result);
Chris Lattner0eade312006-03-24 02:22:33 +00003170 }
3171 setValue(&I, Result);
3172 }
3173}
3174
Duncan Sandsb4fd45e2007-07-06 09:10:03 +00003175/// ExtractTypeInfo - Returns the type info, possibly bitcast, encoded in V.
Duncan Sandscf26d7c2007-07-04 20:52:51 +00003176static GlobalVariable *ExtractTypeInfo (Value *V) {
Anton Korobeynikov0b12ecf2008-05-07 22:54:15 +00003177 V = V->stripPointerCasts();
Duncan Sandsb4fd45e2007-07-06 09:10:03 +00003178 GlobalVariable *GV = dyn_cast<GlobalVariable>(V);
Anton Korobeynikov4c71dfe2008-02-20 11:10:28 +00003179 assert ((GV || isa<ConstantPointerNull>(V)) &&
Duncan Sandscf26d7c2007-07-04 20:52:51 +00003180 "TypeInfo must be a global variable or NULL");
3181 return GV;
3182}
3183
Duncan Sandsf4070822007-06-15 19:04:19 +00003184/// addCatchInfo - Extract the personality and type infos from an eh.selector
Duncan Sandscf26d7c2007-07-04 20:52:51 +00003185/// call, and add them to the specified machine basic block.
Duncan Sandsf4070822007-06-15 19:04:19 +00003186static void addCatchInfo(CallInst &I, MachineModuleInfo *MMI,
3187 MachineBasicBlock *MBB) {
3188 // Inform the MachineModuleInfo of the personality for this landing pad.
3189 ConstantExpr *CE = cast<ConstantExpr>(I.getOperand(2));
3190 assert(CE->getOpcode() == Instruction::BitCast &&
3191 isa<Function>(CE->getOperand(0)) &&
3192 "Personality should be a function");
3193 MMI->addPersonality(MBB, cast<Function>(CE->getOperand(0)));
3194
3195 // Gather all the type infos for this landing pad and pass them along to
3196 // MachineModuleInfo.
3197 std::vector<GlobalVariable *> TyInfo;
Duncan Sandscf26d7c2007-07-04 20:52:51 +00003198 unsigned N = I.getNumOperands();
3199
3200 for (unsigned i = N - 1; i > 2; --i) {
3201 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(i))) {
3202 unsigned FilterLength = CI->getZExtValue();
Duncan Sands6590b042007-08-27 15:47:50 +00003203 unsigned FirstCatch = i + FilterLength + !FilterLength;
Duncan Sandscf26d7c2007-07-04 20:52:51 +00003204 assert (FirstCatch <= N && "Invalid filter length");
3205
3206 if (FirstCatch < N) {
3207 TyInfo.reserve(N - FirstCatch);
3208 for (unsigned j = FirstCatch; j < N; ++j)
3209 TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
3210 MMI->addCatchTypeInfo(MBB, TyInfo);
3211 TyInfo.clear();
3212 }
3213
Duncan Sands6590b042007-08-27 15:47:50 +00003214 if (!FilterLength) {
3215 // Cleanup.
3216 MMI->addCleanup(MBB);
3217 } else {
3218 // Filter.
3219 TyInfo.reserve(FilterLength - 1);
3220 for (unsigned j = i + 1; j < FirstCatch; ++j)
3221 TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
3222 MMI->addFilterTypeInfo(MBB, TyInfo);
3223 TyInfo.clear();
3224 }
Duncan Sandscf26d7c2007-07-04 20:52:51 +00003225
3226 N = i;
3227 }
Duncan Sandsf4070822007-06-15 19:04:19 +00003228 }
Duncan Sandscf26d7c2007-07-04 20:52:51 +00003229
3230 if (N > 3) {
3231 TyInfo.reserve(N - 3);
3232 for (unsigned j = 3; j < N; ++j)
3233 TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
Duncan Sandsf4070822007-06-15 19:04:19 +00003234 MMI->addCatchTypeInfo(MBB, TyInfo);
Duncan Sandscf26d7c2007-07-04 20:52:51 +00003235 }
Duncan Sandsf4070822007-06-15 19:04:19 +00003236}
3237
Mon P Wang63307c32008-05-05 19:05:59 +00003238
3239/// Inlined utility function to implement binary input atomic intrinsics for
3240// visitIntrinsicCall: I is a call instruction
3241// Op is the associated NodeType for I
3242const char *
3243SelectionDAGLowering::implVisitBinaryAtomic(CallInst& I, ISD::NodeType Op) {
Dan Gohman475871a2008-07-27 21:46:04 +00003244 SDValue Root = getRoot();
3245 SDValue L = DAG.getAtomic(Op, Root,
Mon P Wang63307c32008-05-05 19:05:59 +00003246 getValue(I.getOperand(1)),
Dan Gohmanfd4418f2008-06-25 16:07:49 +00003247 getValue(I.getOperand(2)),
Mon P Wang28873102008-06-25 08:15:39 +00003248 I.getOperand(1));
Mon P Wang63307c32008-05-05 19:05:59 +00003249 setValue(&I, L);
3250 DAG.setRoot(L.getValue(1));
3251 return 0;
3252}
3253
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003254/// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
3255/// we want to emit this as a call to a named external function, return the name
3256/// otherwise lower it and return null.
3257const char *
3258SelectionDAGLowering::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
3259 switch (Intrinsic) {
Chris Lattner0eade312006-03-24 02:22:33 +00003260 default:
3261 // By default, turn this into a target intrinsic node.
3262 visitTargetIntrinsic(I, Intrinsic);
3263 return 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003264 case Intrinsic::vastart: visitVAStart(I); return 0;
3265 case Intrinsic::vaend: visitVAEnd(I); return 0;
3266 case Intrinsic::vacopy: visitVACopy(I); return 0;
Nate Begemanbcc5f362007-01-29 22:58:52 +00003267 case Intrinsic::returnaddress:
3268 setValue(&I, DAG.getNode(ISD::RETURNADDR, TLI.getPointerTy(),
3269 getValue(I.getOperand(1))));
3270 return 0;
3271 case Intrinsic::frameaddress:
3272 setValue(&I, DAG.getNode(ISD::FRAMEADDR, TLI.getPointerTy(),
3273 getValue(I.getOperand(1))));
3274 return 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003275 case Intrinsic::setjmp:
Anton Korobeynikovd27a2582006-12-10 23:12:42 +00003276 return "_setjmp"+!TLI.usesUnderscoreSetJmp();
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003277 break;
3278 case Intrinsic::longjmp:
Anton Korobeynikovd27a2582006-12-10 23:12:42 +00003279 return "_longjmp"+!TLI.usesUnderscoreLongJmp();
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003280 break;
Chris Lattner03dd4652006-03-03 00:00:25 +00003281 case Intrinsic::memcpy_i32:
Dan Gohman707e0182008-04-12 04:36:06 +00003282 case Intrinsic::memcpy_i64: {
Dan Gohman475871a2008-07-27 21:46:04 +00003283 SDValue Op1 = getValue(I.getOperand(1));
3284 SDValue Op2 = getValue(I.getOperand(2));
3285 SDValue Op3 = getValue(I.getOperand(3));
Dan Gohman707e0182008-04-12 04:36:06 +00003286 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
3287 DAG.setRoot(DAG.getMemcpy(getRoot(), Op1, Op2, Op3, Align, false,
3288 I.getOperand(1), 0, I.getOperand(2), 0));
Chris Lattner03dd4652006-03-03 00:00:25 +00003289 return 0;
Dan Gohman707e0182008-04-12 04:36:06 +00003290 }
Chris Lattner03dd4652006-03-03 00:00:25 +00003291 case Intrinsic::memset_i32:
Dan Gohman707e0182008-04-12 04:36:06 +00003292 case Intrinsic::memset_i64: {
Dan Gohman475871a2008-07-27 21:46:04 +00003293 SDValue Op1 = getValue(I.getOperand(1));
3294 SDValue Op2 = getValue(I.getOperand(2));
3295 SDValue Op3 = getValue(I.getOperand(3));
Dan Gohman707e0182008-04-12 04:36:06 +00003296 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
3297 DAG.setRoot(DAG.getMemset(getRoot(), Op1, Op2, Op3, Align,
3298 I.getOperand(1), 0));
Chris Lattner03dd4652006-03-03 00:00:25 +00003299 return 0;
Dan Gohman707e0182008-04-12 04:36:06 +00003300 }
Chris Lattner03dd4652006-03-03 00:00:25 +00003301 case Intrinsic::memmove_i32:
Dan Gohman707e0182008-04-12 04:36:06 +00003302 case Intrinsic::memmove_i64: {
Dan Gohman475871a2008-07-27 21:46:04 +00003303 SDValue Op1 = getValue(I.getOperand(1));
3304 SDValue Op2 = getValue(I.getOperand(2));
3305 SDValue Op3 = getValue(I.getOperand(3));
Dan Gohman707e0182008-04-12 04:36:06 +00003306 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
3307
3308 // If the source and destination are known to not be aliases, we can
3309 // lower memmove as memcpy.
3310 uint64_t Size = -1ULL;
3311 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op3))
3312 Size = C->getValue();
Dan Gohman7c3234c2008-08-27 23:52:12 +00003313 if (AA->alias(I.getOperand(1), Size, I.getOperand(2), Size) ==
Dan Gohman707e0182008-04-12 04:36:06 +00003314 AliasAnalysis::NoAlias) {
3315 DAG.setRoot(DAG.getMemcpy(getRoot(), Op1, Op2, Op3, Align, false,
3316 I.getOperand(1), 0, I.getOperand(2), 0));
3317 return 0;
3318 }
3319
3320 DAG.setRoot(DAG.getMemmove(getRoot(), Op1, Op2, Op3, Align,
3321 I.getOperand(1), 0, I.getOperand(2), 0));
Chris Lattner03dd4652006-03-03 00:00:25 +00003322 return 0;
Dan Gohman707e0182008-04-12 04:36:06 +00003323 }
Chris Lattner86cb6432005-12-13 17:40:33 +00003324 case Intrinsic::dbg_stoppoint: {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00003325 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskey43970fe2006-03-23 18:06:46 +00003326 DbgStopPointInst &SPI = cast<DbgStopPointInst>(I);
Jim Laskey44c3b9f2007-01-26 21:22:28 +00003327 if (MMI && SPI.getContext() && MMI->Verify(SPI.getContext())) {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00003328 DebugInfoDesc *DD = MMI->getDescFor(SPI.getContext());
Jim Laskeyce72b172006-02-11 01:01:30 +00003329 assert(DD && "Not a debug information descriptor");
Dan Gohman7f460202008-06-30 20:59:49 +00003330 DAG.setRoot(DAG.getDbgStopPoint(getRoot(),
3331 SPI.getLine(),
3332 SPI.getColumn(),
3333 cast<CompileUnitDesc>(DD)));
Chris Lattner86cb6432005-12-13 17:40:33 +00003334 }
Jim Laskey43970fe2006-03-23 18:06:46 +00003335
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +00003336 return 0;
Chris Lattner36ce6912005-11-29 06:21:05 +00003337 }
Jim Laskey43970fe2006-03-23 18:06:46 +00003338 case Intrinsic::dbg_region_start: {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00003339 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskey43970fe2006-03-23 18:06:46 +00003340 DbgRegionStartInst &RSI = cast<DbgRegionStartInst>(I);
Jim Laskey44c3b9f2007-01-26 21:22:28 +00003341 if (MMI && RSI.getContext() && MMI->Verify(RSI.getContext())) {
3342 unsigned LabelID = MMI->RecordRegionStart(RSI.getContext());
Dan Gohman44066042008-07-01 00:05:16 +00003343 DAG.setRoot(DAG.getLabel(ISD::DBG_LABEL, getRoot(), LabelID));
Jim Laskey43970fe2006-03-23 18:06:46 +00003344 }
3345
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +00003346 return 0;
Jim Laskey43970fe2006-03-23 18:06:46 +00003347 }
3348 case Intrinsic::dbg_region_end: {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00003349 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskey43970fe2006-03-23 18:06:46 +00003350 DbgRegionEndInst &REI = cast<DbgRegionEndInst>(I);
Jim Laskey44c3b9f2007-01-26 21:22:28 +00003351 if (MMI && REI.getContext() && MMI->Verify(REI.getContext())) {
3352 unsigned LabelID = MMI->RecordRegionEnd(REI.getContext());
Dan Gohman44066042008-07-01 00:05:16 +00003353 DAG.setRoot(DAG.getLabel(ISD::DBG_LABEL, getRoot(), LabelID));
Jim Laskey43970fe2006-03-23 18:06:46 +00003354 }
3355
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +00003356 return 0;
Jim Laskey43970fe2006-03-23 18:06:46 +00003357 }
3358 case Intrinsic::dbg_func_start: {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00003359 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Evan Cheng1b08bbc2008-02-01 09:10:45 +00003360 if (!MMI) return 0;
Jim Laskey43970fe2006-03-23 18:06:46 +00003361 DbgFuncStartInst &FSI = cast<DbgFuncStartInst>(I);
Evan Cheng1b08bbc2008-02-01 09:10:45 +00003362 Value *SP = FSI.getSubprogram();
3363 if (SP && MMI->Verify(SP)) {
3364 // llvm.dbg.func.start implicitly defines a dbg_stoppoint which is
3365 // what (most?) gdb expects.
3366 DebugInfoDesc *DD = MMI->getDescFor(SP);
3367 assert(DD && "Not a debug information descriptor");
3368 SubprogramDesc *Subprogram = cast<SubprogramDesc>(DD);
3369 const CompileUnitDesc *CompileUnit = Subprogram->getFile();
Dan Gohman99fe47b2008-06-30 22:21:03 +00003370 unsigned SrcFile = MMI->RecordSource(CompileUnit);
Evan Cheng1b08bbc2008-02-01 09:10:45 +00003371 // Record the source line but does create a label. It will be emitted
3372 // at asm emission time.
3373 MMI->RecordSourceLine(Subprogram->getLine(), 0, SrcFile);
Jim Laskey43970fe2006-03-23 18:06:46 +00003374 }
3375
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +00003376 return 0;
Jim Laskey43970fe2006-03-23 18:06:46 +00003377 }
3378 case Intrinsic::dbg_declare: {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00003379 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskey43970fe2006-03-23 18:06:46 +00003380 DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
Evan Chenga844bde2008-02-02 04:07:54 +00003381 Value *Variable = DI.getVariable();
3382 if (MMI && Variable && MMI->Verify(Variable))
3383 DAG.setRoot(DAG.getNode(ISD::DECLARE, MVT::Other, getRoot(),
3384 getValue(DI.getAddress()), getValue(Variable)));
Jim Laskey43970fe2006-03-23 18:06:46 +00003385 return 0;
3386 }
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003387
Jim Laskeyb180aa12007-02-21 22:53:45 +00003388 case Intrinsic::eh_exception: {
Dale Johannesen1532f3d2008-04-02 00:25:04 +00003389 if (!CurMBB->isLandingPad()) {
3390 // FIXME: Mark exception register as live in. Hack for PR1508.
3391 unsigned Reg = TLI.getExceptionAddressRegister();
3392 if (Reg) CurMBB->addLiveIn(Reg);
Jim Laskey735b6f82007-02-22 15:38:06 +00003393 }
Dale Johannesen1532f3d2008-04-02 00:25:04 +00003394 // Insert the EXCEPTIONADDR instruction.
3395 SDVTList VTs = DAG.getVTList(TLI.getPointerTy(), MVT::Other);
Dan Gohman475871a2008-07-27 21:46:04 +00003396 SDValue Ops[1];
Dale Johannesen1532f3d2008-04-02 00:25:04 +00003397 Ops[0] = DAG.getRoot();
Dan Gohman475871a2008-07-27 21:46:04 +00003398 SDValue Op = DAG.getNode(ISD::EXCEPTIONADDR, VTs, Ops, 1);
Dale Johannesen1532f3d2008-04-02 00:25:04 +00003399 setValue(&I, Op);
3400 DAG.setRoot(Op.getValue(1));
Jim Laskeyb180aa12007-02-21 22:53:45 +00003401 return 0;
3402 }
3403
Anton Korobeynikov8806c7b2007-09-07 11:39:35 +00003404 case Intrinsic::eh_selector_i32:
3405 case Intrinsic::eh_selector_i64: {
Jim Laskeyb180aa12007-02-21 22:53:45 +00003406 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Duncan Sands83ec4b62008-06-06 12:08:01 +00003407 MVT VT = (Intrinsic == Intrinsic::eh_selector_i32 ?
Anton Korobeynikov8806c7b2007-09-07 11:39:35 +00003408 MVT::i32 : MVT::i64);
3409
Dale Johannesen1532f3d2008-04-02 00:25:04 +00003410 if (MMI) {
Duncan Sandsf4070822007-06-15 19:04:19 +00003411 if (CurMBB->isLandingPad())
3412 addCatchInfo(I, MMI, CurMBB);
Evan Chenge47c3332007-06-27 18:45:32 +00003413 else {
Duncan Sandsf4070822007-06-15 19:04:19 +00003414#ifndef NDEBUG
Duncan Sandsf4070822007-06-15 19:04:19 +00003415 FuncInfo.CatchInfoLost.insert(&I);
3416#endif
Duncan Sands90291952007-07-06 09:18:59 +00003417 // FIXME: Mark exception selector register as live in. Hack for PR1508.
3418 unsigned Reg = TLI.getExceptionSelectorRegister();
3419 if (Reg) CurMBB->addLiveIn(Reg);
Evan Chenge47c3332007-06-27 18:45:32 +00003420 }
Jim Laskey735b6f82007-02-22 15:38:06 +00003421
3422 // Insert the EHSELECTION instruction.
Anton Korobeynikov8806c7b2007-09-07 11:39:35 +00003423 SDVTList VTs = DAG.getVTList(VT, MVT::Other);
Dan Gohman475871a2008-07-27 21:46:04 +00003424 SDValue Ops[2];
Jim Laskey735b6f82007-02-22 15:38:06 +00003425 Ops[0] = getValue(I.getOperand(1));
3426 Ops[1] = getRoot();
Dan Gohman475871a2008-07-27 21:46:04 +00003427 SDValue Op = DAG.getNode(ISD::EHSELECTION, VTs, Ops, 2);
Jim Laskey735b6f82007-02-22 15:38:06 +00003428 setValue(&I, Op);
3429 DAG.setRoot(Op.getValue(1));
Jim Laskey7a1de982007-02-24 09:45:44 +00003430 } else {
Anton Korobeynikov8806c7b2007-09-07 11:39:35 +00003431 setValue(&I, DAG.getConstant(0, VT));
Jim Laskey735b6f82007-02-22 15:38:06 +00003432 }
Jim Laskeyb180aa12007-02-21 22:53:45 +00003433
3434 return 0;
3435 }
Anton Korobeynikov8806c7b2007-09-07 11:39:35 +00003436
3437 case Intrinsic::eh_typeid_for_i32:
3438 case Intrinsic::eh_typeid_for_i64: {
Jim Laskeyb180aa12007-02-21 22:53:45 +00003439 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Duncan Sands83ec4b62008-06-06 12:08:01 +00003440 MVT VT = (Intrinsic == Intrinsic::eh_typeid_for_i32 ?
Anton Korobeynikov8806c7b2007-09-07 11:39:35 +00003441 MVT::i32 : MVT::i64);
Jim Laskeyb180aa12007-02-21 22:53:45 +00003442
Jim Laskey735b6f82007-02-22 15:38:06 +00003443 if (MMI) {
3444 // Find the type id for the given typeinfo.
Duncan Sandscf26d7c2007-07-04 20:52:51 +00003445 GlobalVariable *GV = ExtractTypeInfo(I.getOperand(1));
Duncan Sands3b346362007-05-04 17:12:26 +00003446
Jim Laskey735b6f82007-02-22 15:38:06 +00003447 unsigned TypeID = MMI->getTypeIDFor(GV);
Anton Korobeynikov8806c7b2007-09-07 11:39:35 +00003448 setValue(&I, DAG.getConstant(TypeID, VT));
Jim Laskey7a1de982007-02-24 09:45:44 +00003449 } else {
Duncan Sandsf664e412007-07-06 14:46:23 +00003450 // Return something different to eh_selector.
Anton Korobeynikov8806c7b2007-09-07 11:39:35 +00003451 setValue(&I, DAG.getConstant(1, VT));
Jim Laskey735b6f82007-02-22 15:38:06 +00003452 }
Jim Laskeyb180aa12007-02-21 22:53:45 +00003453
3454 return 0;
3455 }
3456
Anton Korobeynikov2365f512007-07-14 14:06:15 +00003457 case Intrinsic::eh_return: {
3458 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3459
Dale Johannesen1532f3d2008-04-02 00:25:04 +00003460 if (MMI) {
Anton Korobeynikov2365f512007-07-14 14:06:15 +00003461 MMI->setCallsEHReturn(true);
3462 DAG.setRoot(DAG.getNode(ISD::EH_RETURN,
3463 MVT::Other,
Dan Gohman86e1ebf2008-03-27 19:56:19 +00003464 getControlRoot(),
Anton Korobeynikov2365f512007-07-14 14:06:15 +00003465 getValue(I.getOperand(1)),
3466 getValue(I.getOperand(2))));
3467 } else {
3468 setValue(&I, DAG.getConstant(0, TLI.getPointerTy()));
3469 }
3470
3471 return 0;
3472 }
3473
3474 case Intrinsic::eh_unwind_init: {
3475 if (MachineModuleInfo *MMI = DAG.getMachineModuleInfo()) {
3476 MMI->setCallsUnwindInit(true);
3477 }
3478
3479 return 0;
3480 }
3481
3482 case Intrinsic::eh_dwarf_cfa: {
Duncan Sands83ec4b62008-06-06 12:08:01 +00003483 MVT VT = getValue(I.getOperand(1)).getValueType();
Dan Gohman475871a2008-07-27 21:46:04 +00003484 SDValue CfaArg;
Duncan Sands8e4eb092008-06-08 20:54:56 +00003485 if (VT.bitsGT(TLI.getPointerTy()))
Dale Johannesen1532f3d2008-04-02 00:25:04 +00003486 CfaArg = DAG.getNode(ISD::TRUNCATE,
3487 TLI.getPointerTy(), getValue(I.getOperand(1)));
3488 else
3489 CfaArg = DAG.getNode(ISD::SIGN_EXTEND,
3490 TLI.getPointerTy(), getValue(I.getOperand(1)));
Anton Korobeynikov2365f512007-07-14 14:06:15 +00003491
Dan Gohman475871a2008-07-27 21:46:04 +00003492 SDValue Offset = DAG.getNode(ISD::ADD,
Dale Johannesen1532f3d2008-04-02 00:25:04 +00003493 TLI.getPointerTy(),
3494 DAG.getNode(ISD::FRAME_TO_ARGS_OFFSET,
3495 TLI.getPointerTy()),
3496 CfaArg);
3497 setValue(&I, DAG.getNode(ISD::ADD,
3498 TLI.getPointerTy(),
3499 DAG.getNode(ISD::FRAMEADDR,
3500 TLI.getPointerTy(),
3501 DAG.getConstant(0,
3502 TLI.getPointerTy())),
3503 Offset));
Anton Korobeynikov2365f512007-07-14 14:06:15 +00003504 return 0;
3505 }
3506
Dale Johannesen9ab7fb32007-10-02 17:43:59 +00003507 case Intrinsic::sqrt:
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003508 setValue(&I, DAG.getNode(ISD::FSQRT,
3509 getValue(I.getOperand(1)).getValueType(),
3510 getValue(I.getOperand(1))));
3511 return 0;
Dale Johannesen9ab7fb32007-10-02 17:43:59 +00003512 case Intrinsic::powi:
Chris Lattner6ddf8ed2006-09-09 06:03:30 +00003513 setValue(&I, DAG.getNode(ISD::FPOWI,
3514 getValue(I.getOperand(1)).getValueType(),
3515 getValue(I.getOperand(1)),
3516 getValue(I.getOperand(2))));
3517 return 0;
Dan Gohmanac9385a2007-10-12 00:01:22 +00003518 case Intrinsic::sin:
3519 setValue(&I, DAG.getNode(ISD::FSIN,
3520 getValue(I.getOperand(1)).getValueType(),
3521 getValue(I.getOperand(1))));
3522 return 0;
3523 case Intrinsic::cos:
3524 setValue(&I, DAG.getNode(ISD::FCOS,
3525 getValue(I.getOperand(1)).getValueType(),
3526 getValue(I.getOperand(1))));
3527 return 0;
3528 case Intrinsic::pow:
3529 setValue(&I, DAG.getNode(ISD::FPOW,
3530 getValue(I.getOperand(1)).getValueType(),
3531 getValue(I.getOperand(1)),
3532 getValue(I.getOperand(2))));
3533 return 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003534 case Intrinsic::pcmarker: {
Dan Gohman475871a2008-07-27 21:46:04 +00003535 SDValue Tmp = getValue(I.getOperand(1));
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003536 DAG.setRoot(DAG.getNode(ISD::PCMARKER, MVT::Other, getRoot(), Tmp));
3537 return 0;
3538 }
Andrew Lenharth8b91c772005-11-11 22:48:54 +00003539 case Intrinsic::readcyclecounter: {
Dan Gohman475871a2008-07-27 21:46:04 +00003540 SDValue Op = getRoot();
3541 SDValue Tmp = DAG.getNode(ISD::READCYCLECOUNTER,
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00003542 DAG.getNodeValueTypes(MVT::i64, MVT::Other), 2,
3543 &Op, 1);
Andrew Lenharth8b91c772005-11-11 22:48:54 +00003544 setValue(&I, Tmp);
3545 DAG.setRoot(Tmp.getValue(1));
Andrew Lenharth51b8d542005-11-11 16:47:30 +00003546 return 0;
Andrew Lenharth8b91c772005-11-11 22:48:54 +00003547 }
Chris Lattnerc6eb6d72007-04-10 03:20:39 +00003548 case Intrinsic::part_select: {
Reid Spencer3f108cb2007-04-05 01:20:18 +00003549 // Currently not implemented: just abort
Reid Spencerf75b8742007-04-12 02:48:46 +00003550 assert(0 && "part_select intrinsic not implemented");
3551 abort();
3552 }
3553 case Intrinsic::part_set: {
3554 // Currently not implemented: just abort
3555 assert(0 && "part_set intrinsic not implemented");
Reid Spencer3f108cb2007-04-05 01:20:18 +00003556 abort();
Reid Spenceraddd11d2007-04-04 23:48:25 +00003557 }
Reid Spencera4f9c4d2007-04-01 07:34:11 +00003558 case Intrinsic::bswap:
Nate Begemand88fc032006-01-14 03:14:10 +00003559 setValue(&I, DAG.getNode(ISD::BSWAP,
3560 getValue(I.getOperand(1)).getValueType(),
3561 getValue(I.getOperand(1))));
3562 return 0;
Reid Spencera4f9c4d2007-04-01 07:34:11 +00003563 case Intrinsic::cttz: {
Dan Gohman475871a2008-07-27 21:46:04 +00003564 SDValue Arg = getValue(I.getOperand(1));
Duncan Sands83ec4b62008-06-06 12:08:01 +00003565 MVT Ty = Arg.getValueType();
Dan Gohman475871a2008-07-27 21:46:04 +00003566 SDValue result = DAG.getNode(ISD::CTTZ, Ty, Arg);
Reid Spencera4f9c4d2007-04-01 07:34:11 +00003567 setValue(&I, result);
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003568 return 0;
Reid Spencera4f9c4d2007-04-01 07:34:11 +00003569 }
3570 case Intrinsic::ctlz: {
Dan Gohman475871a2008-07-27 21:46:04 +00003571 SDValue Arg = getValue(I.getOperand(1));
Duncan Sands83ec4b62008-06-06 12:08:01 +00003572 MVT Ty = Arg.getValueType();
Dan Gohman475871a2008-07-27 21:46:04 +00003573 SDValue result = DAG.getNode(ISD::CTLZ, Ty, Arg);
Reid Spencera4f9c4d2007-04-01 07:34:11 +00003574 setValue(&I, result);
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003575 return 0;
Reid Spencera4f9c4d2007-04-01 07:34:11 +00003576 }
3577 case Intrinsic::ctpop: {
Dan Gohman475871a2008-07-27 21:46:04 +00003578 SDValue Arg = getValue(I.getOperand(1));
Duncan Sands83ec4b62008-06-06 12:08:01 +00003579 MVT Ty = Arg.getValueType();
Dan Gohman475871a2008-07-27 21:46:04 +00003580 SDValue result = DAG.getNode(ISD::CTPOP, Ty, Arg);
Reid Spencera4f9c4d2007-04-01 07:34:11 +00003581 setValue(&I, result);
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003582 return 0;
Reid Spencera4f9c4d2007-04-01 07:34:11 +00003583 }
Chris Lattner140d53c2006-01-13 02:50:02 +00003584 case Intrinsic::stacksave: {
Dan Gohman475871a2008-07-27 21:46:04 +00003585 SDValue Op = getRoot();
3586 SDValue Tmp = DAG.getNode(ISD::STACKSAVE,
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00003587 DAG.getNodeValueTypes(TLI.getPointerTy(), MVT::Other), 2, &Op, 1);
Chris Lattner140d53c2006-01-13 02:50:02 +00003588 setValue(&I, Tmp);
3589 DAG.setRoot(Tmp.getValue(1));
3590 return 0;
3591 }
Chris Lattner39a17dd2006-01-23 05:22:07 +00003592 case Intrinsic::stackrestore: {
Dan Gohman475871a2008-07-27 21:46:04 +00003593 SDValue Tmp = getValue(I.getOperand(1));
Chris Lattner39a17dd2006-01-23 05:22:07 +00003594 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, MVT::Other, getRoot(), Tmp));
Chris Lattner140d53c2006-01-13 02:50:02 +00003595 return 0;
Chris Lattner39a17dd2006-01-23 05:22:07 +00003596 }
Tanya Lattner24e5aad2007-06-15 22:26:58 +00003597 case Intrinsic::var_annotation:
3598 // Discard annotate attributes
3599 return 0;
Duncan Sands36397f52007-07-27 12:58:54 +00003600
Duncan Sands36397f52007-07-27 12:58:54 +00003601 case Intrinsic::init_trampoline: {
Anton Korobeynikov0b12ecf2008-05-07 22:54:15 +00003602 const Function *F = cast<Function>(I.getOperand(2)->stripPointerCasts());
Duncan Sands36397f52007-07-27 12:58:54 +00003603
Dan Gohman475871a2008-07-27 21:46:04 +00003604 SDValue Ops[6];
Duncan Sands36397f52007-07-27 12:58:54 +00003605 Ops[0] = getRoot();
3606 Ops[1] = getValue(I.getOperand(1));
3607 Ops[2] = getValue(I.getOperand(2));
3608 Ops[3] = getValue(I.getOperand(3));
3609 Ops[4] = DAG.getSrcValue(I.getOperand(1));
3610 Ops[5] = DAG.getSrcValue(F);
3611
Dan Gohman475871a2008-07-27 21:46:04 +00003612 SDValue Tmp = DAG.getNode(ISD::TRAMPOLINE,
Duncan Sandsf7331b32007-09-11 14:10:23 +00003613 DAG.getNodeValueTypes(TLI.getPointerTy(),
3614 MVT::Other), 2,
3615 Ops, 6);
3616
3617 setValue(&I, Tmp);
3618 DAG.setRoot(Tmp.getValue(1));
Duncan Sands36397f52007-07-27 12:58:54 +00003619 return 0;
3620 }
Gordon Henriksence224772008-01-07 01:30:38 +00003621
3622 case Intrinsic::gcroot:
Gordon Henriksen5eca0752008-08-17 18:44:35 +00003623 if (GFI) {
Gordon Henriksence224772008-01-07 01:30:38 +00003624 Value *Alloca = I.getOperand(1);
3625 Constant *TypeMap = cast<Constant>(I.getOperand(2));
3626
3627 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).Val);
Gordon Henriksen5eca0752008-08-17 18:44:35 +00003628 GFI->addStackRoot(FI->getIndex(), TypeMap);
Gordon Henriksence224772008-01-07 01:30:38 +00003629 }
3630 return 0;
3631
3632 case Intrinsic::gcread:
3633 case Intrinsic::gcwrite:
Gordon Henriksen5eca0752008-08-17 18:44:35 +00003634 assert(0 && "GC failed to lower gcread/gcwrite intrinsics!");
Gordon Henriksence224772008-01-07 01:30:38 +00003635 return 0;
3636
Anton Korobeynikov917c2a62007-11-15 23:25:33 +00003637 case Intrinsic::flt_rounds: {
Dan Gohman1a024862008-01-31 00:41:03 +00003638 setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, MVT::i32));
Anton Korobeynikov917c2a62007-11-15 23:25:33 +00003639 return 0;
3640 }
Anton Korobeynikov66fac792008-01-15 07:02:33 +00003641
3642 case Intrinsic::trap: {
3643 DAG.setRoot(DAG.getNode(ISD::TRAP, MVT::Other, getRoot()));
3644 return 0;
3645 }
Evan Cheng27b7db52008-03-08 00:58:38 +00003646 case Intrinsic::prefetch: {
Dan Gohman475871a2008-07-27 21:46:04 +00003647 SDValue Ops[4];
Evan Cheng27b7db52008-03-08 00:58:38 +00003648 Ops[0] = getRoot();
3649 Ops[1] = getValue(I.getOperand(1));
3650 Ops[2] = getValue(I.getOperand(2));
3651 Ops[3] = getValue(I.getOperand(3));
3652 DAG.setRoot(DAG.getNode(ISD::PREFETCH, MVT::Other, &Ops[0], 4));
3653 return 0;
3654 }
3655
Andrew Lenharth22c5c1b2008-02-16 01:24:58 +00003656 case Intrinsic::memory_barrier: {
Dan Gohman475871a2008-07-27 21:46:04 +00003657 SDValue Ops[6];
Andrew Lenharth22c5c1b2008-02-16 01:24:58 +00003658 Ops[0] = getRoot();
3659 for (int x = 1; x < 6; ++x)
3660 Ops[x] = getValue(I.getOperand(x));
3661
3662 DAG.setRoot(DAG.getNode(ISD::MEMBARRIER, MVT::Other, &Ops[0], 6));
3663 return 0;
3664 }
Mon P Wang28873102008-06-25 08:15:39 +00003665 case Intrinsic::atomic_cmp_swap: {
Dan Gohman475871a2008-07-27 21:46:04 +00003666 SDValue Root = getRoot();
3667 SDValue L = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, Root,
Andrew Lenharthab0b9492008-02-21 06:45:13 +00003668 getValue(I.getOperand(1)),
3669 getValue(I.getOperand(2)),
Dan Gohmanfd4418f2008-06-25 16:07:49 +00003670 getValue(I.getOperand(3)),
Mon P Wang28873102008-06-25 08:15:39 +00003671 I.getOperand(1));
Andrew Lenharthab0b9492008-02-21 06:45:13 +00003672 setValue(&I, L);
3673 DAG.setRoot(L.getValue(1));
3674 return 0;
3675 }
Mon P Wang28873102008-06-25 08:15:39 +00003676 case Intrinsic::atomic_load_add:
3677 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_ADD);
3678 case Intrinsic::atomic_load_sub:
3679 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_SUB);
Mon P Wang63307c32008-05-05 19:05:59 +00003680 case Intrinsic::atomic_load_and:
3681 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_AND);
3682 case Intrinsic::atomic_load_or:
3683 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_OR);
3684 case Intrinsic::atomic_load_xor:
3685 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_XOR);
Andrew Lenharth507a58a2008-06-14 05:48:15 +00003686 case Intrinsic::atomic_load_nand:
3687 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_NAND);
Mon P Wang63307c32008-05-05 19:05:59 +00003688 case Intrinsic::atomic_load_min:
3689 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MIN);
3690 case Intrinsic::atomic_load_max:
3691 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MAX);
3692 case Intrinsic::atomic_load_umin:
3693 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMIN);
3694 case Intrinsic::atomic_load_umax:
3695 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMAX);
3696 case Intrinsic::atomic_swap:
3697 return implVisitBinaryAtomic(I, ISD::ATOMIC_SWAP);
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003698 }
3699}
3700
3701
Dan Gohman475871a2008-07-27 21:46:04 +00003702void SelectionDAGLowering::LowerCallTo(CallSite CS, SDValue Callee,
Jim Laskey1da20a72007-02-23 21:45:01 +00003703 bool IsTailCall,
Anton Korobeynikov070280e2007-05-23 11:08:31 +00003704 MachineBasicBlock *LandingPad) {
Duncan Sands6f74b482007-12-19 09:48:52 +00003705 const PointerType *PT = cast<PointerType>(CS.getCalledValue()->getType());
Jim Laskey735b6f82007-02-22 15:38:06 +00003706 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
Anton Korobeynikov070280e2007-05-23 11:08:31 +00003707 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3708 unsigned BeginLabel = 0, EndLabel = 0;
Duncan Sands6f74b482007-12-19 09:48:52 +00003709
Jim Laskey735b6f82007-02-22 15:38:06 +00003710 TargetLowering::ArgListTy Args;
3711 TargetLowering::ArgListEntry Entry;
Duncan Sands6f74b482007-12-19 09:48:52 +00003712 Args.reserve(CS.arg_size());
3713 for (CallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
3714 i != e; ++i) {
Dan Gohman475871a2008-07-27 21:46:04 +00003715 SDValue ArgNode = getValue(*i);
Duncan Sands6f74b482007-12-19 09:48:52 +00003716 Entry.Node = ArgNode; Entry.Ty = (*i)->getType();
Duncan Sands4fee7032007-05-07 20:49:28 +00003717
Duncan Sands6f74b482007-12-19 09:48:52 +00003718 unsigned attrInd = i - CS.arg_begin() + 1;
3719 Entry.isSExt = CS.paramHasAttr(attrInd, ParamAttr::SExt);
3720 Entry.isZExt = CS.paramHasAttr(attrInd, ParamAttr::ZExt);
3721 Entry.isInReg = CS.paramHasAttr(attrInd, ParamAttr::InReg);
3722 Entry.isSRet = CS.paramHasAttr(attrInd, ParamAttr::StructRet);
3723 Entry.isNest = CS.paramHasAttr(attrInd, ParamAttr::Nest);
3724 Entry.isByVal = CS.paramHasAttr(attrInd, ParamAttr::ByVal);
Dale Johannesen08e78b12008-02-22 17:49:45 +00003725 Entry.Alignment = CS.getParamAlignment(attrInd);
Jim Laskey735b6f82007-02-22 15:38:06 +00003726 Args.push_back(Entry);
3727 }
3728
Dale Johannesen1532f3d2008-04-02 00:25:04 +00003729 if (LandingPad && MMI) {
Anton Korobeynikov070280e2007-05-23 11:08:31 +00003730 // Insert a label before the invoke call to mark the try range. This can be
3731 // used to detect deletion of the invoke via the MachineModuleInfo.
3732 BeginLabel = MMI->NextLabelID();
Dale Johannesena4091d32008-04-04 23:48:31 +00003733 // Both PendingLoads and PendingExports must be flushed here;
3734 // this call might not return.
3735 (void)getRoot();
Dan Gohman44066042008-07-01 00:05:16 +00003736 DAG.setRoot(DAG.getLabel(ISD::EH_LABEL, getControlRoot(), BeginLabel));
Anton Korobeynikov070280e2007-05-23 11:08:31 +00003737 }
Duncan Sands6f74b482007-12-19 09:48:52 +00003738
Dan Gohman475871a2008-07-27 21:46:04 +00003739 std::pair<SDValue,SDValue> Result =
Duncan Sands6f74b482007-12-19 09:48:52 +00003740 TLI.LowerCallTo(getRoot(), CS.getType(),
3741 CS.paramHasAttr(0, ParamAttr::SExt),
Duncan Sands00fee652008-02-14 17:28:50 +00003742 CS.paramHasAttr(0, ParamAttr::ZExt),
Duncan Sands6f74b482007-12-19 09:48:52 +00003743 FTy->isVarArg(), CS.getCallingConv(), IsTailCall,
Jim Laskey735b6f82007-02-22 15:38:06 +00003744 Callee, Args, DAG);
Duncan Sands6f74b482007-12-19 09:48:52 +00003745 if (CS.getType() != Type::VoidTy)
3746 setValue(CS.getInstruction(), Result.first);
Jim Laskey735b6f82007-02-22 15:38:06 +00003747 DAG.setRoot(Result.second);
Anton Korobeynikov070280e2007-05-23 11:08:31 +00003748
Dale Johannesen1532f3d2008-04-02 00:25:04 +00003749 if (LandingPad && MMI) {
Anton Korobeynikov070280e2007-05-23 11:08:31 +00003750 // Insert a label at the end of the invoke call to mark the try range. This
3751 // can be used to detect deletion of the invoke via the MachineModuleInfo.
3752 EndLabel = MMI->NextLabelID();
Dan Gohman44066042008-07-01 00:05:16 +00003753 DAG.setRoot(DAG.getLabel(ISD::EH_LABEL, getRoot(), EndLabel));
Anton Korobeynikov070280e2007-05-23 11:08:31 +00003754
Duncan Sands6f74b482007-12-19 09:48:52 +00003755 // Inform MachineModuleInfo of range.
Anton Korobeynikov070280e2007-05-23 11:08:31 +00003756 MMI->addInvoke(LandingPad, BeginLabel, EndLabel);
3757 }
Jim Laskey735b6f82007-02-22 15:38:06 +00003758}
3759
3760
Chris Lattner1c08c712005-01-07 07:47:53 +00003761void SelectionDAGLowering::visitCall(CallInst &I) {
Chris Lattner64e14b12005-01-08 22:48:57 +00003762 const char *RenameFn = 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003763 if (Function *F = I.getCalledFunction()) {
Chris Lattner87b51bc2007-09-10 21:15:22 +00003764 if (F->isDeclaration()) {
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003765 if (unsigned IID = F->getIntrinsicID()) {
3766 RenameFn = visitIntrinsicCall(I, IID);
3767 if (!RenameFn)
3768 return;
Chris Lattner87b51bc2007-09-10 21:15:22 +00003769 }
3770 }
3771
3772 // Check for well-known libc/libm calls. If the function is internal, it
3773 // can't be a library call.
3774 unsigned NameLen = F->getNameLen();
3775 if (!F->hasInternalLinkage() && NameLen) {
3776 const char *NameStr = F->getNameStart();
3777 if (NameStr[0] == 'c' &&
3778 ((NameLen == 8 && !strcmp(NameStr, "copysign")) ||
3779 (NameLen == 9 && !strcmp(NameStr, "copysignf")))) {
3780 if (I.getNumOperands() == 3 && // Basic sanity checks.
3781 I.getOperand(1)->getType()->isFloatingPoint() &&
3782 I.getType() == I.getOperand(1)->getType() &&
3783 I.getType() == I.getOperand(2)->getType()) {
Dan Gohman475871a2008-07-27 21:46:04 +00003784 SDValue LHS = getValue(I.getOperand(1));
3785 SDValue RHS = getValue(I.getOperand(2));
Chris Lattner87b51bc2007-09-10 21:15:22 +00003786 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, LHS.getValueType(),
3787 LHS, RHS));
3788 return;
3789 }
3790 } else if (NameStr[0] == 'f' &&
3791 ((NameLen == 4 && !strcmp(NameStr, "fabs")) ||
Dale Johannesen2f429012007-09-26 21:10:55 +00003792 (NameLen == 5 && !strcmp(NameStr, "fabsf")) ||
3793 (NameLen == 5 && !strcmp(NameStr, "fabsl")))) {
Chris Lattner87b51bc2007-09-10 21:15:22 +00003794 if (I.getNumOperands() == 2 && // Basic sanity checks.
3795 I.getOperand(1)->getType()->isFloatingPoint() &&
3796 I.getType() == I.getOperand(1)->getType()) {
Dan Gohman475871a2008-07-27 21:46:04 +00003797 SDValue Tmp = getValue(I.getOperand(1));
Chris Lattner87b51bc2007-09-10 21:15:22 +00003798 setValue(&I, DAG.getNode(ISD::FABS, Tmp.getValueType(), Tmp));
3799 return;
3800 }
3801 } else if (NameStr[0] == 's' &&
3802 ((NameLen == 3 && !strcmp(NameStr, "sin")) ||
Dale Johannesen2f429012007-09-26 21:10:55 +00003803 (NameLen == 4 && !strcmp(NameStr, "sinf")) ||
3804 (NameLen == 4 && !strcmp(NameStr, "sinl")))) {
Chris Lattner87b51bc2007-09-10 21:15:22 +00003805 if (I.getNumOperands() == 2 && // Basic sanity checks.
3806 I.getOperand(1)->getType()->isFloatingPoint() &&
3807 I.getType() == I.getOperand(1)->getType()) {
Dan Gohman475871a2008-07-27 21:46:04 +00003808 SDValue Tmp = getValue(I.getOperand(1));
Chris Lattner87b51bc2007-09-10 21:15:22 +00003809 setValue(&I, DAG.getNode(ISD::FSIN, Tmp.getValueType(), Tmp));
3810 return;
3811 }
3812 } else if (NameStr[0] == 'c' &&
3813 ((NameLen == 3 && !strcmp(NameStr, "cos")) ||
Dale Johannesen2f429012007-09-26 21:10:55 +00003814 (NameLen == 4 && !strcmp(NameStr, "cosf")) ||
3815 (NameLen == 4 && !strcmp(NameStr, "cosl")))) {
Chris Lattner87b51bc2007-09-10 21:15:22 +00003816 if (I.getNumOperands() == 2 && // Basic sanity checks.
3817 I.getOperand(1)->getType()->isFloatingPoint() &&
3818 I.getType() == I.getOperand(1)->getType()) {
Dan Gohman475871a2008-07-27 21:46:04 +00003819 SDValue Tmp = getValue(I.getOperand(1));
Chris Lattner87b51bc2007-09-10 21:15:22 +00003820 setValue(&I, DAG.getNode(ISD::FCOS, Tmp.getValueType(), Tmp));
3821 return;
Chris Lattnerf76e7dc2005-04-30 04:43:14 +00003822 }
Chris Lattner1ca85d52005-05-14 13:56:55 +00003823 }
Chris Lattner87b51bc2007-09-10 21:15:22 +00003824 }
Chris Lattnerce7518c2006-01-26 22:24:51 +00003825 } else if (isa<InlineAsm>(I.getOperand(0))) {
Duncan Sandsfd7b3262007-12-17 18:08:19 +00003826 visitInlineAsm(&I);
Chris Lattnerce7518c2006-01-26 22:24:51 +00003827 return;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003828 }
Misha Brukmanedf128a2005-04-21 22:36:52 +00003829
Dan Gohman475871a2008-07-27 21:46:04 +00003830 SDValue Callee;
Chris Lattner64e14b12005-01-08 22:48:57 +00003831 if (!RenameFn)
3832 Callee = getValue(I.getOperand(0));
3833 else
3834 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
Anton Korobeynikov070280e2007-05-23 11:08:31 +00003835
Duncan Sands6f74b482007-12-19 09:48:52 +00003836 LowerCallTo(&I, Callee, I.isTailCall());
Chris Lattner1c08c712005-01-07 07:47:53 +00003837}
3838
Jim Laskey735b6f82007-02-22 15:38:06 +00003839
Dan Gohmanb6f5b002007-06-28 23:29:44 +00003840/// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
3841/// this value and returns the result as a ValueVT value. This uses
3842/// Chain/Flag as the input and updates them for the output Chain/Flag.
3843/// If the Flag pointer is NULL, no flag is used.
Dan Gohman475871a2008-07-27 21:46:04 +00003844SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
3845 SDValue &Chain,
3846 SDValue *Flag) const {
Dan Gohman23ce5022008-04-25 18:27:55 +00003847 // Assemble the legal parts into the final values.
Dan Gohman475871a2008-07-27 21:46:04 +00003848 SmallVector<SDValue, 4> Values(ValueVTs.size());
3849 SmallVector<SDValue, 8> Parts;
Chris Lattner6833b062008-04-28 07:16:35 +00003850 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
Dan Gohman23ce5022008-04-25 18:27:55 +00003851 // Copy the legal parts from the registers.
Duncan Sands83ec4b62008-06-06 12:08:01 +00003852 MVT ValueVT = ValueVTs[Value];
Dan Gohman23ce5022008-04-25 18:27:55 +00003853 unsigned NumRegs = TLI->getNumRegisters(ValueVT);
Duncan Sands83ec4b62008-06-06 12:08:01 +00003854 MVT RegisterVT = RegVTs[Value];
Dan Gohman23ce5022008-04-25 18:27:55 +00003855
Chris Lattner6833b062008-04-28 07:16:35 +00003856 Parts.resize(NumRegs);
Dan Gohman23ce5022008-04-25 18:27:55 +00003857 for (unsigned i = 0; i != NumRegs; ++i) {
Dan Gohman475871a2008-07-27 21:46:04 +00003858 SDValue P;
Chris Lattner6833b062008-04-28 07:16:35 +00003859 if (Flag == 0)
3860 P = DAG.getCopyFromReg(Chain, Regs[Part+i], RegisterVT);
3861 else {
3862 P = DAG.getCopyFromReg(Chain, Regs[Part+i], RegisterVT, *Flag);
Dan Gohman23ce5022008-04-25 18:27:55 +00003863 *Flag = P.getValue(2);
Chris Lattner6833b062008-04-28 07:16:35 +00003864 }
3865 Chain = P.getValue(1);
Chris Lattneread0d882008-06-17 06:09:18 +00003866
3867 // If the source register was virtual and if we know something about it,
3868 // add an assert node.
3869 if (TargetRegisterInfo::isVirtualRegister(Regs[Part+i]) &&
3870 RegisterVT.isInteger() && !RegisterVT.isVector()) {
3871 unsigned SlotNo = Regs[Part+i]-TargetRegisterInfo::FirstVirtualRegister;
3872 FunctionLoweringInfo &FLI = DAG.getFunctionLoweringInfo();
3873 if (FLI.LiveOutRegInfo.size() > SlotNo) {
3874 FunctionLoweringInfo::LiveOutInfo &LOI = FLI.LiveOutRegInfo[SlotNo];
3875
3876 unsigned RegSize = RegisterVT.getSizeInBits();
3877 unsigned NumSignBits = LOI.NumSignBits;
3878 unsigned NumZeroBits = LOI.KnownZero.countLeadingOnes();
3879
3880 // FIXME: We capture more information than the dag can represent. For
3881 // now, just use the tightest assertzext/assertsext possible.
3882 bool isSExt = true;
3883 MVT FromVT(MVT::Other);
3884 if (NumSignBits == RegSize)
3885 isSExt = true, FromVT = MVT::i1; // ASSERT SEXT 1
3886 else if (NumZeroBits >= RegSize-1)
3887 isSExt = false, FromVT = MVT::i1; // ASSERT ZEXT 1
3888 else if (NumSignBits > RegSize-8)
3889 isSExt = true, FromVT = MVT::i8; // ASSERT SEXT 8
3890 else if (NumZeroBits >= RegSize-9)
3891 isSExt = false, FromVT = MVT::i8; // ASSERT ZEXT 8
3892 else if (NumSignBits > RegSize-16)
3893 isSExt = true, FromVT = MVT::i16; // ASSERT SEXT 16
3894 else if (NumZeroBits >= RegSize-17)
3895 isSExt = false, FromVT = MVT::i16; // ASSERT ZEXT 16
3896 else if (NumSignBits > RegSize-32)
3897 isSExt = true, FromVT = MVT::i32; // ASSERT SEXT 32
3898 else if (NumZeroBits >= RegSize-33)
3899 isSExt = false, FromVT = MVT::i32; // ASSERT ZEXT 32
3900
3901 if (FromVT != MVT::Other) {
3902 P = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext,
3903 RegisterVT, P, DAG.getValueType(FromVT));
3904
3905 }
3906 }
3907 }
3908
Dan Gohman23ce5022008-04-25 18:27:55 +00003909 Parts[Part+i] = P;
3910 }
Chris Lattner5df99b32007-03-25 05:00:54 +00003911
Dan Gohman23ce5022008-04-25 18:27:55 +00003912 Values[Value] = getCopyFromParts(DAG, &Parts[Part], NumRegs, RegisterVT,
3913 ValueVT);
3914 Part += NumRegs;
3915 }
Duncan Sands4bdcb612008-07-02 17:40:58 +00003916
Duncan Sandsf9516202008-06-30 10:19:09 +00003917 return DAG.getMergeValues(DAG.getVTList(&ValueVTs[0], ValueVTs.size()),
3918 &Values[0], ValueVTs.size());
Chris Lattner864635a2006-02-22 22:37:12 +00003919}
3920
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00003921/// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
3922/// specified value into the registers specified by this object. This uses
3923/// Chain/Flag as the input and updates them for the output Chain/Flag.
Dan Gohmanb6f5b002007-06-28 23:29:44 +00003924/// If the Flag pointer is NULL, no flag is used.
Dan Gohman475871a2008-07-27 21:46:04 +00003925void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG,
3926 SDValue &Chain, SDValue *Flag) const {
Dan Gohmanb6f5b002007-06-28 23:29:44 +00003927 // Get the list of the values's legal parts.
Dan Gohman23ce5022008-04-25 18:27:55 +00003928 unsigned NumRegs = Regs.size();
Dan Gohman475871a2008-07-27 21:46:04 +00003929 SmallVector<SDValue, 8> Parts(NumRegs);
Chris Lattner6833b062008-04-28 07:16:35 +00003930 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
Duncan Sands83ec4b62008-06-06 12:08:01 +00003931 MVT ValueVT = ValueVTs[Value];
Dan Gohman23ce5022008-04-25 18:27:55 +00003932 unsigned NumParts = TLI->getNumRegisters(ValueVT);
Duncan Sands83ec4b62008-06-06 12:08:01 +00003933 MVT RegisterVT = RegVTs[Value];
Dan Gohman23ce5022008-04-25 18:27:55 +00003934
Gabor Greif99a6cb92008-08-26 22:36:50 +00003935 getCopyToParts(DAG, Val.getValue(Val.getResNo() + Value),
Dan Gohman23ce5022008-04-25 18:27:55 +00003936 &Parts[Part], NumParts, RegisterVT);
3937 Part += NumParts;
3938 }
Dan Gohmanb6f5b002007-06-28 23:29:44 +00003939
3940 // Copy the parts into the registers.
Dan Gohman475871a2008-07-27 21:46:04 +00003941 SmallVector<SDValue, 8> Chains(NumRegs);
Dan Gohman23ce5022008-04-25 18:27:55 +00003942 for (unsigned i = 0; i != NumRegs; ++i) {
Dan Gohman475871a2008-07-27 21:46:04 +00003943 SDValue Part;
Chris Lattner6833b062008-04-28 07:16:35 +00003944 if (Flag == 0)
3945 Part = DAG.getCopyToReg(Chain, Regs[i], Parts[i]);
3946 else {
3947 Part = DAG.getCopyToReg(Chain, Regs[i], Parts[i], *Flag);
Dan Gohmanb6f5b002007-06-28 23:29:44 +00003948 *Flag = Part.getValue(1);
Chris Lattner6833b062008-04-28 07:16:35 +00003949 }
3950 Chains[i] = Part.getValue(0);
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00003951 }
Chris Lattner6833b062008-04-28 07:16:35 +00003952
Evan Cheng33bf38a2008-04-28 22:07:13 +00003953 if (NumRegs == 1 || Flag)
3954 // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is
3955 // flagged to it. That is the CopyToReg nodes and the user are considered
3956 // a single scheduling unit. If we create a TokenFactor and return it as
3957 // chain, then the TokenFactor is both a predecessor (operand) of the
3958 // user as well as a successor (the TF operands are flagged to the user).
3959 // c1, f1 = CopyToReg
3960 // c2, f2 = CopyToReg
3961 // c3 = TokenFactor c1, c2
3962 // ...
3963 // = op c3, ..., f2
3964 Chain = Chains[NumRegs-1];
Chris Lattner6833b062008-04-28 07:16:35 +00003965 else
3966 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other, &Chains[0], NumRegs);
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00003967}
Chris Lattner864635a2006-02-22 22:37:12 +00003968
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00003969/// AddInlineAsmOperands - Add this value to the specified inlineasm node
3970/// operand list. This adds the code marker and includes the number of
3971/// values added into it.
3972void RegsForValue::AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
Dan Gohman475871a2008-07-27 21:46:04 +00003973 std::vector<SDValue> &Ops) const {
Duncan Sands83ec4b62008-06-06 12:08:01 +00003974 MVT IntPtrTy = DAG.getTargetLoweringInfo().getPointerTy();
Chris Lattner4b993b12007-04-09 00:33:58 +00003975 Ops.push_back(DAG.getTargetConstant(Code | (Regs.size() << 3), IntPtrTy));
Chris Lattner6833b062008-04-28 07:16:35 +00003976 for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
3977 unsigned NumRegs = TLI->getNumRegisters(ValueVTs[Value]);
Duncan Sands83ec4b62008-06-06 12:08:01 +00003978 MVT RegisterVT = RegVTs[Value];
Chris Lattner6833b062008-04-28 07:16:35 +00003979 for (unsigned i = 0; i != NumRegs; ++i)
3980 Ops.push_back(DAG.getRegister(Regs[Reg++], RegisterVT));
Dan Gohman23ce5022008-04-25 18:27:55 +00003981 }
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00003982}
Chris Lattner864635a2006-02-22 22:37:12 +00003983
3984/// isAllocatableRegister - If the specified register is safe to allocate,
3985/// i.e. it isn't a stack pointer or some other special register, return the
3986/// register class for the register. Otherwise, return null.
3987static const TargetRegisterClass *
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00003988isAllocatableRegister(unsigned Reg, MachineFunction &MF,
Dan Gohman6f0d0242008-02-10 18:45:23 +00003989 const TargetLowering &TLI,
3990 const TargetRegisterInfo *TRI) {
Duncan Sands83ec4b62008-06-06 12:08:01 +00003991 MVT FoundVT = MVT::Other;
Chris Lattnerf8814cf2006-04-02 00:24:45 +00003992 const TargetRegisterClass *FoundRC = 0;
Dan Gohman6f0d0242008-02-10 18:45:23 +00003993 for (TargetRegisterInfo::regclass_iterator RCI = TRI->regclass_begin(),
3994 E = TRI->regclass_end(); RCI != E; ++RCI) {
Duncan Sands83ec4b62008-06-06 12:08:01 +00003995 MVT ThisVT = MVT::Other;
Chris Lattnerf8814cf2006-04-02 00:24:45 +00003996
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00003997 const TargetRegisterClass *RC = *RCI;
3998 // If none of the the value types for this register class are valid, we
3999 // can't use it. For example, 64-bit reg classes on 32-bit targets.
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00004000 for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
4001 I != E; ++I) {
4002 if (TLI.isTypeLegal(*I)) {
Chris Lattnerf8814cf2006-04-02 00:24:45 +00004003 // If we have already found this register in a different register class,
4004 // choose the one with the largest VT specified. For example, on
4005 // PowerPC, we favor f64 register classes over f32.
Duncan Sands8e4eb092008-06-08 20:54:56 +00004006 if (FoundVT == MVT::Other || FoundVT.bitsLT(*I)) {
Chris Lattnerf8814cf2006-04-02 00:24:45 +00004007 ThisVT = *I;
4008 break;
4009 }
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00004010 }
4011 }
4012
Chris Lattnerf8814cf2006-04-02 00:24:45 +00004013 if (ThisVT == MVT::Other) continue;
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00004014
Chris Lattner864635a2006-02-22 22:37:12 +00004015 // NOTE: This isn't ideal. In particular, this might allocate the
4016 // frame pointer in functions that need it (due to them not being taken
4017 // out of allocation, because a variable sized allocation hasn't been seen
4018 // yet). This is a slight code pessimization, but should still work.
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00004019 for (TargetRegisterClass::iterator I = RC->allocation_order_begin(MF),
4020 E = RC->allocation_order_end(MF); I != E; ++I)
Chris Lattnerf8814cf2006-04-02 00:24:45 +00004021 if (*I == Reg) {
4022 // We found a matching register class. Keep looking at others in case
4023 // we find one with larger registers that this physreg is also in.
4024 FoundRC = RC;
4025 FoundVT = ThisVT;
4026 break;
4027 }
Chris Lattner4e4b5762006-02-01 18:59:47 +00004028 }
Chris Lattnerf8814cf2006-04-02 00:24:45 +00004029 return FoundRC;
Chris Lattner864635a2006-02-22 22:37:12 +00004030}
4031
Chris Lattner4e4b5762006-02-01 18:59:47 +00004032
Chris Lattner0c583402007-04-28 20:49:53 +00004033namespace {
4034/// AsmOperandInfo - This contains information for each constraint that we are
4035/// lowering.
Evan Cheng5c807602008-02-26 02:33:44 +00004036struct SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo {
4037 /// CallOperand - If this is the result output operand or a clobber
4038 /// this is null, otherwise it is the incoming operand to the CallInst.
4039 /// This gets modified as the asm is processed.
Dan Gohman475871a2008-07-27 21:46:04 +00004040 SDValue CallOperand;
Evan Cheng5c807602008-02-26 02:33:44 +00004041
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004042 /// AssignedRegs - If this is a register or register class operand, this
4043 /// contains the set of register corresponding to the operand.
4044 RegsForValue AssignedRegs;
4045
Dan Gohman23ce5022008-04-25 18:27:55 +00004046 explicit SDISelAsmOperandInfo(const InlineAsm::ConstraintInfo &info)
Evan Cheng5c807602008-02-26 02:33:44 +00004047 : TargetLowering::AsmOperandInfo(info), CallOperand(0,0) {
Chris Lattner0c583402007-04-28 20:49:53 +00004048 }
Chris Lattner3ff90dc2007-04-30 17:16:27 +00004049
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004050 /// MarkAllocatedRegs - Once AssignedRegs is set, mark the assigned registers
4051 /// busy in OutputRegs/InputRegs.
4052 void MarkAllocatedRegs(bool isOutReg, bool isInReg,
4053 std::set<unsigned> &OutputRegs,
Chris Lattner7cbeb242008-02-21 04:55:52 +00004054 std::set<unsigned> &InputRegs,
4055 const TargetRegisterInfo &TRI) const {
4056 if (isOutReg) {
4057 for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i)
4058 MarkRegAndAliases(AssignedRegs.Regs[i], OutputRegs, TRI);
4059 }
4060 if (isInReg) {
4061 for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i)
4062 MarkRegAndAliases(AssignedRegs.Regs[i], InputRegs, TRI);
4063 }
4064 }
4065
4066private:
4067 /// MarkRegAndAliases - Mark the specified register and all aliases in the
4068 /// specified set.
4069 static void MarkRegAndAliases(unsigned Reg, std::set<unsigned> &Regs,
4070 const TargetRegisterInfo &TRI) {
4071 assert(TargetRegisterInfo::isPhysicalRegister(Reg) && "Isn't a physreg");
4072 Regs.insert(Reg);
4073 if (const unsigned *Aliases = TRI.getAliasSet(Reg))
4074 for (; *Aliases; ++Aliases)
4075 Regs.insert(*Aliases);
4076 }
Chris Lattner0c583402007-04-28 20:49:53 +00004077};
4078} // end anon namespace.
Chris Lattner864635a2006-02-22 22:37:12 +00004079
Chris Lattner3ff90dc2007-04-30 17:16:27 +00004080
Chris Lattner0fe71e92008-02-21 19:43:13 +00004081/// GetRegistersForValue - Assign registers (virtual or physical) for the
4082/// specified operand. We prefer to assign virtual registers, to allow the
4083/// register allocator handle the assignment process. However, if the asm uses
4084/// features that we can't model on machineinstrs, we have SDISel do the
4085/// allocation. This produces generally horrible, but correct, code.
4086///
4087/// OpInfo describes the operand.
4088/// HasEarlyClobber is true if there are any early clobber constraints (=&r)
4089/// or any explicitly clobbered registers.
4090/// Input and OutputRegs are the set of already allocated physical registers.
4091///
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004092void SelectionDAGLowering::
Evan Cheng5c807602008-02-26 02:33:44 +00004093GetRegistersForValue(SDISelAsmOperandInfo &OpInfo, bool HasEarlyClobber,
Chris Lattnerbf996f12007-04-30 17:29:31 +00004094 std::set<unsigned> &OutputRegs,
4095 std::set<unsigned> &InputRegs) {
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004096 // Compute whether this value requires an input register, an output register,
4097 // or both.
4098 bool isOutReg = false;
4099 bool isInReg = false;
4100 switch (OpInfo.Type) {
4101 case InlineAsm::isOutput:
4102 isOutReg = true;
4103
4104 // If this is an early-clobber output, or if there is an input
4105 // constraint that matches this, we need to reserve the input register
4106 // so no other inputs allocate to it.
4107 isInReg = OpInfo.isEarlyClobber || OpInfo.hasMatchingInput;
4108 break;
4109 case InlineAsm::isInput:
4110 isInReg = true;
4111 isOutReg = false;
4112 break;
4113 case InlineAsm::isClobber:
4114 isOutReg = true;
4115 isInReg = true;
4116 break;
4117 }
4118
4119
4120 MachineFunction &MF = DAG.getMachineFunction();
Chris Lattnerb606dba2008-04-28 06:44:42 +00004121 SmallVector<unsigned, 4> Regs;
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004122
4123 // If this is a constraint for a single physreg, or a constraint for a
4124 // register class, find it.
4125 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
4126 TLI.getRegForInlineAsmConstraint(OpInfo.ConstraintCode,
4127 OpInfo.ConstraintVT);
Chris Lattnerbf996f12007-04-30 17:29:31 +00004128
4129 unsigned NumRegs = 1;
4130 if (OpInfo.ConstraintVT != MVT::Other)
Dan Gohmanb9f10192007-06-21 14:42:22 +00004131 NumRegs = TLI.getNumRegisters(OpInfo.ConstraintVT);
Duncan Sands83ec4b62008-06-06 12:08:01 +00004132 MVT RegVT;
4133 MVT ValueVT = OpInfo.ConstraintVT;
Chris Lattnerbf996f12007-04-30 17:29:31 +00004134
Chris Lattnerbf996f12007-04-30 17:29:31 +00004135
4136 // If this is a constraint for a specific physical register, like {r17},
4137 // assign it now.
4138 if (PhysReg.first) {
4139 if (OpInfo.ConstraintVT == MVT::Other)
4140 ValueVT = *PhysReg.second->vt_begin();
4141
4142 // Get the actual register value type. This is important, because the user
4143 // may have asked for (e.g.) the AX register in i32 type. We need to
4144 // remember that AX is actually i16 to get the right extension.
4145 RegVT = *PhysReg.second->vt_begin();
4146
4147 // This is a explicit reference to a physical register.
4148 Regs.push_back(PhysReg.first);
4149
4150 // If this is an expanded reference, add the rest of the regs to Regs.
4151 if (NumRegs != 1) {
4152 TargetRegisterClass::iterator I = PhysReg.second->begin();
Chris Lattnerbf996f12007-04-30 17:29:31 +00004153 for (; *I != PhysReg.first; ++I)
Evan Cheng50871242008-05-14 20:07:51 +00004154 assert(I != PhysReg.second->end() && "Didn't find reg!");
Chris Lattnerbf996f12007-04-30 17:29:31 +00004155
4156 // Already added the first reg.
4157 --NumRegs; ++I;
4158 for (; NumRegs; --NumRegs, ++I) {
Evan Cheng50871242008-05-14 20:07:51 +00004159 assert(I != PhysReg.second->end() && "Ran out of registers to allocate!");
Chris Lattnerbf996f12007-04-30 17:29:31 +00004160 Regs.push_back(*I);
4161 }
4162 }
Dan Gohman23ce5022008-04-25 18:27:55 +00004163 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, RegVT, ValueVT);
Chris Lattner7cbeb242008-02-21 04:55:52 +00004164 const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
4165 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TRI);
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004166 return;
Chris Lattnerbf996f12007-04-30 17:29:31 +00004167 }
4168
4169 // Otherwise, if this was a reference to an LLVM register class, create vregs
4170 // for this reference.
4171 std::vector<unsigned> RegClassRegs;
Chris Lattnerc2c28fc2007-06-15 19:11:01 +00004172 const TargetRegisterClass *RC = PhysReg.second;
4173 if (RC) {
Chris Lattnerbf996f12007-04-30 17:29:31 +00004174 // If this is an early clobber or tied register, our regalloc doesn't know
4175 // how to maintain the constraint. If it isn't, go ahead and create vreg
4176 // and let the regalloc do the right thing.
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004177 if (!OpInfo.hasMatchingInput && !OpInfo.isEarlyClobber &&
4178 // If there is some other early clobber and this is an input register,
4179 // then we are forced to pre-allocate the input reg so it doesn't
4180 // conflict with the earlyclobber.
4181 !(OpInfo.Type == InlineAsm::isInput && HasEarlyClobber)) {
Chris Lattnerbf996f12007-04-30 17:29:31 +00004182 RegVT = *PhysReg.second->vt_begin();
4183
4184 if (OpInfo.ConstraintVT == MVT::Other)
4185 ValueVT = RegVT;
4186
4187 // Create the appropriate number of virtual registers.
Chris Lattner84bc5422007-12-31 04:13:23 +00004188 MachineRegisterInfo &RegInfo = MF.getRegInfo();
Chris Lattnerbf996f12007-04-30 17:29:31 +00004189 for (; NumRegs; --NumRegs)
Chris Lattner84bc5422007-12-31 04:13:23 +00004190 Regs.push_back(RegInfo.createVirtualRegister(PhysReg.second));
Chris Lattnerbf996f12007-04-30 17:29:31 +00004191
Dan Gohman23ce5022008-04-25 18:27:55 +00004192 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, RegVT, ValueVT);
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004193 return;
Chris Lattnerbf996f12007-04-30 17:29:31 +00004194 }
4195
4196 // Otherwise, we can't allocate it. Let the code below figure out how to
4197 // maintain these constraints.
4198 RegClassRegs.assign(PhysReg.second->begin(), PhysReg.second->end());
4199
4200 } else {
4201 // This is a reference to a register class that doesn't directly correspond
4202 // to an LLVM register class. Allocate NumRegs consecutive, available,
4203 // registers from the class.
4204 RegClassRegs = TLI.getRegClassForInlineAsmConstraint(OpInfo.ConstraintCode,
4205 OpInfo.ConstraintVT);
4206 }
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004207
Dan Gohman6f0d0242008-02-10 18:45:23 +00004208 const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
Chris Lattnerbf996f12007-04-30 17:29:31 +00004209 unsigned NumAllocated = 0;
4210 for (unsigned i = 0, e = RegClassRegs.size(); i != e; ++i) {
4211 unsigned Reg = RegClassRegs[i];
4212 // See if this register is available.
4213 if ((isOutReg && OutputRegs.count(Reg)) || // Already used.
4214 (isInReg && InputRegs.count(Reg))) { // Already used.
4215 // Make sure we find consecutive registers.
4216 NumAllocated = 0;
4217 continue;
4218 }
4219
4220 // Check to see if this register is allocatable (i.e. don't give out the
4221 // stack pointer).
Chris Lattnerc2c28fc2007-06-15 19:11:01 +00004222 if (RC == 0) {
Dan Gohman6f0d0242008-02-10 18:45:23 +00004223 RC = isAllocatableRegister(Reg, MF, TLI, TRI);
Chris Lattnerc2c28fc2007-06-15 19:11:01 +00004224 if (!RC) { // Couldn't allocate this register.
4225 // Reset NumAllocated to make sure we return consecutive registers.
4226 NumAllocated = 0;
4227 continue;
4228 }
Chris Lattnerbf996f12007-04-30 17:29:31 +00004229 }
4230
4231 // Okay, this register is good, we can use it.
4232 ++NumAllocated;
4233
4234 // If we allocated enough consecutive registers, succeed.
4235 if (NumAllocated == NumRegs) {
4236 unsigned RegStart = (i-NumAllocated)+1;
4237 unsigned RegEnd = i+1;
4238 // Mark all of the allocated registers used.
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004239 for (unsigned i = RegStart; i != RegEnd; ++i)
4240 Regs.push_back(RegClassRegs[i]);
Chris Lattnerbf996f12007-04-30 17:29:31 +00004241
Dan Gohman23ce5022008-04-25 18:27:55 +00004242 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, *RC->vt_begin(),
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004243 OpInfo.ConstraintVT);
Chris Lattner7cbeb242008-02-21 04:55:52 +00004244 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TRI);
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004245 return;
Chris Lattnerbf996f12007-04-30 17:29:31 +00004246 }
4247 }
4248
4249 // Otherwise, we couldn't allocate enough registers for this.
Chris Lattnerbf996f12007-04-30 17:29:31 +00004250}
4251
4252
Chris Lattnerce7518c2006-01-26 22:24:51 +00004253/// visitInlineAsm - Handle a call to an InlineAsm object.
4254///
Duncan Sandsfd7b3262007-12-17 18:08:19 +00004255void SelectionDAGLowering::visitInlineAsm(CallSite CS) {
4256 InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
Chris Lattnerce7518c2006-01-26 22:24:51 +00004257
Chris Lattner0c583402007-04-28 20:49:53 +00004258 /// ConstraintOperands - Information about all of the constraints.
Evan Cheng5c807602008-02-26 02:33:44 +00004259 std::vector<SDISelAsmOperandInfo> ConstraintOperands;
Chris Lattnerce7518c2006-01-26 22:24:51 +00004260
Dan Gohman475871a2008-07-27 21:46:04 +00004261 SDValue Chain = getRoot();
4262 SDValue Flag;
Chris Lattnerce7518c2006-01-26 22:24:51 +00004263
Chris Lattner4e4b5762006-02-01 18:59:47 +00004264 std::set<unsigned> OutputRegs, InputRegs;
Chris Lattner1efa40f2006-02-22 00:56:39 +00004265
Chris Lattner0c583402007-04-28 20:49:53 +00004266 // Do a prepass over the constraints, canonicalizing them, and building up the
4267 // ConstraintOperands list.
4268 std::vector<InlineAsm::ConstraintInfo>
4269 ConstraintInfos = IA->ParseConstraints();
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004270
4271 // SawEarlyClobber - Keep track of whether we saw an earlyclobber output
4272 // constraint. If so, we can't let the register allocator allocate any input
4273 // registers, because it will not know to avoid the earlyclobbered output reg.
4274 bool SawEarlyClobber = false;
4275
Duncan Sandsfd7b3262007-12-17 18:08:19 +00004276 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst.
Chris Lattneracf8b012008-04-27 23:44:28 +00004277 unsigned ResNo = 0; // ResNo - The result number of the next output.
Chris Lattner0c583402007-04-28 20:49:53 +00004278 for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) {
Evan Cheng5c807602008-02-26 02:33:44 +00004279 ConstraintOperands.push_back(SDISelAsmOperandInfo(ConstraintInfos[i]));
4280 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
Chris Lattner0c583402007-04-28 20:49:53 +00004281
Duncan Sands83ec4b62008-06-06 12:08:01 +00004282 MVT OpVT = MVT::Other;
Chris Lattner0c583402007-04-28 20:49:53 +00004283
4284 // Compute the value type for each operand.
4285 switch (OpInfo.Type) {
Chris Lattner1efa40f2006-02-22 00:56:39 +00004286 case InlineAsm::isOutput:
Chris Lattneracf8b012008-04-27 23:44:28 +00004287 // Indirect outputs just consume an argument.
4288 if (OpInfo.isIndirect) {
Duncan Sandsfd7b3262007-12-17 18:08:19 +00004289 OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
Chris Lattneracf8b012008-04-27 23:44:28 +00004290 break;
Chris Lattner1efa40f2006-02-22 00:56:39 +00004291 }
Chris Lattneracf8b012008-04-27 23:44:28 +00004292 // The return value of the call is this value. As such, there is no
4293 // corresponding argument.
4294 assert(CS.getType() != Type::VoidTy && "Bad inline asm!");
4295 if (const StructType *STy = dyn_cast<StructType>(CS.getType())) {
4296 OpVT = TLI.getValueType(STy->getElementType(ResNo));
4297 } else {
4298 assert(ResNo == 0 && "Asm only has one result!");
4299 OpVT = TLI.getValueType(CS.getType());
4300 }
4301 ++ResNo;
Chris Lattner1efa40f2006-02-22 00:56:39 +00004302 break;
4303 case InlineAsm::isInput:
Duncan Sandsfd7b3262007-12-17 18:08:19 +00004304 OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
Chris Lattner1efa40f2006-02-22 00:56:39 +00004305 break;
4306 case InlineAsm::isClobber:
Chris Lattner0c583402007-04-28 20:49:53 +00004307 // Nothing to do.
Chris Lattner1efa40f2006-02-22 00:56:39 +00004308 break;
4309 }
Chris Lattner1efa40f2006-02-22 00:56:39 +00004310
Chris Lattner0c583402007-04-28 20:49:53 +00004311 // If this is an input or an indirect output, process the call argument.
Dale Johanneseneb57ea72007-11-05 21:20:28 +00004312 // BasicBlocks are labels, currently appearing only in asm's.
Chris Lattner0c583402007-04-28 20:49:53 +00004313 if (OpInfo.CallOperandVal) {
Chris Lattner507ffd22008-04-27 00:16:18 +00004314 if (BasicBlock *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal))
4315 OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
Dale Johanneseneb57ea72007-11-05 21:20:28 +00004316 else {
4317 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
4318 const Type *OpTy = OpInfo.CallOperandVal->getType();
4319 // If this is an indirect operand, the operand is a pointer to the
4320 // accessed type.
4321 if (OpInfo.isIndirect)
4322 OpTy = cast<PointerType>(OpTy)->getElementType();
4323
Dan Gohman4fa2a3f2008-05-23 00:34:04 +00004324 // If OpTy is not a single value, it may be a struct/union that we
Dale Johanneseneb57ea72007-11-05 21:20:28 +00004325 // can tile with integers.
Dan Gohman4fa2a3f2008-05-23 00:34:04 +00004326 if (!OpTy->isSingleValueType() && OpTy->isSized()) {
Dale Johanneseneb57ea72007-11-05 21:20:28 +00004327 unsigned BitSize = TD->getTypeSizeInBits(OpTy);
4328 switch (BitSize) {
4329 default: break;
4330 case 1:
4331 case 8:
4332 case 16:
4333 case 32:
4334 case 64:
4335 OpTy = IntegerType::get(BitSize);
4336 break;
4337 }
Chris Lattner6995cf62007-04-29 18:58:03 +00004338 }
Dale Johanneseneb57ea72007-11-05 21:20:28 +00004339
4340 OpVT = TLI.getValueType(OpTy, true);
Chris Lattner0c583402007-04-28 20:49:53 +00004341 }
4342 }
4343
4344 OpInfo.ConstraintVT = OpVT;
Chris Lattner2a600be2007-04-28 21:01:43 +00004345
Chris Lattner3ff90dc2007-04-30 17:16:27 +00004346 // Compute the constraint code and ConstraintType to use.
Chris Lattner5a096902008-04-27 00:37:18 +00004347 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
Chris Lattner0c583402007-04-28 20:49:53 +00004348
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004349 // Keep track of whether we see an earlyclobber.
4350 SawEarlyClobber |= OpInfo.isEarlyClobber;
Chris Lattner09e4b7e2007-04-28 21:12:06 +00004351
Chris Lattner0fe71e92008-02-21 19:43:13 +00004352 // If we see a clobber of a register, it is an early clobber.
Chris Lattner69e6a8d2008-02-21 20:54:31 +00004353 if (!SawEarlyClobber &&
4354 OpInfo.Type == InlineAsm::isClobber &&
4355 OpInfo.ConstraintType == TargetLowering::C_Register) {
Chris Lattner09c5d8b2008-08-26 06:07:47 +00004356 // Note that we want to ignore things that we don't track here, like
Chris Lattner69e6a8d2008-02-21 20:54:31 +00004357 // dirflag, fpsr, flags, etc.
4358 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
4359 TLI.getRegForInlineAsmConstraint(OpInfo.ConstraintCode,
4360 OpInfo.ConstraintVT);
4361 if (PhysReg.first || PhysReg.second) {
4362 // This is a register we know of.
4363 SawEarlyClobber = true;
4364 }
4365 }
Chris Lattner0fe71e92008-02-21 19:43:13 +00004366
Chris Lattner09e4b7e2007-04-28 21:12:06 +00004367 // If this is a memory input, and if the operand is not indirect, do what we
4368 // need to to provide an address for the memory input.
4369 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
4370 !OpInfo.isIndirect) {
4371 assert(OpInfo.Type == InlineAsm::isInput &&
4372 "Can only indirectify direct input operands!");
4373
4374 // Memory operands really want the address of the value. If we don't have
4375 // an indirect input, put it in the constpool if we can, otherwise spill
4376 // it to a stack slot.
4377
4378 // If the operand is a float, integer, or vector constant, spill to a
4379 // constant pool entry to get its address.
4380 Value *OpVal = OpInfo.CallOperandVal;
4381 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
4382 isa<ConstantVector>(OpVal)) {
4383 OpInfo.CallOperand = DAG.getConstantPool(cast<Constant>(OpVal),
4384 TLI.getPointerTy());
4385 } else {
4386 // Otherwise, create a stack slot and emit a store to it before the
4387 // asm.
4388 const Type *Ty = OpVal->getType();
Duncan Sands514ab342007-11-01 20:53:16 +00004389 uint64_t TySize = TLI.getTargetData()->getABITypeSize(Ty);
Chris Lattner09e4b7e2007-04-28 21:12:06 +00004390 unsigned Align = TLI.getTargetData()->getPrefTypeAlignment(Ty);
4391 MachineFunction &MF = DAG.getMachineFunction();
4392 int SSFI = MF.getFrameInfo()->CreateStackObject(TySize, Align);
Dan Gohman475871a2008-07-27 21:46:04 +00004393 SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getPointerTy());
Chris Lattner09e4b7e2007-04-28 21:12:06 +00004394 Chain = DAG.getStore(Chain, OpInfo.CallOperand, StackSlot, NULL, 0);
4395 OpInfo.CallOperand = StackSlot;
4396 }
4397
4398 // There is no longer a Value* corresponding to this operand.
4399 OpInfo.CallOperandVal = 0;
4400 // It is now an indirect operand.
4401 OpInfo.isIndirect = true;
4402 }
4403
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004404 // If this constraint is for a specific register, allocate it before
4405 // anything else.
4406 if (OpInfo.ConstraintType == TargetLowering::C_Register)
4407 GetRegistersForValue(OpInfo, SawEarlyClobber, OutputRegs, InputRegs);
Chris Lattner0c583402007-04-28 20:49:53 +00004408 }
Chris Lattner0c583402007-04-28 20:49:53 +00004409 ConstraintInfos.clear();
4410
4411
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004412 // Second pass - Loop over all of the operands, assigning virtual or physregs
4413 // to registerclass operands.
4414 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
Evan Cheng5c807602008-02-26 02:33:44 +00004415 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004416
4417 // C_Register operands have already been allocated, Other/Memory don't need
4418 // to be.
4419 if (OpInfo.ConstraintType == TargetLowering::C_RegisterClass)
4420 GetRegistersForValue(OpInfo, SawEarlyClobber, OutputRegs, InputRegs);
4421 }
4422
Chris Lattner0c583402007-04-28 20:49:53 +00004423 // AsmNodeOperands - The operands for the ISD::INLINEASM node.
Dan Gohman475871a2008-07-27 21:46:04 +00004424 std::vector<SDValue> AsmNodeOperands;
4425 AsmNodeOperands.push_back(SDValue()); // reserve space for input chain
Chris Lattner0c583402007-04-28 20:49:53 +00004426 AsmNodeOperands.push_back(
4427 DAG.getTargetExternalSymbol(IA->getAsmString().c_str(), MVT::Other));
4428
Chris Lattner2cc2f662006-02-01 01:28:23 +00004429
Chris Lattner0f0b7d42006-02-21 23:12:12 +00004430 // Loop over all of the inputs, copying the operand values into the
4431 // appropriate registers and processing the output regs.
Chris Lattner864635a2006-02-22 22:37:12 +00004432 RegsForValue RetValRegs;
Chris Lattner41f62592008-04-29 04:29:54 +00004433
Chris Lattner0c583402007-04-28 20:49:53 +00004434 // IndirectStoresToEmit - The set of stores to emit after the inline asm node.
4435 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
4436
4437 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
Evan Cheng5c807602008-02-26 02:33:44 +00004438 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
Chris Lattner1efa40f2006-02-22 00:56:39 +00004439
Chris Lattner0c583402007-04-28 20:49:53 +00004440 switch (OpInfo.Type) {
Chris Lattner2cc2f662006-02-01 01:28:23 +00004441 case InlineAsm::isOutput: {
Chris Lattnerc83994e2007-04-28 21:03:16 +00004442 if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass &&
4443 OpInfo.ConstraintType != TargetLowering::C_Register) {
Chris Lattnerf2f3cd52007-04-28 06:08:13 +00004444 // Memory output, or 'other' output (e.g. 'X' constraint).
Chris Lattner09e4b7e2007-04-28 21:12:06 +00004445 assert(OpInfo.isIndirect && "Memory output must be indirect operand");
Chris Lattner22873462006-02-27 23:45:39 +00004446
Chris Lattner22873462006-02-27 23:45:39 +00004447 // Add information to the INLINEASM node to know about this output.
4448 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
Chris Lattnerc90233b2007-05-15 01:33:58 +00004449 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
4450 TLI.getPointerTy()));
Chris Lattner09e4b7e2007-04-28 21:12:06 +00004451 AsmNodeOperands.push_back(OpInfo.CallOperand);
Chris Lattner22873462006-02-27 23:45:39 +00004452 break;
4453 }
4454
Chris Lattner2a600be2007-04-28 21:01:43 +00004455 // Otherwise, this is a register or register class output.
Chris Lattner22873462006-02-27 23:45:39 +00004456
Chris Lattner864635a2006-02-22 22:37:12 +00004457 // Copy the output from the appropriate register. Find a register that
Chris Lattner1efa40f2006-02-22 00:56:39 +00004458 // we can use.
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004459 if (OpInfo.AssignedRegs.Regs.empty()) {
Duncan Sandsa47c6c32008-06-17 03:24:13 +00004460 cerr << "Couldn't allocate output reg for constraint '"
Chris Lattner0c583402007-04-28 20:49:53 +00004461 << OpInfo.ConstraintCode << "'!\n";
Chris Lattnerd03f1582006-10-31 07:33:13 +00004462 exit(1);
4463 }
Chris Lattner1efa40f2006-02-22 00:56:39 +00004464
Chris Lattner41f62592008-04-29 04:29:54 +00004465 // If this is an indirect operand, store through the pointer after the
4466 // asm.
4467 if (OpInfo.isIndirect) {
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004468 IndirectStoresToEmit.push_back(std::make_pair(OpInfo.AssignedRegs,
Chris Lattner0c583402007-04-28 20:49:53 +00004469 OpInfo.CallOperandVal));
Chris Lattner41f62592008-04-29 04:29:54 +00004470 } else {
4471 // This is the result value of the call.
4472 assert(CS.getType() != Type::VoidTy && "Bad inline asm!");
4473 // Concatenate this output onto the outputs list.
4474 RetValRegs.append(OpInfo.AssignedRegs);
Chris Lattner2cc2f662006-02-01 01:28:23 +00004475 }
Chris Lattner6656dd12006-01-31 02:03:41 +00004476
4477 // Add information to the INLINEASM node to know that this register is
4478 // set.
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004479 OpInfo.AssignedRegs.AddInlineAsmOperands(2 /*REGDEF*/, DAG,
4480 AsmNodeOperands);
Chris Lattner6656dd12006-01-31 02:03:41 +00004481 break;
4482 }
4483 case InlineAsm::isInput: {
Dan Gohman475871a2008-07-27 21:46:04 +00004484 SDValue InOperandVal = OpInfo.CallOperand;
Chris Lattner3d81fee2006-02-04 02:16:44 +00004485
Chris Lattner0c583402007-04-28 20:49:53 +00004486 if (isdigit(OpInfo.ConstraintCode[0])) { // Matching constraint?
Chris Lattner2223aea2006-02-02 00:25:23 +00004487 // If this is required to match an output register we have already set,
4488 // just use its register.
Chris Lattner0c583402007-04-28 20:49:53 +00004489 unsigned OperandNo = atoi(OpInfo.ConstraintCode.c_str());
Chris Lattner3d81fee2006-02-04 02:16:44 +00004490
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00004491 // Scan until we find the definition we already emitted of this operand.
4492 // When we find it, create a RegsForValue operand.
4493 unsigned CurOp = 2; // The first operand.
4494 for (; OperandNo; --OperandNo) {
4495 // Advance to the next operand.
4496 unsigned NumOps =
4497 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
Chris Lattnera15cf702006-07-20 19:02:21 +00004498 assert(((NumOps & 7) == 2 /*REGDEF*/ ||
4499 (NumOps & 7) == 4 /*MEM*/) &&
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00004500 "Skipped past definitions?");
4501 CurOp += (NumOps>>3)+1;
4502 }
4503
4504 unsigned NumOps =
4505 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
Chris Lattner527fae12007-02-01 01:21:12 +00004506 if ((NumOps & 7) == 2 /*REGDEF*/) {
4507 // Add NumOps>>3 registers to MatchedRegs.
4508 RegsForValue MatchedRegs;
Dan Gohman23ce5022008-04-25 18:27:55 +00004509 MatchedRegs.TLI = &TLI;
Dan Gohman1fa850b2008-05-02 00:03:54 +00004510 MatchedRegs.ValueVTs.push_back(InOperandVal.getValueType());
4511 MatchedRegs.RegVTs.push_back(AsmNodeOperands[CurOp+1].getValueType());
Chris Lattner527fae12007-02-01 01:21:12 +00004512 for (unsigned i = 0, e = NumOps>>3; i != e; ++i) {
4513 unsigned Reg =
4514 cast<RegisterSDNode>(AsmNodeOperands[++CurOp])->getReg();
4515 MatchedRegs.Regs.push_back(Reg);
4516 }
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00004517
Chris Lattner527fae12007-02-01 01:21:12 +00004518 // Use the produced MatchedRegs object to
Dan Gohmanb6f5b002007-06-28 23:29:44 +00004519 MatchedRegs.getCopyToRegs(InOperandVal, DAG, Chain, &Flag);
Chris Lattner527fae12007-02-01 01:21:12 +00004520 MatchedRegs.AddInlineAsmOperands(1 /*REGUSE*/, DAG, AsmNodeOperands);
4521 break;
4522 } else {
4523 assert((NumOps & 7) == 4/*MEM*/ && "Unknown matching constraint!");
Chris Lattnerf9853bc2008-02-21 05:27:19 +00004524 assert((NumOps >> 3) == 1 && "Unexpected number of operands");
4525 // Add information to the INLINEASM node to know about this input.
4526 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
4527 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
4528 TLI.getPointerTy()));
4529 AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
4530 break;
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00004531 }
Chris Lattner2223aea2006-02-02 00:25:23 +00004532 }
Chris Lattner87bc3bd2006-02-24 01:11:24 +00004533
Chris Lattner2a600be2007-04-28 21:01:43 +00004534 if (OpInfo.ConstraintType == TargetLowering::C_Other) {
Chris Lattner0c583402007-04-28 20:49:53 +00004535 assert(!OpInfo.isIndirect &&
Chris Lattner44b2c502007-04-28 06:42:38 +00004536 "Don't know how to handle indirect other inputs yet!");
4537
Dan Gohman475871a2008-07-27 21:46:04 +00004538 std::vector<SDValue> Ops;
Chris Lattner48884cd2007-08-25 00:47:38 +00004539 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode[0],
4540 Ops, DAG);
4541 if (Ops.empty()) {
Bill Wendling832171c2006-12-07 20:04:42 +00004542 cerr << "Invalid operand for inline asm constraint '"
Chris Lattner0c583402007-04-28 20:49:53 +00004543 << OpInfo.ConstraintCode << "'!\n";
Chris Lattner53069fb2006-10-31 19:41:18 +00004544 exit(1);
4545 }
Chris Lattner87bc3bd2006-02-24 01:11:24 +00004546
4547 // Add information to the INLINEASM node to know about this input.
Chris Lattner48884cd2007-08-25 00:47:38 +00004548 unsigned ResOpType = 3 /*IMM*/ | (Ops.size() << 3);
Chris Lattnerc90233b2007-05-15 01:33:58 +00004549 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
4550 TLI.getPointerTy()));
Chris Lattner48884cd2007-08-25 00:47:38 +00004551 AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end());
Chris Lattner87bc3bd2006-02-24 01:11:24 +00004552 break;
Chris Lattner2a600be2007-04-28 21:01:43 +00004553 } else if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
Chris Lattner09e4b7e2007-04-28 21:12:06 +00004554 assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
Chris Lattner44b2c502007-04-28 06:42:38 +00004555 assert(InOperandVal.getValueType() == TLI.getPointerTy() &&
4556 "Memory operands expect pointer values");
4557
Chris Lattner87bc3bd2006-02-24 01:11:24 +00004558 // Add information to the INLINEASM node to know about this input.
4559 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
Chris Lattnerc90233b2007-05-15 01:33:58 +00004560 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
4561 TLI.getPointerTy()));
Chris Lattner87bc3bd2006-02-24 01:11:24 +00004562 AsmNodeOperands.push_back(InOperandVal);
4563 break;
4564 }
4565
Chris Lattner2a600be2007-04-28 21:01:43 +00004566 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
4567 OpInfo.ConstraintType == TargetLowering::C_Register) &&
4568 "Unknown constraint type!");
Chris Lattner0c583402007-04-28 20:49:53 +00004569 assert(!OpInfo.isIndirect &&
Chris Lattner44b2c502007-04-28 06:42:38 +00004570 "Don't know how to handle indirect register inputs yet!");
Chris Lattner87bc3bd2006-02-24 01:11:24 +00004571
4572 // Copy the input into the appropriate registers.
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004573 assert(!OpInfo.AssignedRegs.Regs.empty() &&
4574 "Couldn't allocate input reg!");
Chris Lattner87bc3bd2006-02-24 01:11:24 +00004575
Dan Gohmanb6f5b002007-06-28 23:29:44 +00004576 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, Chain, &Flag);
Chris Lattner87bc3bd2006-02-24 01:11:24 +00004577
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004578 OpInfo.AssignedRegs.AddInlineAsmOperands(1/*REGUSE*/, DAG,
4579 AsmNodeOperands);
Chris Lattner6656dd12006-01-31 02:03:41 +00004580 break;
4581 }
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00004582 case InlineAsm::isClobber: {
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00004583 // Add the clobbered value to the operand list, so that the register
4584 // allocator is aware that the physreg got clobbered.
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004585 if (!OpInfo.AssignedRegs.Regs.empty())
4586 OpInfo.AssignedRegs.AddInlineAsmOperands(2/*REGDEF*/, DAG,
4587 AsmNodeOperands);
Chris Lattner6656dd12006-01-31 02:03:41 +00004588 break;
4589 }
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00004590 }
Chris Lattner6656dd12006-01-31 02:03:41 +00004591 }
Chris Lattnerce7518c2006-01-26 22:24:51 +00004592
4593 // Finish up input operands.
4594 AsmNodeOperands[0] = Chain;
4595 if (Flag.Val) AsmNodeOperands.push_back(Flag);
4596
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00004597 Chain = DAG.getNode(ISD::INLINEASM,
4598 DAG.getNodeValueTypes(MVT::Other, MVT::Flag), 2,
Chris Lattnerbd564bf2006-08-08 02:23:42 +00004599 &AsmNodeOperands[0], AsmNodeOperands.size());
Chris Lattnerce7518c2006-01-26 22:24:51 +00004600 Flag = Chain.getValue(1);
4601
Chris Lattner6656dd12006-01-31 02:03:41 +00004602 // If this asm returns a register value, copy the result from that register
4603 // and set it as the value of the call.
Chris Lattner3a508c92007-04-12 06:00:20 +00004604 if (!RetValRegs.Regs.empty()) {
Dan Gohman475871a2008-07-27 21:46:04 +00004605 SDValue Val = RetValRegs.getCopyFromRegs(DAG, Chain, &Flag);
Chris Lattner3fb29682008-04-29 04:48:56 +00004606
4607 // If any of the results of the inline asm is a vector, it may have the
4608 // wrong width/num elts. This can happen for register classes that can
4609 // contain multiple different value types. The preg or vreg allocated may
4610 // not have the same VT as was expected. Convert it to the right type with
Dan Gohman7f321562007-06-25 16:23:39 +00004611 // bit_convert.
Chris Lattner3fb29682008-04-29 04:48:56 +00004612 if (const StructType *ResSTy = dyn_cast<StructType>(CS.getType())) {
4613 for (unsigned i = 0, e = ResSTy->getNumElements(); i != e; ++i) {
Duncan Sands83ec4b62008-06-06 12:08:01 +00004614 if (Val.Val->getValueType(i).isVector())
Chris Lattner3fb29682008-04-29 04:48:56 +00004615 Val = DAG.getNode(ISD::BIT_CONVERT,
4616 TLI.getValueType(ResSTy->getElementType(i)), Val);
4617 }
4618 } else {
Duncan Sands83ec4b62008-06-06 12:08:01 +00004619 if (Val.getValueType().isVector())
Chris Lattner3fb29682008-04-29 04:48:56 +00004620 Val = DAG.getNode(ISD::BIT_CONVERT, TLI.getValueType(CS.getType()),
4621 Val);
Chris Lattner3a508c92007-04-12 06:00:20 +00004622 }
Chris Lattner3fb29682008-04-29 04:48:56 +00004623
Duncan Sandsfd7b3262007-12-17 18:08:19 +00004624 setValue(CS.getInstruction(), Val);
Chris Lattner3a508c92007-04-12 06:00:20 +00004625 }
Chris Lattnerce7518c2006-01-26 22:24:51 +00004626
Dan Gohman475871a2008-07-27 21:46:04 +00004627 std::vector<std::pair<SDValue, Value*> > StoresToEmit;
Chris Lattner6656dd12006-01-31 02:03:41 +00004628
4629 // Process indirect outputs, first output all of the flagged copies out of
4630 // physregs.
4631 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
Chris Lattner864635a2006-02-22 22:37:12 +00004632 RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
Chris Lattner6656dd12006-01-31 02:03:41 +00004633 Value *Ptr = IndirectStoresToEmit[i].second;
Dan Gohman475871a2008-07-27 21:46:04 +00004634 SDValue OutVal = OutRegs.getCopyFromRegs(DAG, Chain, &Flag);
Chris Lattner864635a2006-02-22 22:37:12 +00004635 StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
Chris Lattner6656dd12006-01-31 02:03:41 +00004636 }
4637
4638 // Emit the non-flagged stores from the physregs.
Dan Gohman475871a2008-07-27 21:46:04 +00004639 SmallVector<SDValue, 8> OutChains;
Chris Lattner6656dd12006-01-31 02:03:41 +00004640 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i)
Chris Lattner0c583402007-04-28 20:49:53 +00004641 OutChains.push_back(DAG.getStore(Chain, StoresToEmit[i].first,
Chris Lattner6656dd12006-01-31 02:03:41 +00004642 getValue(StoresToEmit[i].second),
Evan Cheng8b2794a2006-10-13 21:14:26 +00004643 StoresToEmit[i].second, 0));
Chris Lattner6656dd12006-01-31 02:03:41 +00004644 if (!OutChains.empty())
Chris Lattnerbd564bf2006-08-08 02:23:42 +00004645 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
4646 &OutChains[0], OutChains.size());
Chris Lattnerce7518c2006-01-26 22:24:51 +00004647 DAG.setRoot(Chain);
4648}
4649
4650
Chris Lattner1c08c712005-01-07 07:47:53 +00004651void SelectionDAGLowering::visitMalloc(MallocInst &I) {
Dan Gohman475871a2008-07-27 21:46:04 +00004652 SDValue Src = getValue(I.getOperand(0));
Chris Lattner1c08c712005-01-07 07:47:53 +00004653
Duncan Sands83ec4b62008-06-06 12:08:01 +00004654 MVT IntPtr = TLI.getPointerTy();
Chris Lattner68cd65e2005-01-22 23:04:37 +00004655
Duncan Sands8e4eb092008-06-08 20:54:56 +00004656 if (IntPtr.bitsLT(Src.getValueType()))
Chris Lattner68cd65e2005-01-22 23:04:37 +00004657 Src = DAG.getNode(ISD::TRUNCATE, IntPtr, Src);
Duncan Sands8e4eb092008-06-08 20:54:56 +00004658 else if (IntPtr.bitsGT(Src.getValueType()))
Chris Lattner68cd65e2005-01-22 23:04:37 +00004659 Src = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, Src);
Chris Lattner1c08c712005-01-07 07:47:53 +00004660
4661 // Scale the source by the type size.
Duncan Sands514ab342007-11-01 20:53:16 +00004662 uint64_t ElementSize = TD->getABITypeSize(I.getType()->getElementType());
Chris Lattner1c08c712005-01-07 07:47:53 +00004663 Src = DAG.getNode(ISD::MUL, Src.getValueType(),
Chris Lattner0bd48932008-01-17 07:00:52 +00004664 Src, DAG.getIntPtrConstant(ElementSize));
Chris Lattner1c08c712005-01-07 07:47:53 +00004665
Reid Spencer47857812006-12-31 05:55:36 +00004666 TargetLowering::ArgListTy Args;
4667 TargetLowering::ArgListEntry Entry;
4668 Entry.Node = Src;
4669 Entry.Ty = TLI.getTargetData()->getIntPtrType();
Reid Spencer47857812006-12-31 05:55:36 +00004670 Args.push_back(Entry);
Chris Lattnercf5734d2005-01-08 19:26:18 +00004671
Dan Gohman475871a2008-07-27 21:46:04 +00004672 std::pair<SDValue,SDValue> Result =
Duncan Sands00fee652008-02-14 17:28:50 +00004673 TLI.LowerCallTo(getRoot(), I.getType(), false, false, false, CallingConv::C,
4674 true, DAG.getExternalSymbol("malloc", IntPtr), Args, DAG);
Chris Lattnercf5734d2005-01-08 19:26:18 +00004675 setValue(&I, Result.first); // Pointers always fit in registers
4676 DAG.setRoot(Result.second);
Chris Lattner1c08c712005-01-07 07:47:53 +00004677}
4678
4679void SelectionDAGLowering::visitFree(FreeInst &I) {
Reid Spencer47857812006-12-31 05:55:36 +00004680 TargetLowering::ArgListTy Args;
4681 TargetLowering::ArgListEntry Entry;
4682 Entry.Node = getValue(I.getOperand(0));
4683 Entry.Ty = TLI.getTargetData()->getIntPtrType();
Reid Spencer47857812006-12-31 05:55:36 +00004684 Args.push_back(Entry);
Duncan Sands83ec4b62008-06-06 12:08:01 +00004685 MVT IntPtr = TLI.getPointerTy();
Dan Gohman475871a2008-07-27 21:46:04 +00004686 std::pair<SDValue,SDValue> Result =
Duncan Sands00fee652008-02-14 17:28:50 +00004687 TLI.LowerCallTo(getRoot(), Type::VoidTy, false, false, false,
4688 CallingConv::C, true,
Chris Lattnercf5734d2005-01-08 19:26:18 +00004689 DAG.getExternalSymbol("free", IntPtr), Args, DAG);
4690 DAG.setRoot(Result.second);
Chris Lattner1c08c712005-01-07 07:47:53 +00004691}
4692
Evan Chengff9b3732008-01-30 18:18:23 +00004693// EmitInstrWithCustomInserter - This method should be implemented by targets
4694// that mark instructions with the 'usesCustomDAGSchedInserter' flag. These
Chris Lattner025c39b2005-08-26 20:54:47 +00004695// instructions are special in various ways, which require special support to
4696// insert. The specified MachineInstr is created but not inserted into any
4697// basic blocks, and the scheduler passes ownership of it to this method.
Evan Chengff9b3732008-01-30 18:18:23 +00004698MachineBasicBlock *TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
Chris Lattner025c39b2005-08-26 20:54:47 +00004699 MachineBasicBlock *MBB) {
Bill Wendling832171c2006-12-07 20:04:42 +00004700 cerr << "If a target marks an instruction with "
4701 << "'usesCustomDAGSchedInserter', it must implement "
Evan Chengff9b3732008-01-30 18:18:23 +00004702 << "TargetLowering::EmitInstrWithCustomInserter!\n";
Chris Lattner025c39b2005-08-26 20:54:47 +00004703 abort();
4704 return 0;
4705}
4706
Chris Lattner39ae3622005-01-09 00:00:49 +00004707void SelectionDAGLowering::visitVAStart(CallInst &I) {
Nate Begemanacc398c2006-01-25 18:21:52 +00004708 DAG.setRoot(DAG.getNode(ISD::VASTART, MVT::Other, getRoot(),
4709 getValue(I.getOperand(1)),
4710 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner39ae3622005-01-09 00:00:49 +00004711}
4712
4713void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
Dan Gohman475871a2008-07-27 21:46:04 +00004714 SDValue V = DAG.getVAArg(TLI.getValueType(I.getType()), getRoot(),
Nate Begemanacc398c2006-01-25 18:21:52 +00004715 getValue(I.getOperand(0)),
4716 DAG.getSrcValue(I.getOperand(0)));
4717 setValue(&I, V);
4718 DAG.setRoot(V.getValue(1));
Chris Lattner1c08c712005-01-07 07:47:53 +00004719}
4720
4721void SelectionDAGLowering::visitVAEnd(CallInst &I) {
Nate Begemanacc398c2006-01-25 18:21:52 +00004722 DAG.setRoot(DAG.getNode(ISD::VAEND, MVT::Other, getRoot(),
4723 getValue(I.getOperand(1)),
4724 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner1c08c712005-01-07 07:47:53 +00004725}
4726
4727void SelectionDAGLowering::visitVACopy(CallInst &I) {
Nate Begemanacc398c2006-01-25 18:21:52 +00004728 DAG.setRoot(DAG.getNode(ISD::VACOPY, MVT::Other, getRoot(),
4729 getValue(I.getOperand(1)),
4730 getValue(I.getOperand(2)),
4731 DAG.getSrcValue(I.getOperand(1)),
4732 DAG.getSrcValue(I.getOperand(2))));
Chris Lattner1c08c712005-01-07 07:47:53 +00004733}
4734
Chris Lattnerfdfded52006-04-12 16:20:43 +00004735/// TargetLowering::LowerArguments - This is the default LowerArguments
4736/// implementation, which just inserts a FORMAL_ARGUMENTS node. FIXME: When all
Chris Lattnerf4ec8172006-05-16 22:53:20 +00004737/// targets are migrated to using FORMAL_ARGUMENTS, this hook should be
4738/// integrated into SDISel.
Dan Gohmana44b6742008-06-30 20:31:15 +00004739void TargetLowering::LowerArguments(Function &F, SelectionDAG &DAG,
Dan Gohman475871a2008-07-27 21:46:04 +00004740 SmallVectorImpl<SDValue> &ArgValues) {
Chris Lattnerfdfded52006-04-12 16:20:43 +00004741 // Add CC# and isVararg as operands to the FORMAL_ARGUMENTS node.
Dan Gohman475871a2008-07-27 21:46:04 +00004742 SmallVector<SDValue, 3+16> Ops;
Chris Lattner8c0c10c2006-05-16 06:45:34 +00004743 Ops.push_back(DAG.getRoot());
Chris Lattnerfdfded52006-04-12 16:20:43 +00004744 Ops.push_back(DAG.getConstant(F.getCallingConv(), getPointerTy()));
4745 Ops.push_back(DAG.getConstant(F.isVarArg(), getPointerTy()));
4746
4747 // Add one result value for each formal argument.
Dan Gohmana44b6742008-06-30 20:31:15 +00004748 SmallVector<MVT, 16> RetVals;
Anton Korobeynikov6aa279d2007-01-28 18:01:49 +00004749 unsigned j = 1;
Anton Korobeynikovac2b2cf2007-01-28 16:04:40 +00004750 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end();
4751 I != E; ++I, ++j) {
Dan Gohmanf5025cf2008-06-09 21:19:23 +00004752 SmallVector<MVT, 4> ValueVTs;
4753 ComputeValueVTs(*this, I->getType(), ValueVTs);
4754 for (unsigned Value = 0, NumValues = ValueVTs.size();
4755 Value != NumValues; ++Value) {
4756 MVT VT = ValueVTs[Value];
4757 const Type *ArgTy = VT.getTypeForMVT();
4758 ISD::ArgFlagsTy Flags;
4759 unsigned OriginalAlignment =
4760 getTargetData()->getABITypeAlignment(ArgTy);
Lauro Ramos Venancio7aa47b62007-02-13 13:50:08 +00004761
Dan Gohmanf5025cf2008-06-09 21:19:23 +00004762 if (F.paramHasAttr(j, ParamAttr::ZExt))
4763 Flags.setZExt();
4764 if (F.paramHasAttr(j, ParamAttr::SExt))
4765 Flags.setSExt();
4766 if (F.paramHasAttr(j, ParamAttr::InReg))
4767 Flags.setInReg();
4768 if (F.paramHasAttr(j, ParamAttr::StructRet))
4769 Flags.setSRet();
4770 if (F.paramHasAttr(j, ParamAttr::ByVal)) {
4771 Flags.setByVal();
4772 const PointerType *Ty = cast<PointerType>(I->getType());
4773 const Type *ElementTy = Ty->getElementType();
4774 unsigned FrameAlign = getByValTypeAlignment(ElementTy);
4775 unsigned FrameSize = getTargetData()->getABITypeSize(ElementTy);
4776 // For ByVal, alignment should be passed from FE. BE will guess if
4777 // this info is not there but there are cases it cannot get right.
4778 if (F.getParamAlignment(j))
4779 FrameAlign = F.getParamAlignment(j);
4780 Flags.setByValAlign(FrameAlign);
4781 Flags.setByValSize(FrameSize);
4782 }
4783 if (F.paramHasAttr(j, ParamAttr::Nest))
4784 Flags.setNest();
4785 Flags.setOrigAlign(OriginalAlignment);
Duncan Sandsb988bac2008-02-11 20:58:28 +00004786
Dan Gohmanf5025cf2008-06-09 21:19:23 +00004787 MVT RegisterVT = getRegisterType(VT);
4788 unsigned NumRegs = getNumRegisters(VT);
4789 for (unsigned i = 0; i != NumRegs; ++i) {
4790 RetVals.push_back(RegisterVT);
4791 ISD::ArgFlagsTy MyFlags = Flags;
4792 if (NumRegs > 1 && i == 0)
4793 MyFlags.setSplit();
4794 // if it isn't first piece, alignment must be 1
4795 else if (i > 0)
4796 MyFlags.setOrigAlign(1);
4797 Ops.push_back(DAG.getArgFlags(MyFlags));
4798 }
Dan Gohmanb6f5b002007-06-28 23:29:44 +00004799 }
Chris Lattnerfdfded52006-04-12 16:20:43 +00004800 }
Evan Cheng3b0d2862006-04-25 23:03:35 +00004801
Chris Lattner8c0c10c2006-05-16 06:45:34 +00004802 RetVals.push_back(MVT::Other);
Chris Lattnerfdfded52006-04-12 16:20:43 +00004803
4804 // Create the node.
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00004805 SDNode *Result = DAG.getNode(ISD::FORMAL_ARGUMENTS,
Chris Lattner86ca3ca2008-02-13 07:39:09 +00004806 DAG.getVTList(&RetVals[0], RetVals.size()),
Chris Lattnerbd564bf2006-08-08 02:23:42 +00004807 &Ops[0], Ops.size()).Val;
Chris Lattner86ca3ca2008-02-13 07:39:09 +00004808
4809 // Prelower FORMAL_ARGUMENTS. This isn't required for functionality, but
4810 // allows exposing the loads that may be part of the argument access to the
4811 // first DAGCombiner pass.
Dan Gohman475871a2008-07-27 21:46:04 +00004812 SDValue TmpRes = LowerOperation(SDValue(Result, 0), DAG);
Chris Lattner86ca3ca2008-02-13 07:39:09 +00004813
4814 // The number of results should match up, except that the lowered one may have
4815 // an extra flag result.
4816 assert((Result->getNumValues() == TmpRes.Val->getNumValues() ||
4817 (Result->getNumValues()+1 == TmpRes.Val->getNumValues() &&
4818 TmpRes.getValue(Result->getNumValues()).getValueType() == MVT::Flag))
4819 && "Lowering produced unexpected number of results!");
Dan Gohman2dbc1672008-07-21 21:04:07 +00004820
4821 // The FORMAL_ARGUMENTS node itself is likely no longer needed.
4822 if (Result != TmpRes.Val && Result->use_empty()) {
4823 HandleSDNode Dummy(DAG.getRoot());
4824 DAG.RemoveDeadNode(Result);
4825 }
4826
Chris Lattner86ca3ca2008-02-13 07:39:09 +00004827 Result = TmpRes.Val;
4828
Dan Gohman27a70be2007-07-02 16:18:06 +00004829 unsigned NumArgRegs = Result->getNumValues() - 1;
Dan Gohman475871a2008-07-27 21:46:04 +00004830 DAG.setRoot(SDValue(Result, NumArgRegs));
Chris Lattnerfdfded52006-04-12 16:20:43 +00004831
4832 // Set up the return result vector.
Chris Lattnerfdfded52006-04-12 16:20:43 +00004833 unsigned i = 0;
Reid Spencer47857812006-12-31 05:55:36 +00004834 unsigned Idx = 1;
4835 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E;
4836 ++I, ++Idx) {
Dan Gohmanf5025cf2008-06-09 21:19:23 +00004837 SmallVector<MVT, 4> ValueVTs;
4838 ComputeValueVTs(*this, I->getType(), ValueVTs);
4839 for (unsigned Value = 0, NumValues = ValueVTs.size();
4840 Value != NumValues; ++Value) {
4841 MVT VT = ValueVTs[Value];
4842 MVT PartVT = getRegisterType(VT);
Duncan Sandsb988bac2008-02-11 20:58:28 +00004843
Dan Gohmanf5025cf2008-06-09 21:19:23 +00004844 unsigned NumParts = getNumRegisters(VT);
Dan Gohman475871a2008-07-27 21:46:04 +00004845 SmallVector<SDValue, 4> Parts(NumParts);
Dan Gohmanf5025cf2008-06-09 21:19:23 +00004846 for (unsigned j = 0; j != NumParts; ++j)
Dan Gohman475871a2008-07-27 21:46:04 +00004847 Parts[j] = SDValue(Result, i++);
Duncan Sandsb988bac2008-02-11 20:58:28 +00004848
Dan Gohmanf5025cf2008-06-09 21:19:23 +00004849 ISD::NodeType AssertOp = ISD::DELETED_NODE;
4850 if (F.paramHasAttr(Idx, ParamAttr::SExt))
4851 AssertOp = ISD::AssertSext;
4852 else if (F.paramHasAttr(Idx, ParamAttr::ZExt))
4853 AssertOp = ISD::AssertZext;
Duncan Sandsb988bac2008-02-11 20:58:28 +00004854
Dan Gohmana44b6742008-06-30 20:31:15 +00004855 ArgValues.push_back(getCopyFromParts(DAG, &Parts[0], NumParts, PartVT, VT,
4856 AssertOp));
Dan Gohmanf5025cf2008-06-09 21:19:23 +00004857 }
Chris Lattnerfdfded52006-04-12 16:20:43 +00004858 }
Dan Gohman27a70be2007-07-02 16:18:06 +00004859 assert(i == NumArgRegs && "Argument register count mismatch!");
Chris Lattnerfdfded52006-04-12 16:20:43 +00004860}
4861
Chris Lattnerf4ec8172006-05-16 22:53:20 +00004862
4863/// TargetLowering::LowerCallTo - This is the default LowerCallTo
4864/// implementation, which just inserts an ISD::CALL node, which is later custom
4865/// lowered by the target to something concrete. FIXME: When all targets are
4866/// migrated to using ISD::CALL, this hook should be integrated into SDISel.
Dan Gohman475871a2008-07-27 21:46:04 +00004867std::pair<SDValue, SDValue>
4868TargetLowering::LowerCallTo(SDValue Chain, const Type *RetTy,
Duncan Sands00fee652008-02-14 17:28:50 +00004869 bool RetSExt, bool RetZExt, bool isVarArg,
4870 unsigned CallingConv, bool isTailCall,
Dan Gohman475871a2008-07-27 21:46:04 +00004871 SDValue Callee,
Chris Lattnerf4ec8172006-05-16 22:53:20 +00004872 ArgListTy &Args, SelectionDAG &DAG) {
Dan Gohman475871a2008-07-27 21:46:04 +00004873 SmallVector<SDValue, 32> Ops;
Chris Lattnerf4ec8172006-05-16 22:53:20 +00004874 Ops.push_back(Chain); // Op#0 - Chain
4875 Ops.push_back(DAG.getConstant(CallingConv, getPointerTy())); // Op#1 - CC
4876 Ops.push_back(DAG.getConstant(isVarArg, getPointerTy())); // Op#2 - VarArg
4877 Ops.push_back(DAG.getConstant(isTailCall, getPointerTy())); // Op#3 - Tail
4878 Ops.push_back(Callee);
4879
4880 // Handle all of the outgoing arguments.
4881 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
Dan Gohmanf5025cf2008-06-09 21:19:23 +00004882 SmallVector<MVT, 4> ValueVTs;
4883 ComputeValueVTs(*this, Args[i].Ty, ValueVTs);
4884 for (unsigned Value = 0, NumValues = ValueVTs.size();
4885 Value != NumValues; ++Value) {
4886 MVT VT = ValueVTs[Value];
4887 const Type *ArgTy = VT.getTypeForMVT();
Gabor Greif99a6cb92008-08-26 22:36:50 +00004888 SDValue Op = SDValue(Args[i].Node.Val, Args[i].Node.getResNo() + Value);
Dan Gohmanf5025cf2008-06-09 21:19:23 +00004889 ISD::ArgFlagsTy Flags;
4890 unsigned OriginalAlignment =
4891 getTargetData()->getABITypeAlignment(ArgTy);
Duncan Sands276dcbd2008-03-21 09:14:45 +00004892
Dan Gohmanf5025cf2008-06-09 21:19:23 +00004893 if (Args[i].isZExt)
4894 Flags.setZExt();
4895 if (Args[i].isSExt)
4896 Flags.setSExt();
4897 if (Args[i].isInReg)
4898 Flags.setInReg();
4899 if (Args[i].isSRet)
4900 Flags.setSRet();
4901 if (Args[i].isByVal) {
4902 Flags.setByVal();
4903 const PointerType *Ty = cast<PointerType>(Args[i].Ty);
4904 const Type *ElementTy = Ty->getElementType();
4905 unsigned FrameAlign = getByValTypeAlignment(ElementTy);
4906 unsigned FrameSize = getTargetData()->getABITypeSize(ElementTy);
4907 // For ByVal, alignment should come from FE. BE will guess if this
4908 // info is not there but there are cases it cannot get right.
4909 if (Args[i].Alignment)
4910 FrameAlign = Args[i].Alignment;
4911 Flags.setByValAlign(FrameAlign);
4912 Flags.setByValSize(FrameSize);
4913 }
4914 if (Args[i].isNest)
4915 Flags.setNest();
4916 Flags.setOrigAlign(OriginalAlignment);
Dan Gohman27a70be2007-07-02 16:18:06 +00004917
Dan Gohmanf5025cf2008-06-09 21:19:23 +00004918 MVT PartVT = getRegisterType(VT);
4919 unsigned NumParts = getNumRegisters(VT);
Dan Gohman475871a2008-07-27 21:46:04 +00004920 SmallVector<SDValue, 4> Parts(NumParts);
Dan Gohmanf5025cf2008-06-09 21:19:23 +00004921 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
Duncan Sandsb988bac2008-02-11 20:58:28 +00004922
Dan Gohmanf5025cf2008-06-09 21:19:23 +00004923 if (Args[i].isSExt)
4924 ExtendKind = ISD::SIGN_EXTEND;
4925 else if (Args[i].isZExt)
4926 ExtendKind = ISD::ZERO_EXTEND;
Duncan Sandsb988bac2008-02-11 20:58:28 +00004927
Dan Gohmanf5025cf2008-06-09 21:19:23 +00004928 getCopyToParts(DAG, Op, &Parts[0], NumParts, PartVT, ExtendKind);
Duncan Sandsb988bac2008-02-11 20:58:28 +00004929
Dan Gohmanf5025cf2008-06-09 21:19:23 +00004930 for (unsigned i = 0; i != NumParts; ++i) {
4931 // if it isn't first piece, alignment must be 1
4932 ISD::ArgFlagsTy MyFlags = Flags;
4933 if (NumParts > 1 && i == 0)
4934 MyFlags.setSplit();
4935 else if (i != 0)
4936 MyFlags.setOrigAlign(1);
Duncan Sandsb988bac2008-02-11 20:58:28 +00004937
Dan Gohmanf5025cf2008-06-09 21:19:23 +00004938 Ops.push_back(Parts[i]);
4939 Ops.push_back(DAG.getArgFlags(MyFlags));
4940 }
Dan Gohman27a70be2007-07-02 16:18:06 +00004941 }
Chris Lattnerf4ec8172006-05-16 22:53:20 +00004942 }
4943
Dan Gohmanef5d1942008-03-11 21:11:25 +00004944 // Figure out the result value types. We start by making a list of
Dan Gohman23ce5022008-04-25 18:27:55 +00004945 // the potentially illegal return value types.
Duncan Sands83ec4b62008-06-06 12:08:01 +00004946 SmallVector<MVT, 4> LoweredRetTys;
4947 SmallVector<MVT, 4> RetTys;
Dan Gohman23ce5022008-04-25 18:27:55 +00004948 ComputeValueVTs(*this, RetTy, RetTys);
Dan Gohmanef5d1942008-03-11 21:11:25 +00004949
Dan Gohman23ce5022008-04-25 18:27:55 +00004950 // Then we translate that to a list of legal types.
4951 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
Duncan Sands83ec4b62008-06-06 12:08:01 +00004952 MVT VT = RetTys[I];
4953 MVT RegisterVT = getRegisterType(VT);
Dan Gohmanef5d1942008-03-11 21:11:25 +00004954 unsigned NumRegs = getNumRegisters(VT);
4955 for (unsigned i = 0; i != NumRegs; ++i)
4956 LoweredRetTys.push_back(RegisterVT);
4957 }
Chris Lattnerf4ec8172006-05-16 22:53:20 +00004958
Dan Gohmanef5d1942008-03-11 21:11:25 +00004959 LoweredRetTys.push_back(MVT::Other); // Always has a chain.
Chris Lattnerf4ec8172006-05-16 22:53:20 +00004960
Dan Gohmanb6f5b002007-06-28 23:29:44 +00004961 // Create the CALL node.
Dan Gohman475871a2008-07-27 21:46:04 +00004962 SDValue Res = DAG.getNode(ISD::CALL,
Dan Gohmanef5d1942008-03-11 21:11:25 +00004963 DAG.getVTList(&LoweredRetTys[0],
4964 LoweredRetTys.size()),
Chris Lattnerbe384162006-08-16 22:57:46 +00004965 &Ops[0], Ops.size());
Dan Gohmanef5d1942008-03-11 21:11:25 +00004966 Chain = Res.getValue(LoweredRetTys.size() - 1);
Dan Gohmanb6f5b002007-06-28 23:29:44 +00004967
4968 // Gather up the call result into a single value.
4969 if (RetTy != Type::VoidTy) {
Duncan Sands00fee652008-02-14 17:28:50 +00004970 ISD::NodeType AssertOp = ISD::DELETED_NODE;
4971
4972 if (RetSExt)
4973 AssertOp = ISD::AssertSext;
4974 else if (RetZExt)
Dan Gohmanb6f5b002007-06-28 23:29:44 +00004975 AssertOp = ISD::AssertZext;
Duncan Sands00fee652008-02-14 17:28:50 +00004976
Dan Gohman475871a2008-07-27 21:46:04 +00004977 SmallVector<SDValue, 4> ReturnValues;
Dan Gohmanef5d1942008-03-11 21:11:25 +00004978 unsigned RegNo = 0;
Dan Gohman23ce5022008-04-25 18:27:55 +00004979 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
Duncan Sands83ec4b62008-06-06 12:08:01 +00004980 MVT VT = RetTys[I];
4981 MVT RegisterVT = getRegisterType(VT);
Dan Gohmanef5d1942008-03-11 21:11:25 +00004982 unsigned NumRegs = getNumRegisters(VT);
4983 unsigned RegNoEnd = NumRegs + RegNo;
Dan Gohman475871a2008-07-27 21:46:04 +00004984 SmallVector<SDValue, 4> Results;
Dan Gohmanef5d1942008-03-11 21:11:25 +00004985 for (; RegNo != RegNoEnd; ++RegNo)
4986 Results.push_back(Res.getValue(RegNo));
Dan Gohman475871a2008-07-27 21:46:04 +00004987 SDValue ReturnValue =
Dan Gohmanef5d1942008-03-11 21:11:25 +00004988 getCopyFromParts(DAG, &Results[0], NumRegs, RegisterVT, VT,
4989 AssertOp);
4990 ReturnValues.push_back(ReturnValue);
4991 }
Duncan Sandsf9516202008-06-30 10:19:09 +00004992 Res = DAG.getMergeValues(DAG.getVTList(&RetTys[0], RetTys.size()),
4993 &ReturnValues[0], ReturnValues.size());
Chris Lattnerf4ec8172006-05-16 22:53:20 +00004994 }
Dan Gohmanb6f5b002007-06-28 23:29:44 +00004995
4996 return std::make_pair(Res, Chain);
Chris Lattnerf4ec8172006-05-16 22:53:20 +00004997}
4998
Dan Gohman475871a2008-07-27 21:46:04 +00004999SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) {
Chris Lattner171453a2005-01-16 07:28:41 +00005000 assert(0 && "LowerOperation not implemented for this target!");
5001 abort();
Dan Gohman475871a2008-07-27 21:46:04 +00005002 return SDValue();
Chris Lattner171453a2005-01-16 07:28:41 +00005003}
5004
Nate Begeman0aed7842006-01-28 03:14:31 +00005005
Chris Lattner7041ee32005-01-11 05:56:49 +00005006//===----------------------------------------------------------------------===//
5007// SelectionDAGISel code
5008//===----------------------------------------------------------------------===//
Chris Lattner1c08c712005-01-07 07:47:53 +00005009
Dan Gohman7c3234c2008-08-27 23:52:12 +00005010SelectionDAGISel::SelectionDAGISel(TargetLowering &tli, bool fast) :
5011 FunctionPass((intptr_t)&ID), TLI(tli),
5012 FuncInfo(new FunctionLoweringInfo(TLI)),
5013 CurDAG(new SelectionDAG(TLI, *FuncInfo)),
5014 SDL(new SelectionDAGLowering(*CurDAG, TLI, *FuncInfo)),
5015 GFI(),
5016 Fast(fast),
5017 DAGSize(0)
5018{}
5019
5020SelectionDAGISel::~SelectionDAGISel() {
5021 delete SDL;
5022 delete CurDAG;
5023 delete FuncInfo;
5024}
5025
Duncan Sands83ec4b62008-06-06 12:08:01 +00005026unsigned SelectionDAGISel::MakeReg(MVT VT) {
Chris Lattner84bc5422007-12-31 04:13:23 +00005027 return RegInfo->createVirtualRegister(TLI.getRegClassFor(VT));
Chris Lattner1c08c712005-01-07 07:47:53 +00005028}
5029
Chris Lattner495a0b52005-08-17 06:37:43 +00005030void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const {
Jim Laskeyc7c3f112006-10-16 20:52:31 +00005031 AU.addRequired<AliasAnalysis>();
Gordon Henriksen5eca0752008-08-17 18:44:35 +00005032 AU.addRequired<GCModuleInfo>();
Chris Lattnerc8d288f2007-03-31 04:18:03 +00005033 AU.setPreservesAll();
Chris Lattner495a0b52005-08-17 06:37:43 +00005034}
Chris Lattner1c08c712005-01-07 07:47:53 +00005035
Chris Lattner1c08c712005-01-07 07:47:53 +00005036bool SelectionDAGISel::runOnFunction(Function &Fn) {
Dan Gohman5f43f922007-08-27 16:26:13 +00005037 // Get alias analysis for load/store combining.
5038 AA = &getAnalysis<AliasAnalysis>();
5039
Chris Lattner1c08c712005-01-07 07:47:53 +00005040 MachineFunction &MF = MachineFunction::construct(&Fn, TLI.getTargetMachine());
Gordon Henriksen5eca0752008-08-17 18:44:35 +00005041 if (MF.getFunction()->hasGC())
5042 GFI = &getAnalysis<GCModuleInfo>().getFunctionInfo(*MF.getFunction());
Gordon Henriksence224772008-01-07 01:30:38 +00005043 else
Gordon Henriksen5eca0752008-08-17 18:44:35 +00005044 GFI = 0;
Chris Lattner84bc5422007-12-31 04:13:23 +00005045 RegInfo = &MF.getRegInfo();
Bill Wendling832171c2006-12-07 20:04:42 +00005046 DOUT << "\n\n\n=== " << Fn.getName() << "\n";
Chris Lattner1c08c712005-01-07 07:47:53 +00005047
Dan Gohman7c3234c2008-08-27 23:52:12 +00005048 FuncInfo->set(Fn, MF);
5049 CurDAG->init(MF, getAnalysisToUpdate<MachineModuleInfo>());
5050 SDL->init(GFI, *AA);
Chris Lattner1c08c712005-01-07 07:47:53 +00005051
Dale Johannesen1532f3d2008-04-02 00:25:04 +00005052 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
5053 if (InvokeInst *Invoke = dyn_cast<InvokeInst>(I->getTerminator()))
5054 // Mark landing pad.
Dan Gohman7c3234c2008-08-27 23:52:12 +00005055 FuncInfo->MBBMap[Invoke->getSuccessor(1)]->setIsLandingPad();
Duncan Sands9fac0b52007-06-06 10:05:18 +00005056
Dan Gohman7c3234c2008-08-27 23:52:12 +00005057 SelectAllBasicBlocks(Fn, MF);
Misha Brukmanedf128a2005-04-21 22:36:52 +00005058
Evan Chengad2070c2007-02-10 02:43:39 +00005059 // Add function live-ins to entry block live-in set.
5060 BasicBlock *EntryBB = &Fn.getEntryBlock();
Dan Gohman7c3234c2008-08-27 23:52:12 +00005061 BB = FuncInfo->MBBMap[EntryBB];
Chris Lattner84bc5422007-12-31 04:13:23 +00005062 if (!RegInfo->livein_empty())
5063 for (MachineRegisterInfo::livein_iterator I = RegInfo->livein_begin(),
5064 E = RegInfo->livein_end(); I != E; ++I)
Evan Chengad2070c2007-02-10 02:43:39 +00005065 BB->addLiveIn(I->first);
5066
Duncan Sandsf4070822007-06-15 19:04:19 +00005067#ifndef NDEBUG
Dan Gohman7c3234c2008-08-27 23:52:12 +00005068 assert(FuncInfo->CatchInfoFound.size() == FuncInfo->CatchInfoLost.size() &&
Duncan Sandsf4070822007-06-15 19:04:19 +00005069 "Not all catch info was assigned to a landing pad!");
5070#endif
5071
Dan Gohman7c3234c2008-08-27 23:52:12 +00005072 FuncInfo->clear();
5073
Chris Lattner1c08c712005-01-07 07:47:53 +00005074 return true;
5075}
5076
Chris Lattner6833b062008-04-28 07:16:35 +00005077void SelectionDAGLowering::CopyValueToVirtualRegister(Value *V, unsigned Reg) {
Dan Gohman475871a2008-07-27 21:46:04 +00005078 SDValue Op = getValue(V);
Chris Lattner18c2f132005-01-13 20:50:02 +00005079 assert((Op.getOpcode() != ISD::CopyFromReg ||
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00005080 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
Chris Lattner18c2f132005-01-13 20:50:02 +00005081 "Copy from a reg to the same reg!");
Dan Gohman86e1ebf2008-03-27 19:56:19 +00005082 assert(!TargetRegisterInfo::isPhysicalRegister(Reg) && "Is a physreg");
Dan Gohmanb6f5b002007-06-28 23:29:44 +00005083
Dan Gohman23ce5022008-04-25 18:27:55 +00005084 RegsForValue RFV(TLI, Reg, V->getType());
Dan Gohman475871a2008-07-27 21:46:04 +00005085 SDValue Chain = DAG.getEntryNode();
Dan Gohman23ce5022008-04-25 18:27:55 +00005086 RFV.getCopyToRegs(Op, DAG, Chain, 0);
5087 PendingExports.push_back(Chain);
Chris Lattner1c08c712005-01-07 07:47:53 +00005088}
5089
Chris Lattner068a81e2005-01-17 17:15:02 +00005090void SelectionDAGISel::
Dan Gohman7c3234c2008-08-27 23:52:12 +00005091LowerArguments(BasicBlock *LLVMBB) {
Chris Lattner068a81e2005-01-17 17:15:02 +00005092 // If this is the entry block, emit arguments.
Evan Cheng15699fc2007-02-10 01:08:18 +00005093 Function &F = *LLVMBB->getParent();
Dan Gohman7c3234c2008-08-27 23:52:12 +00005094 SDValue OldRoot = SDL->DAG.getRoot();
Dan Gohman475871a2008-07-27 21:46:04 +00005095 SmallVector<SDValue, 16> Args;
Dan Gohman7c3234c2008-08-27 23:52:12 +00005096 TLI.LowerArguments(F, SDL->DAG, Args);
Chris Lattner068a81e2005-01-17 17:15:02 +00005097
Chris Lattnerbf209482005-10-30 19:42:35 +00005098 unsigned a = 0;
5099 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
Dan Gohmanf5025cf2008-06-09 21:19:23 +00005100 AI != E; ++AI) {
5101 SmallVector<MVT, 4> ValueVTs;
5102 ComputeValueVTs(TLI, AI->getType(), ValueVTs);
5103 unsigned NumValues = ValueVTs.size();
Chris Lattnerbf209482005-10-30 19:42:35 +00005104 if (!AI->use_empty()) {
Dan Gohman7c3234c2008-08-27 23:52:12 +00005105 SDL->setValue(AI, SDL->DAG.getMergeValues(&Args[a], NumValues));
Chris Lattnerbf209482005-10-30 19:42:35 +00005106 // If this argument is live outside of the entry block, insert a copy from
5107 // whereever we got it to the vreg that other BB's will reference it as.
Dan Gohman7c3234c2008-08-27 23:52:12 +00005108 DenseMap<const Value*, unsigned>::iterator VMI=FuncInfo->ValueMap.find(AI);
5109 if (VMI != FuncInfo->ValueMap.end()) {
5110 SDL->CopyValueToVirtualRegister(AI, VMI->second);
Chris Lattnerbf209482005-10-30 19:42:35 +00005111 }
Chris Lattner0afa8e32005-01-17 17:55:19 +00005112 }
Dan Gohmanf5025cf2008-06-09 21:19:23 +00005113 a += NumValues;
5114 }
Chris Lattnerbf209482005-10-30 19:42:35 +00005115
Chris Lattnerbf209482005-10-30 19:42:35 +00005116 // Finally, if the target has anything special to do, allow it to do so.
Chris Lattner96645412006-05-16 06:10:58 +00005117 // FIXME: this should insert code into the DAG!
Dan Gohman7c3234c2008-08-27 23:52:12 +00005118 EmitFunctionEntryCode(F, SDL->DAG.getMachineFunction());
Chris Lattner068a81e2005-01-17 17:15:02 +00005119}
5120
Duncan Sandsf4070822007-06-15 19:04:19 +00005121static void copyCatchInfo(BasicBlock *SrcBB, BasicBlock *DestBB,
5122 MachineModuleInfo *MMI, FunctionLoweringInfo &FLI) {
Duncan Sandsf4070822007-06-15 19:04:19 +00005123 for (BasicBlock::iterator I = SrcBB->begin(), E = --SrcBB->end(); I != E; ++I)
Duncan Sandscf26d7c2007-07-04 20:52:51 +00005124 if (isSelector(I)) {
Duncan Sandsf4070822007-06-15 19:04:19 +00005125 // Apply the catch info to DestBB.
5126 addCatchInfo(cast<CallInst>(*I), MMI, FLI.MBBMap[DestBB]);
5127#ifndef NDEBUG
Duncan Sands560a7372007-11-15 09:54:37 +00005128 if (!FLI.MBBMap[SrcBB]->isLandingPad())
5129 FLI.CatchInfoFound.insert(I);
Duncan Sandsf4070822007-06-15 19:04:19 +00005130#endif
5131 }
5132}
5133
Arnold Schwaighofer30e62c02008-04-30 09:16:33 +00005134/// IsFixedFrameObjectWithPosOffset - Check if object is a fixed frame object and
5135/// whether object offset >= 0.
5136static bool
Dan Gohman475871a2008-07-27 21:46:04 +00005137IsFixedFrameObjectWithPosOffset(MachineFrameInfo * MFI, SDValue Op) {
Arnold Schwaighofer30e62c02008-04-30 09:16:33 +00005138 if (!isa<FrameIndexSDNode>(Op)) return false;
5139
5140 FrameIndexSDNode * FrameIdxNode = dyn_cast<FrameIndexSDNode>(Op);
5141 int FrameIdx = FrameIdxNode->getIndex();
5142 return MFI->isFixedObjectIndex(FrameIdx) &&
5143 MFI->getObjectOffset(FrameIdx) >= 0;
5144}
5145
5146/// IsPossiblyOverwrittenArgumentOfTailCall - Check if the operand could
5147/// possibly be overwritten when lowering the outgoing arguments in a tail
5148/// call. Currently the implementation of this call is very conservative and
5149/// assumes all arguments sourcing from FORMAL_ARGUMENTS or a CopyFromReg with
5150/// virtual registers would be overwritten by direct lowering.
Dan Gohman475871a2008-07-27 21:46:04 +00005151static bool IsPossiblyOverwrittenArgumentOfTailCall(SDValue Op,
Arnold Schwaighofer30e62c02008-04-30 09:16:33 +00005152 MachineFrameInfo * MFI) {
5153 RegisterSDNode * OpReg = NULL;
5154 if (Op.getOpcode() == ISD::FORMAL_ARGUMENTS ||
5155 (Op.getOpcode()== ISD::CopyFromReg &&
5156 (OpReg = dyn_cast<RegisterSDNode>(Op.getOperand(1))) &&
5157 (OpReg->getReg() >= TargetRegisterInfo::FirstVirtualRegister)) ||
5158 (Op.getOpcode() == ISD::LOAD &&
5159 IsFixedFrameObjectWithPosOffset(MFI, Op.getOperand(1))) ||
5160 (Op.getOpcode() == ISD::MERGE_VALUES &&
Gabor Greif99a6cb92008-08-26 22:36:50 +00005161 Op.getOperand(Op.getResNo()).getOpcode() == ISD::LOAD &&
5162 IsFixedFrameObjectWithPosOffset(MFI, Op.getOperand(Op.getResNo()).
Arnold Schwaighofer30e62c02008-04-30 09:16:33 +00005163 getOperand(1))))
5164 return true;
5165 return false;
5166}
5167
Arnold Schwaighoferc85e1712007-10-11 19:40:01 +00005168/// CheckDAGForTailCallsAndFixThem - This Function looks for CALL nodes in the
Arnold Schwaighofer48abc5c2007-10-12 21:30:57 +00005169/// DAG and fixes their tailcall attribute operand.
Arnold Schwaighoferc85e1712007-10-11 19:40:01 +00005170static void CheckDAGForTailCallsAndFixThem(SelectionDAG &DAG,
5171 TargetLowering& TLI) {
5172 SDNode * Ret = NULL;
Dan Gohman475871a2008-07-27 21:46:04 +00005173 SDValue Terminator = DAG.getRoot();
Arnold Schwaighoferc85e1712007-10-11 19:40:01 +00005174
5175 // Find RET node.
5176 if (Terminator.getOpcode() == ISD::RET) {
5177 Ret = Terminator.Val;
5178 }
5179
5180 // Fix tail call attribute of CALL nodes.
5181 for (SelectionDAG::allnodes_iterator BE = DAG.allnodes_begin(),
Dan Gohman0e5f1302008-07-07 23:02:41 +00005182 BI = DAG.allnodes_end(); BI != BE; ) {
5183 --BI;
Arnold Schwaighoferc85e1712007-10-11 19:40:01 +00005184 if (BI->getOpcode() == ISD::CALL) {
Dan Gohman475871a2008-07-27 21:46:04 +00005185 SDValue OpRet(Ret, 0);
5186 SDValue OpCall(BI, 0);
Arnold Schwaighoferc85e1712007-10-11 19:40:01 +00005187 bool isMarkedTailCall =
5188 cast<ConstantSDNode>(OpCall.getOperand(3))->getValue() != 0;
5189 // If CALL node has tail call attribute set to true and the call is not
5190 // eligible (no RET or the target rejects) the attribute is fixed to
Arnold Schwaighofer48abc5c2007-10-12 21:30:57 +00005191 // false. The TargetLowering::IsEligibleForTailCallOptimization function
Arnold Schwaighoferc85e1712007-10-11 19:40:01 +00005192 // must correctly identify tail call optimizable calls.
Arnold Schwaighofer30e62c02008-04-30 09:16:33 +00005193 if (!isMarkedTailCall) continue;
5194 if (Ret==NULL ||
5195 !TLI.IsEligibleForTailCallOptimization(OpCall, OpRet, DAG)) {
5196 // Not eligible. Mark CALL node as non tail call.
Dan Gohman475871a2008-07-27 21:46:04 +00005197 SmallVector<SDValue, 32> Ops;
Arnold Schwaighoferc85e1712007-10-11 19:40:01 +00005198 unsigned idx=0;
Arnold Schwaighofer30e62c02008-04-30 09:16:33 +00005199 for(SDNode::op_iterator I =OpCall.Val->op_begin(),
5200 E = OpCall.Val->op_end(); I != E; I++, idx++) {
Arnold Schwaighoferc85e1712007-10-11 19:40:01 +00005201 if (idx!=3)
5202 Ops.push_back(*I);
Arnold Schwaighofer30e62c02008-04-30 09:16:33 +00005203 else
Arnold Schwaighoferc85e1712007-10-11 19:40:01 +00005204 Ops.push_back(DAG.getConstant(false, TLI.getPointerTy()));
5205 }
5206 DAG.UpdateNodeOperands(OpCall, Ops.begin(), Ops.size());
Arnold Schwaighofer30e62c02008-04-30 09:16:33 +00005207 } else {
5208 // Look for tail call clobbered arguments. Emit a series of
5209 // copyto/copyfrom virtual register nodes to protect them.
Dan Gohman475871a2008-07-27 21:46:04 +00005210 SmallVector<SDValue, 32> Ops;
5211 SDValue Chain = OpCall.getOperand(0), InFlag;
Arnold Schwaighofer30e62c02008-04-30 09:16:33 +00005212 unsigned idx=0;
5213 for(SDNode::op_iterator I = OpCall.Val->op_begin(),
5214 E = OpCall.Val->op_end(); I != E; I++, idx++) {
Dan Gohman475871a2008-07-27 21:46:04 +00005215 SDValue Arg = *I;
Arnold Schwaighofer30e62c02008-04-30 09:16:33 +00005216 if (idx > 4 && (idx % 2)) {
5217 bool isByVal = cast<ARG_FLAGSSDNode>(OpCall.getOperand(idx+1))->
5218 getArgFlags().isByVal();
5219 MachineFunction &MF = DAG.getMachineFunction();
5220 MachineFrameInfo *MFI = MF.getFrameInfo();
5221 if (!isByVal &&
5222 IsPossiblyOverwrittenArgumentOfTailCall(Arg, MFI)) {
Duncan Sands83ec4b62008-06-06 12:08:01 +00005223 MVT VT = Arg.getValueType();
Arnold Schwaighofer30e62c02008-04-30 09:16:33 +00005224 unsigned VReg = MF.getRegInfo().
5225 createVirtualRegister(TLI.getRegClassFor(VT));
5226 Chain = DAG.getCopyToReg(Chain, VReg, Arg, InFlag);
5227 InFlag = Chain.getValue(1);
5228 Arg = DAG.getCopyFromReg(Chain, VReg, VT, InFlag);
5229 Chain = Arg.getValue(1);
5230 InFlag = Arg.getValue(2);
5231 }
5232 }
5233 Ops.push_back(Arg);
5234 }
5235 // Link in chain of CopyTo/CopyFromReg.
5236 Ops[0] = Chain;
5237 DAG.UpdateNodeOperands(OpCall, Ops.begin(), Ops.size());
Arnold Schwaighoferc85e1712007-10-11 19:40:01 +00005238 }
5239 }
5240 }
5241}
5242
Dan Gohmanf350b272008-08-23 02:25:05 +00005243/// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
5244/// ensure constants are generated when needed. Remember the virtual registers
5245/// that need to be added to the Machine PHI nodes as input. We cannot just
5246/// directly add them, because expansion might result in multiple MBB's for one
5247/// BB. As such, the start of the BB might correspond to a different MBB than
5248/// the end.
5249///
5250void
Dan Gohman7c3234c2008-08-27 23:52:12 +00005251SelectionDAGISel::HandlePHINodesInSuccessorBlocks(BasicBlock *LLVMBB) {
Chris Lattner8c494ab2006-10-27 23:50:33 +00005252 TerminatorInst *TI = LLVMBB->getTerminator();
Chris Lattner1c08c712005-01-07 07:47:53 +00005253
Dan Gohman7c3234c2008-08-27 23:52:12 +00005254 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
5255
Dan Gohman532dc2e2007-07-09 20:59:04 +00005256 // Check successor nodes' PHI nodes that expect a constant to be available
5257 // from this block.
Chris Lattner1c08c712005-01-07 07:47:53 +00005258 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
5259 BasicBlock *SuccBB = TI->getSuccessor(succ);
Chris Lattnerd5e93c02006-09-07 01:59:34 +00005260 if (!isa<PHINode>(SuccBB->begin())) continue;
Dan Gohman7c3234c2008-08-27 23:52:12 +00005261 MachineBasicBlock *SuccMBB = FuncInfo->MBBMap[SuccBB];
Chris Lattnerd5e93c02006-09-07 01:59:34 +00005262
Chris Lattner8c494ab2006-10-27 23:50:33 +00005263 // If this terminator has multiple identical successors (common for
5264 // switches), only handle each succ once.
Dan Gohman7c3234c2008-08-27 23:52:12 +00005265 if (!SuccsHandled.insert(SuccMBB)) continue;
Chris Lattner8c494ab2006-10-27 23:50:33 +00005266
5267 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
Chris Lattner1c08c712005-01-07 07:47:53 +00005268 PHINode *PN;
5269
5270 // At this point we know that there is a 1-1 correspondence between LLVM PHI
5271 // nodes and Machine PHI nodes, but the incoming operands have not been
5272 // emitted yet.
5273 for (BasicBlock::iterator I = SuccBB->begin();
Chris Lattner8c494ab2006-10-27 23:50:33 +00005274 (PN = dyn_cast<PHINode>(I)); ++I) {
5275 // Ignore dead phi's.
5276 if (PN->use_empty()) continue;
Dan Gohman7c3234c2008-08-27 23:52:12 +00005277
Chris Lattner8c494ab2006-10-27 23:50:33 +00005278 unsigned Reg;
5279 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
Dan Gohman7c3234c2008-08-27 23:52:12 +00005280
Chris Lattner8c494ab2006-10-27 23:50:33 +00005281 if (Constant *C = dyn_cast<Constant>(PHIOp)) {
Dan Gohman7c3234c2008-08-27 23:52:12 +00005282 unsigned &RegOut = SDL->ConstantsOut[C];
Chris Lattner8c494ab2006-10-27 23:50:33 +00005283 if (RegOut == 0) {
Dan Gohman7c3234c2008-08-27 23:52:12 +00005284 RegOut = FuncInfo->CreateRegForValue(C);
5285 SDL->CopyValueToVirtualRegister(C, RegOut);
Chris Lattner1c08c712005-01-07 07:47:53 +00005286 }
Chris Lattner8c494ab2006-10-27 23:50:33 +00005287 Reg = RegOut;
5288 } else {
Dan Gohman7c3234c2008-08-27 23:52:12 +00005289 Reg = FuncInfo->ValueMap[PHIOp];
Chris Lattner8c494ab2006-10-27 23:50:33 +00005290 if (Reg == 0) {
5291 assert(isa<AllocaInst>(PHIOp) &&
Dan Gohman7c3234c2008-08-27 23:52:12 +00005292 FuncInfo->StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
Chris Lattner8c494ab2006-10-27 23:50:33 +00005293 "Didn't codegen value into a register!??");
Dan Gohman7c3234c2008-08-27 23:52:12 +00005294 Reg = FuncInfo->CreateRegForValue(PHIOp);
5295 SDL->CopyValueToVirtualRegister(PHIOp, Reg);
Chris Lattner7e021512006-03-31 02:12:18 +00005296 }
Chris Lattner1c08c712005-01-07 07:47:53 +00005297 }
Chris Lattner8c494ab2006-10-27 23:50:33 +00005298
5299 // Remember that this register needs to added to the machine PHI node as
5300 // the input for this MBB.
Dan Gohman6f498b02008-08-04 23:42:46 +00005301 SmallVector<MVT, 4> ValueVTs;
5302 ComputeValueVTs(TLI, PN->getType(), ValueVTs);
5303 for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
5304 MVT VT = ValueVTs[vti];
5305 unsigned NumRegisters = TLI.getNumRegisters(VT);
5306 for (unsigned i = 0, e = NumRegisters; i != e; ++i)
Dan Gohman7c3234c2008-08-27 23:52:12 +00005307 SDL->PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
Dan Gohman6f498b02008-08-04 23:42:46 +00005308 Reg += NumRegisters;
5309 }
Chris Lattner8c494ab2006-10-27 23:50:33 +00005310 }
Chris Lattner1c08c712005-01-07 07:47:53 +00005311 }
Dan Gohman7c3234c2008-08-27 23:52:12 +00005312 SDL->ConstantsOut.clear();
Chris Lattner1c08c712005-01-07 07:47:53 +00005313
5314 // Lower the terminator after the copies are emitted.
Dan Gohman7c3234c2008-08-27 23:52:12 +00005315 SDL->visit(*LLVMBB->getTerminator());
Dan Gohmanf350b272008-08-23 02:25:05 +00005316}
5317
5318void SelectionDAGISel::SelectBasicBlock(BasicBlock *LLVMBB,
5319 BasicBlock::iterator Begin,
5320 BasicBlock::iterator End,
Dan Gohman7c3234c2008-08-27 23:52:12 +00005321 bool DoArgs) {
Dan Gohmanf350b272008-08-23 02:25:05 +00005322 // Lower any arguments needed in this block if this is the entry block.
5323 if (DoArgs)
Dan Gohman7c3234c2008-08-27 23:52:12 +00005324 LowerArguments(LLVMBB);
Dan Gohmanf350b272008-08-23 02:25:05 +00005325
Dan Gohman7c3234c2008-08-27 23:52:12 +00005326 SDL->setCurrentBasicBlock(BB);
Dan Gohmanf350b272008-08-23 02:25:05 +00005327
5328 MachineModuleInfo *MMI = CurDAG->getMachineModuleInfo();
5329
5330 if (MMI && BB->isLandingPad()) {
5331 // Add a label to mark the beginning of the landing pad. Deletion of the
5332 // landing pad can thus be detected via the MachineModuleInfo.
5333 unsigned LabelID = MMI->addLandingPad(BB);
5334 CurDAG->setRoot(CurDAG->getLabel(ISD::EH_LABEL,
5335 CurDAG->getEntryNode(), LabelID));
5336
5337 // Mark exception register as live in.
5338 unsigned Reg = TLI.getExceptionAddressRegister();
5339 if (Reg) BB->addLiveIn(Reg);
5340
5341 // Mark exception selector register as live in.
5342 Reg = TLI.getExceptionSelectorRegister();
5343 if (Reg) BB->addLiveIn(Reg);
5344
5345 // FIXME: Hack around an exception handling flaw (PR1508): the personality
5346 // function and list of typeids logically belong to the invoke (or, if you
5347 // like, the basic block containing the invoke), and need to be associated
5348 // with it in the dwarf exception handling tables. Currently however the
5349 // information is provided by an intrinsic (eh.selector) that can be moved
5350 // to unexpected places by the optimizers: if the unwind edge is critical,
5351 // then breaking it can result in the intrinsics being in the successor of
5352 // the landing pad, not the landing pad itself. This results in exceptions
5353 // not being caught because no typeids are associated with the invoke.
5354 // This may not be the only way things can go wrong, but it is the only way
5355 // we try to work around for the moment.
5356 BranchInst *Br = dyn_cast<BranchInst>(LLVMBB->getTerminator());
5357
5358 if (Br && Br->isUnconditional()) { // Critical edge?
5359 BasicBlock::iterator I, E;
5360 for (I = LLVMBB->begin(), E = --LLVMBB->end(); I != E; ++I)
5361 if (isSelector(I))
5362 break;
5363
5364 if (I == E)
5365 // No catch info found - try to extract some from the successor.
Dan Gohman7c3234c2008-08-27 23:52:12 +00005366 copyCatchInfo(Br->getSuccessor(0), LLVMBB, MMI, *FuncInfo);
Dan Gohmanf350b272008-08-23 02:25:05 +00005367 }
5368 }
5369
5370 // Lower all of the non-terminator instructions.
5371 for (BasicBlock::iterator I = Begin; I != End; ++I)
5372 if (!isa<TerminatorInst>(I))
Dan Gohman7c3234c2008-08-27 23:52:12 +00005373 SDL->visit(*I);
Dan Gohmanf350b272008-08-23 02:25:05 +00005374
5375 // Ensure that all instructions which are used outside of their defining
5376 // blocks are available as virtual registers. Invoke is handled elsewhere.
5377 for (BasicBlock::iterator I = Begin; I != End; ++I)
5378 if (!I->use_empty() && !isa<PHINode>(I) && !isa<InvokeInst>(I)) {
Dan Gohman7c3234c2008-08-27 23:52:12 +00005379 DenseMap<const Value*,unsigned>::iterator VMI =FuncInfo->ValueMap.find(I);
5380 if (VMI != FuncInfo->ValueMap.end())
5381 SDL->CopyValueToVirtualRegister(I, VMI->second);
Dan Gohmanf350b272008-08-23 02:25:05 +00005382 }
5383
5384 // Handle PHI nodes in successor blocks.
5385 if (Begin != End && End == LLVMBB->end())
Dan Gohman7c3234c2008-08-27 23:52:12 +00005386 HandlePHINodesInSuccessorBlocks(LLVMBB);
Anton Korobeynikov4198c582007-04-09 12:31:58 +00005387
Chris Lattnera651cf62005-01-17 19:43:36 +00005388 // Make sure the root of the DAG is up-to-date.
Dan Gohman7c3234c2008-08-27 23:52:12 +00005389 CurDAG->setRoot(SDL->getControlRoot());
Arnold Schwaighoferc85e1712007-10-11 19:40:01 +00005390
5391 // Check whether calls in this block are real tail calls. Fix up CALL nodes
5392 // with correct tailcall attribute so that the target can rely on the tailcall
5393 // attribute indicating whether the call is really eligible for tail call
5394 // optimization.
Dan Gohmanf350b272008-08-23 02:25:05 +00005395 CheckDAGForTailCallsAndFixThem(*CurDAG, TLI);
5396
5397 // Final step, emit the lowered DAG as machine code.
5398 CodeGenAndEmitDAG();
Dan Gohman7c3234c2008-08-27 23:52:12 +00005399 SDL->clear();
Chris Lattner1c08c712005-01-07 07:47:53 +00005400}
5401
Dan Gohmanf350b272008-08-23 02:25:05 +00005402void SelectionDAGISel::ComputeLiveOutVRegInfo() {
Chris Lattneread0d882008-06-17 06:09:18 +00005403 SmallPtrSet<SDNode*, 128> VisitedNodes;
5404 SmallVector<SDNode*, 128> Worklist;
5405
Dan Gohmanf350b272008-08-23 02:25:05 +00005406 Worklist.push_back(CurDAG->getRoot().Val);
Chris Lattneread0d882008-06-17 06:09:18 +00005407
5408 APInt Mask;
5409 APInt KnownZero;
5410 APInt KnownOne;
5411
5412 while (!Worklist.empty()) {
5413 SDNode *N = Worklist.back();
5414 Worklist.pop_back();
5415
5416 // If we've already seen this node, ignore it.
5417 if (!VisitedNodes.insert(N))
5418 continue;
5419
5420 // Otherwise, add all chain operands to the worklist.
5421 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
5422 if (N->getOperand(i).getValueType() == MVT::Other)
5423 Worklist.push_back(N->getOperand(i).Val);
5424
5425 // If this is a CopyToReg with a vreg dest, process it.
5426 if (N->getOpcode() != ISD::CopyToReg)
5427 continue;
5428
5429 unsigned DestReg = cast<RegisterSDNode>(N->getOperand(1))->getReg();
5430 if (!TargetRegisterInfo::isVirtualRegister(DestReg))
5431 continue;
5432
5433 // Ignore non-scalar or non-integer values.
Dan Gohman475871a2008-07-27 21:46:04 +00005434 SDValue Src = N->getOperand(2);
Chris Lattneread0d882008-06-17 06:09:18 +00005435 MVT SrcVT = Src.getValueType();
5436 if (!SrcVT.isInteger() || SrcVT.isVector())
5437 continue;
5438
Dan Gohmanf350b272008-08-23 02:25:05 +00005439 unsigned NumSignBits = CurDAG->ComputeNumSignBits(Src);
Chris Lattneread0d882008-06-17 06:09:18 +00005440 Mask = APInt::getAllOnesValue(SrcVT.getSizeInBits());
Dan Gohmanf350b272008-08-23 02:25:05 +00005441 CurDAG->ComputeMaskedBits(Src, Mask, KnownZero, KnownOne);
Chris Lattneread0d882008-06-17 06:09:18 +00005442
5443 // Only install this information if it tells us something.
5444 if (NumSignBits != 1 || KnownZero != 0 || KnownOne != 0) {
5445 DestReg -= TargetRegisterInfo::FirstVirtualRegister;
Dan Gohmanf350b272008-08-23 02:25:05 +00005446 FunctionLoweringInfo &FLI = CurDAG->getFunctionLoweringInfo();
Chris Lattneread0d882008-06-17 06:09:18 +00005447 if (DestReg >= FLI.LiveOutRegInfo.size())
5448 FLI.LiveOutRegInfo.resize(DestReg+1);
5449 FunctionLoweringInfo::LiveOutInfo &LOI = FLI.LiveOutRegInfo[DestReg];
5450 LOI.NumSignBits = NumSignBits;
5451 LOI.KnownOne = NumSignBits;
5452 LOI.KnownZero = NumSignBits;
5453 }
5454 }
5455}
5456
Dan Gohmanf350b272008-08-23 02:25:05 +00005457void SelectionDAGISel::CodeGenAndEmitDAG() {
Dan Gohman462dc7f2008-07-21 20:00:07 +00005458 std::string GroupName;
5459 if (TimePassesIsEnabled)
5460 GroupName = "Instruction Selection and Scheduling";
5461 std::string BlockName;
5462 if (ViewDAGCombine1 || ViewLegalizeTypesDAGs || ViewLegalizeDAGs ||
5463 ViewDAGCombine2 || ViewISelDAGs || ViewSchedDAGs || ViewSUnitDAGs)
Dan Gohmanf350b272008-08-23 02:25:05 +00005464 BlockName = CurDAG->getMachineFunction().getFunction()->getName() + ':' +
Dan Gohman462dc7f2008-07-21 20:00:07 +00005465 BB->getBasicBlock()->getName();
5466
5467 DOUT << "Initial selection DAG:\n";
Dan Gohmanf350b272008-08-23 02:25:05 +00005468 DEBUG(CurDAG->dump());
Dan Gohman462dc7f2008-07-21 20:00:07 +00005469
Dan Gohmanf350b272008-08-23 02:25:05 +00005470 if (ViewDAGCombine1) CurDAG->viewGraph("dag-combine1 input for " + BlockName);
Dan Gohman417e11b2007-10-08 15:12:17 +00005471
Chris Lattneraf21d552005-10-10 16:47:10 +00005472 // Run the DAG combiner in pre-legalize mode.
Evan Chengebffb662008-07-01 17:59:20 +00005473 if (TimePassesIsEnabled) {
Dan Gohman5e843682008-07-14 18:19:29 +00005474 NamedRegionTimer T("DAG Combining 1", GroupName);
Dan Gohmanf350b272008-08-23 02:25:05 +00005475 CurDAG->Combine(false, *AA, Fast);
Evan Chengebffb662008-07-01 17:59:20 +00005476 } else {
Dan Gohmanf350b272008-08-23 02:25:05 +00005477 CurDAG->Combine(false, *AA, Fast);
Evan Chengebffb662008-07-01 17:59:20 +00005478 }
Nate Begeman2300f552005-09-07 00:15:36 +00005479
Dan Gohman417e11b2007-10-08 15:12:17 +00005480 DOUT << "Optimized lowered selection DAG:\n";
Dan Gohmanf350b272008-08-23 02:25:05 +00005481 DEBUG(CurDAG->dump());
Duncan Sandsf00e74f2008-07-17 17:06:03 +00005482
Chris Lattner1c08c712005-01-07 07:47:53 +00005483 // Second step, hack on the DAG until it only uses operations and types that
5484 // the target supports.
Duncan Sandsf00e74f2008-07-17 17:06:03 +00005485 if (EnableLegalizeTypes) {// Enable this some day.
Dan Gohmanf350b272008-08-23 02:25:05 +00005486 if (ViewLegalizeTypesDAGs) CurDAG->viewGraph("legalize-types input for " +
5487 BlockName);
Dan Gohman462dc7f2008-07-21 20:00:07 +00005488
5489 if (TimePassesIsEnabled) {
5490 NamedRegionTimer T("Type Legalization", GroupName);
Dan Gohmanf350b272008-08-23 02:25:05 +00005491 CurDAG->LegalizeTypes();
Dan Gohman462dc7f2008-07-21 20:00:07 +00005492 } else {
Dan Gohmanf350b272008-08-23 02:25:05 +00005493 CurDAG->LegalizeTypes();
Dan Gohman462dc7f2008-07-21 20:00:07 +00005494 }
5495
5496 DOUT << "Type-legalized selection DAG:\n";
Dan Gohmanf350b272008-08-23 02:25:05 +00005497 DEBUG(CurDAG->dump());
Dan Gohman462dc7f2008-07-21 20:00:07 +00005498
Chris Lattner70587ea2008-07-10 23:37:50 +00005499 // TODO: enable a dag combine pass here.
5500 }
Duncan Sandsf00e74f2008-07-17 17:06:03 +00005501
Dan Gohmanf350b272008-08-23 02:25:05 +00005502 if (ViewLegalizeDAGs) CurDAG->viewGraph("legalize input for " + BlockName);
Dan Gohman462dc7f2008-07-21 20:00:07 +00005503
Evan Chengebffb662008-07-01 17:59:20 +00005504 if (TimePassesIsEnabled) {
Dan Gohman5e843682008-07-14 18:19:29 +00005505 NamedRegionTimer T("DAG Legalization", GroupName);
Dan Gohmanf350b272008-08-23 02:25:05 +00005506 CurDAG->Legalize();
Evan Chengebffb662008-07-01 17:59:20 +00005507 } else {
Dan Gohmanf350b272008-08-23 02:25:05 +00005508 CurDAG->Legalize();
Evan Chengebffb662008-07-01 17:59:20 +00005509 }
Nate Begemanf15485a2006-03-27 01:32:24 +00005510
Bill Wendling832171c2006-12-07 20:04:42 +00005511 DOUT << "Legalized selection DAG:\n";
Dan Gohmanf350b272008-08-23 02:25:05 +00005512 DEBUG(CurDAG->dump());
Nate Begemanf15485a2006-03-27 01:32:24 +00005513
Dan Gohmanf350b272008-08-23 02:25:05 +00005514 if (ViewDAGCombine2) CurDAG->viewGraph("dag-combine2 input for " + BlockName);
Dan Gohman462dc7f2008-07-21 20:00:07 +00005515
Chris Lattneraf21d552005-10-10 16:47:10 +00005516 // Run the DAG combiner in post-legalize mode.
Evan Chengebffb662008-07-01 17:59:20 +00005517 if (TimePassesIsEnabled) {
Dan Gohman5e843682008-07-14 18:19:29 +00005518 NamedRegionTimer T("DAG Combining 2", GroupName);
Dan Gohmanf350b272008-08-23 02:25:05 +00005519 CurDAG->Combine(true, *AA, Fast);
Evan Chengebffb662008-07-01 17:59:20 +00005520 } else {
Dan Gohmanf350b272008-08-23 02:25:05 +00005521 CurDAG->Combine(true, *AA, Fast);
Evan Chengebffb662008-07-01 17:59:20 +00005522 }
Nate Begeman2300f552005-09-07 00:15:36 +00005523
Dan Gohman417e11b2007-10-08 15:12:17 +00005524 DOUT << "Optimized legalized selection DAG:\n";
Dan Gohmanf350b272008-08-23 02:25:05 +00005525 DEBUG(CurDAG->dump());
Dan Gohman417e11b2007-10-08 15:12:17 +00005526
Dan Gohmanf350b272008-08-23 02:25:05 +00005527 if (ViewISelDAGs) CurDAG->viewGraph("isel input for " + BlockName);
Chris Lattneread0d882008-06-17 06:09:18 +00005528
Dan Gohman925a7e82008-08-13 19:47:40 +00005529 if (!Fast && EnableValueProp)
Dan Gohmanf350b272008-08-23 02:25:05 +00005530 ComputeLiveOutVRegInfo();
Evan Cheng552c4a82006-04-28 02:09:19 +00005531
Chris Lattnera33ef482005-03-30 01:10:47 +00005532 // Third, instruction select all of the operations to machine code, adding the
5533 // code to the MachineBasicBlock.
Evan Chengebffb662008-07-01 17:59:20 +00005534 if (TimePassesIsEnabled) {
Dan Gohman5e843682008-07-14 18:19:29 +00005535 NamedRegionTimer T("Instruction Selection", GroupName);
Dan Gohmanf350b272008-08-23 02:25:05 +00005536 InstructionSelect();
Evan Chengebffb662008-07-01 17:59:20 +00005537 } else {
Dan Gohmanf350b272008-08-23 02:25:05 +00005538 InstructionSelect();
Evan Chengebffb662008-07-01 17:59:20 +00005539 }
Evan Chengdb8d56b2008-06-30 20:45:06 +00005540
Dan Gohman462dc7f2008-07-21 20:00:07 +00005541 DOUT << "Selected selection DAG:\n";
Dan Gohmanf350b272008-08-23 02:25:05 +00005542 DEBUG(CurDAG->dump());
Dan Gohman462dc7f2008-07-21 20:00:07 +00005543
Dan Gohmanf350b272008-08-23 02:25:05 +00005544 if (ViewSchedDAGs) CurDAG->viewGraph("scheduler input for " + BlockName);
Dan Gohman462dc7f2008-07-21 20:00:07 +00005545
Dan Gohman5e843682008-07-14 18:19:29 +00005546 // Schedule machine code.
5547 ScheduleDAG *Scheduler;
5548 if (TimePassesIsEnabled) {
5549 NamedRegionTimer T("Instruction Scheduling", GroupName);
Dan Gohmanf350b272008-08-23 02:25:05 +00005550 Scheduler = Schedule();
Dan Gohman5e843682008-07-14 18:19:29 +00005551 } else {
Dan Gohmanf350b272008-08-23 02:25:05 +00005552 Scheduler = Schedule();
Dan Gohman5e843682008-07-14 18:19:29 +00005553 }
5554
Dan Gohman462dc7f2008-07-21 20:00:07 +00005555 if (ViewSUnitDAGs) Scheduler->viewGraph();
5556
Evan Chengdb8d56b2008-06-30 20:45:06 +00005557 // Emit machine code to BB. This can change 'BB' to the last block being
5558 // inserted into.
Evan Chengebffb662008-07-01 17:59:20 +00005559 if (TimePassesIsEnabled) {
Dan Gohman5e843682008-07-14 18:19:29 +00005560 NamedRegionTimer T("Instruction Creation", GroupName);
5561 BB = Scheduler->EmitSchedule();
Evan Chengebffb662008-07-01 17:59:20 +00005562 } else {
Dan Gohman5e843682008-07-14 18:19:29 +00005563 BB = Scheduler->EmitSchedule();
5564 }
5565
5566 // Free the scheduler state.
5567 if (TimePassesIsEnabled) {
5568 NamedRegionTimer T("Instruction Scheduling Cleanup", GroupName);
5569 delete Scheduler;
5570 } else {
5571 delete Scheduler;
Evan Chengebffb662008-07-01 17:59:20 +00005572 }
Evan Chengdb8d56b2008-06-30 20:45:06 +00005573
Bill Wendling832171c2006-12-07 20:04:42 +00005574 DOUT << "Selected machine code:\n";
Chris Lattner1c08c712005-01-07 07:47:53 +00005575 DEBUG(BB->dump());
Nate Begemanf15485a2006-03-27 01:32:24 +00005576}
Chris Lattner1c08c712005-01-07 07:47:53 +00005577
Dan Gohman7c3234c2008-08-27 23:52:12 +00005578void SelectionDAGISel::SelectAllBasicBlocks(Function &Fn, MachineFunction &MF) {
Evan Cheng39fd6e82008-08-07 00:43:25 +00005579 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I) {
5580 BasicBlock *LLVMBB = &*I;
Dan Gohman7c3234c2008-08-27 23:52:12 +00005581 BB = FuncInfo->MBBMap[LLVMBB];
Dan Gohmanf350b272008-08-23 02:25:05 +00005582
5583 BasicBlock::iterator Begin = LLVMBB->begin();
5584 BasicBlock::iterator End = LLVMBB->end();
5585 bool DoArgs = LLVMBB == &Fn.getEntryBlock();
5586
5587 // Before doing SelectionDAG ISel, see if FastISel has been requested.
5588 // FastISel doesn't support EH landing pads, which require special handling.
5589 if (EnableFastISel && !BB->isLandingPad()) {
Dan Gohman7c3234c2008-08-27 23:52:12 +00005590 if (FastISel *F = TLI.createFastISel(*FuncInfo->MF)) {
Dan Gohmanf350b272008-08-23 02:25:05 +00005591 while (Begin != End) {
Dan Gohman7c3234c2008-08-27 23:52:12 +00005592 Begin = F->SelectInstructions(Begin, End, FuncInfo->ValueMap,
5593 FuncInfo->MBBMap, BB);
Dan Gohmanf350b272008-08-23 02:25:05 +00005594
5595 if (Begin == End)
5596 // The "fast" selector selected the entire block, so we're done.
5597 break;
5598
5599 // Handle certain instructions as single-LLVM-Instruction blocks.
5600 if (isa<CallInst>(Begin) || isa<LoadInst>(Begin) ||
5601 isa<StoreInst>(Begin)) {
5602 if (Begin->getType() != Type::VoidTy) {
Dan Gohman7c3234c2008-08-27 23:52:12 +00005603 unsigned &R = FuncInfo->ValueMap[Begin];
Dan Gohmanf350b272008-08-23 02:25:05 +00005604 if (!R)
Dan Gohman7c3234c2008-08-27 23:52:12 +00005605 R = FuncInfo->CreateRegForValue(Begin);
Dan Gohmanf350b272008-08-23 02:25:05 +00005606 }
5607
Dan Gohman7c3234c2008-08-27 23:52:12 +00005608 SelectBasicBlock(LLVMBB, Begin, next(Begin), DoArgs);
Dan Gohmanf350b272008-08-23 02:25:05 +00005609
5610 ++Begin;
5611 DoArgs = false;
5612 continue;
5613 }
5614
5615 if (!DisableFastISelAbort &&
5616 // For now, don't abort on non-conditional-branch terminators.
5617 (!isa<TerminatorInst>(Begin) ||
5618 (isa<BranchInst>(Begin) &&
5619 cast<BranchInst>(Begin)->isUnconditional()))) {
5620 // The "fast" selector couldn't handle something and bailed.
5621 // For the purpose of debugging, just abort.
5622#ifndef NDEBUG
5623 Begin->dump();
5624#endif
5625 assert(0 && "FastISel didn't select the entire block");
5626 }
5627 break;
5628 }
5629 delete F;
5630 }
5631 }
5632
5633 if (Begin != End || DoArgs)
Dan Gohman7c3234c2008-08-27 23:52:12 +00005634 SelectBasicBlock(LLVMBB, Begin, End, DoArgs);
Dan Gohmanf350b272008-08-23 02:25:05 +00005635
Dan Gohman7c3234c2008-08-27 23:52:12 +00005636 FinishBasicBlock();
Evan Cheng39fd6e82008-08-07 00:43:25 +00005637 }
Dan Gohman0e5f1302008-07-07 23:02:41 +00005638}
5639
Dan Gohmanfed90b62008-07-28 21:51:04 +00005640void
Dan Gohman7c3234c2008-08-27 23:52:12 +00005641SelectionDAGISel::FinishBasicBlock() {
Dan Gohmanf350b272008-08-23 02:25:05 +00005642
5643 // Perform target specific isel post processing.
5644 InstructionSelectPostProcessing();
Nate Begemanf15485a2006-03-27 01:32:24 +00005645
Dan Gohmanf350b272008-08-23 02:25:05 +00005646 DOUT << "Target-post-processed machine code:\n";
5647 DEBUG(BB->dump());
Nate Begemanf15485a2006-03-27 01:32:24 +00005648
Anton Korobeynikov4198c582007-04-09 12:31:58 +00005649 DOUT << "Total amount of phi nodes to update: "
Dan Gohman7c3234c2008-08-27 23:52:12 +00005650 << SDL->PHINodesToUpdate.size() << "\n";
5651 DEBUG(for (unsigned i = 0, e = SDL->PHINodesToUpdate.size(); i != e; ++i)
5652 DOUT << "Node " << i << " : (" << SDL->PHINodesToUpdate[i].first
5653 << ", " << SDL->PHINodesToUpdate[i].second << ")\n";);
Nate Begemanf15485a2006-03-27 01:32:24 +00005654
Chris Lattnera33ef482005-03-30 01:10:47 +00005655 // Next, now that we know what the last MBB the LLVM BB expanded is, update
Chris Lattner1c08c712005-01-07 07:47:53 +00005656 // PHI nodes in successors.
Dan Gohman7c3234c2008-08-27 23:52:12 +00005657 if (SDL->SwitchCases.empty() &&
5658 SDL->JTCases.empty() &&
5659 SDL->BitTestCases.empty()) {
5660 for (unsigned i = 0, e = SDL->PHINodesToUpdate.size(); i != e; ++i) {
5661 MachineInstr *PHI = SDL->PHINodesToUpdate[i].first;
Nate Begemanf15485a2006-03-27 01:32:24 +00005662 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
5663 "This is not a machine PHI node that we are updating!");
Dan Gohman7c3234c2008-08-27 23:52:12 +00005664 PHI->addOperand(MachineOperand::CreateReg(SDL->PHINodesToUpdate[i].second,
Chris Lattner9ce2e9d2007-12-30 00:57:42 +00005665 false));
5666 PHI->addOperand(MachineOperand::CreateMBB(BB));
Nate Begemanf15485a2006-03-27 01:32:24 +00005667 }
Dan Gohman7c3234c2008-08-27 23:52:12 +00005668 SDL->PHINodesToUpdate.clear();
Nate Begemanf15485a2006-03-27 01:32:24 +00005669 return;
Chris Lattner1c08c712005-01-07 07:47:53 +00005670 }
Anton Korobeynikov4198c582007-04-09 12:31:58 +00005671
Dan Gohman7c3234c2008-08-27 23:52:12 +00005672 for (unsigned i = 0, e = SDL->BitTestCases.size(); i != e; ++i) {
Anton Korobeynikov4198c582007-04-09 12:31:58 +00005673 // Lower header first, if it wasn't already lowered
Dan Gohman7c3234c2008-08-27 23:52:12 +00005674 if (!SDL->BitTestCases[i].Emitted) {
Anton Korobeynikov4198c582007-04-09 12:31:58 +00005675 // Set the current basic block to the mbb we wish to insert the code into
Dan Gohman7c3234c2008-08-27 23:52:12 +00005676 BB = SDL->BitTestCases[i].Parent;
5677 SDL->setCurrentBasicBlock(BB);
Anton Korobeynikov4198c582007-04-09 12:31:58 +00005678 // Emit the code
Dan Gohman7c3234c2008-08-27 23:52:12 +00005679 SDL->visitBitTestHeader(SDL->BitTestCases[i]);
5680 CurDAG->setRoot(SDL->getRoot());
Dan Gohmanf350b272008-08-23 02:25:05 +00005681 CodeGenAndEmitDAG();
Dan Gohman7c3234c2008-08-27 23:52:12 +00005682 SDL->clear();
Anton Korobeynikov4198c582007-04-09 12:31:58 +00005683 }
5684
Dan Gohman7c3234c2008-08-27 23:52:12 +00005685 for (unsigned j = 0, ej = SDL->BitTestCases[i].Cases.size(); j != ej; ++j) {
Anton Korobeynikov4198c582007-04-09 12:31:58 +00005686 // Set the current basic block to the mbb we wish to insert the code into
Dan Gohman7c3234c2008-08-27 23:52:12 +00005687 BB = SDL->BitTestCases[i].Cases[j].ThisBB;
5688 SDL->setCurrentBasicBlock(BB);
Anton Korobeynikov4198c582007-04-09 12:31:58 +00005689 // Emit the code
5690 if (j+1 != ej)
Dan Gohman7c3234c2008-08-27 23:52:12 +00005691 SDL->visitBitTestCase(SDL->BitTestCases[i].Cases[j+1].ThisBB,
5692 SDL->BitTestCases[i].Reg,
5693 SDL->BitTestCases[i].Cases[j]);
Anton Korobeynikov4198c582007-04-09 12:31:58 +00005694 else
Dan Gohman7c3234c2008-08-27 23:52:12 +00005695 SDL->visitBitTestCase(SDL->BitTestCases[i].Default,
5696 SDL->BitTestCases[i].Reg,
5697 SDL->BitTestCases[i].Cases[j]);
Anton Korobeynikov4198c582007-04-09 12:31:58 +00005698
5699
Dan Gohman7c3234c2008-08-27 23:52:12 +00005700 CurDAG->setRoot(SDL->getRoot());
Dan Gohmanf350b272008-08-23 02:25:05 +00005701 CodeGenAndEmitDAG();
Dan Gohman7c3234c2008-08-27 23:52:12 +00005702 SDL->clear();
Anton Korobeynikov4198c582007-04-09 12:31:58 +00005703 }
5704
5705 // Update PHI Nodes
Dan Gohman7c3234c2008-08-27 23:52:12 +00005706 for (unsigned pi = 0, pe = SDL->PHINodesToUpdate.size(); pi != pe; ++pi) {
5707 MachineInstr *PHI = SDL->PHINodesToUpdate[pi].first;
Anton Korobeynikov4198c582007-04-09 12:31:58 +00005708 MachineBasicBlock *PHIBB = PHI->getParent();
5709 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
5710 "This is not a machine PHI node that we are updating!");
5711 // This is "default" BB. We have two jumps to it. From "header" BB and
5712 // from last "case" BB.
Dan Gohman7c3234c2008-08-27 23:52:12 +00005713 if (PHIBB == SDL->BitTestCases[i].Default) {
5714 PHI->addOperand(MachineOperand::CreateReg(SDL->PHINodesToUpdate[pi].second,
Chris Lattner9ce2e9d2007-12-30 00:57:42 +00005715 false));
Dan Gohman7c3234c2008-08-27 23:52:12 +00005716 PHI->addOperand(MachineOperand::CreateMBB(SDL->BitTestCases[i].Parent));
5717 PHI->addOperand(MachineOperand::CreateReg(SDL->PHINodesToUpdate[pi].second,
Chris Lattner9ce2e9d2007-12-30 00:57:42 +00005718 false));
Dan Gohman7c3234c2008-08-27 23:52:12 +00005719 PHI->addOperand(MachineOperand::CreateMBB(SDL->BitTestCases[i].Cases.
Chris Lattner9ce2e9d2007-12-30 00:57:42 +00005720 back().ThisBB));
Anton Korobeynikov4198c582007-04-09 12:31:58 +00005721 }
5722 // One of "cases" BB.
Dan Gohman7c3234c2008-08-27 23:52:12 +00005723 for (unsigned j = 0, ej = SDL->BitTestCases[i].Cases.size();
5724 j != ej; ++j) {
5725 MachineBasicBlock* cBB = SDL->BitTestCases[i].Cases[j].ThisBB;
Anton Korobeynikov4198c582007-04-09 12:31:58 +00005726 if (cBB->succ_end() !=
5727 std::find(cBB->succ_begin(),cBB->succ_end(), PHIBB)) {
Dan Gohman7c3234c2008-08-27 23:52:12 +00005728 PHI->addOperand(MachineOperand::CreateReg(SDL->PHINodesToUpdate[pi].second,
Chris Lattner9ce2e9d2007-12-30 00:57:42 +00005729 false));
5730 PHI->addOperand(MachineOperand::CreateMBB(cBB));
Anton Korobeynikov4198c582007-04-09 12:31:58 +00005731 }
5732 }
5733 }
5734 }
Dan Gohman7c3234c2008-08-27 23:52:12 +00005735 SDL->BitTestCases.clear();
Anton Korobeynikov4198c582007-04-09 12:31:58 +00005736
Nate Begeman9453eea2006-04-23 06:26:20 +00005737 // If the JumpTable record is filled in, then we need to emit a jump table.
5738 // Updating the PHI nodes is tricky in this case, since we need to determine
5739 // whether the PHI is a successor of the range check MBB or the jump table MBB
Dan Gohman7c3234c2008-08-27 23:52:12 +00005740 for (unsigned i = 0, e = SDL->JTCases.size(); i != e; ++i) {
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00005741 // Lower header first, if it wasn't already lowered
Dan Gohman7c3234c2008-08-27 23:52:12 +00005742 if (!SDL->JTCases[i].first.Emitted) {
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00005743 // Set the current basic block to the mbb we wish to insert the code into
Dan Gohman7c3234c2008-08-27 23:52:12 +00005744 BB = SDL->JTCases[i].first.HeaderBB;
5745 SDL->setCurrentBasicBlock(BB);
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00005746 // Emit the code
Dan Gohman7c3234c2008-08-27 23:52:12 +00005747 SDL->visitJumpTableHeader(SDL->JTCases[i].second, SDL->JTCases[i].first);
5748 CurDAG->setRoot(SDL->getRoot());
Dan Gohmanf350b272008-08-23 02:25:05 +00005749 CodeGenAndEmitDAG();
Dan Gohman7c3234c2008-08-27 23:52:12 +00005750 SDL->clear();
Anton Korobeynikov4198c582007-04-09 12:31:58 +00005751 }
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00005752
Nate Begeman37efe672006-04-22 18:53:45 +00005753 // Set the current basic block to the mbb we wish to insert the code into
Dan Gohman7c3234c2008-08-27 23:52:12 +00005754 BB = SDL->JTCases[i].second.MBB;
5755 SDL->setCurrentBasicBlock(BB);
Nate Begeman37efe672006-04-22 18:53:45 +00005756 // Emit the code
Dan Gohman7c3234c2008-08-27 23:52:12 +00005757 SDL->visitJumpTable(SDL->JTCases[i].second);
5758 CurDAG->setRoot(SDL->getRoot());
Dan Gohmanf350b272008-08-23 02:25:05 +00005759 CodeGenAndEmitDAG();
Dan Gohman7c3234c2008-08-27 23:52:12 +00005760 SDL->clear();
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00005761
Nate Begeman37efe672006-04-22 18:53:45 +00005762 // Update PHI Nodes
Dan Gohman7c3234c2008-08-27 23:52:12 +00005763 for (unsigned pi = 0, pe = SDL->PHINodesToUpdate.size(); pi != pe; ++pi) {
5764 MachineInstr *PHI = SDL->PHINodesToUpdate[pi].first;
Nate Begeman37efe672006-04-22 18:53:45 +00005765 MachineBasicBlock *PHIBB = PHI->getParent();
5766 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
5767 "This is not a machine PHI node that we are updating!");
Anton Korobeynikov4198c582007-04-09 12:31:58 +00005768 // "default" BB. We can go there only from header BB.
Dan Gohman7c3234c2008-08-27 23:52:12 +00005769 if (PHIBB == SDL->JTCases[i].second.Default) {
5770 PHI->addOperand(MachineOperand::CreateReg(SDL->PHINodesToUpdate[pi].second,
Chris Lattner9ce2e9d2007-12-30 00:57:42 +00005771 false));
Dan Gohman7c3234c2008-08-27 23:52:12 +00005772 PHI->addOperand(MachineOperand::CreateMBB(SDL->JTCases[i].first.HeaderBB));
Nate Begemanf4360a42006-05-03 03:48:02 +00005773 }
Anton Korobeynikov4198c582007-04-09 12:31:58 +00005774 // JT BB. Just iterate over successors here
Nate Begemanf4360a42006-05-03 03:48:02 +00005775 if (BB->succ_end() != std::find(BB->succ_begin(),BB->succ_end(), PHIBB)) {
Dan Gohman7c3234c2008-08-27 23:52:12 +00005776 PHI->addOperand(MachineOperand::CreateReg(SDL->PHINodesToUpdate[pi].second,
Chris Lattner9ce2e9d2007-12-30 00:57:42 +00005777 false));
5778 PHI->addOperand(MachineOperand::CreateMBB(BB));
Nate Begeman37efe672006-04-22 18:53:45 +00005779 }
5780 }
Nate Begeman37efe672006-04-22 18:53:45 +00005781 }
Dan Gohman7c3234c2008-08-27 23:52:12 +00005782 SDL->JTCases.clear();
Nate Begeman37efe672006-04-22 18:53:45 +00005783
Chris Lattnerb2e806e2006-10-22 23:00:53 +00005784 // If the switch block involved a branch to one of the actual successors, we
5785 // need to update PHI nodes in that block.
Dan Gohman7c3234c2008-08-27 23:52:12 +00005786 for (unsigned i = 0, e = SDL->PHINodesToUpdate.size(); i != e; ++i) {
5787 MachineInstr *PHI = SDL->PHINodesToUpdate[i].first;
Chris Lattnerb2e806e2006-10-22 23:00:53 +00005788 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
5789 "This is not a machine PHI node that we are updating!");
5790 if (BB->isSuccessor(PHI->getParent())) {
Dan Gohman7c3234c2008-08-27 23:52:12 +00005791 PHI->addOperand(MachineOperand::CreateReg(SDL->PHINodesToUpdate[i].second,
Chris Lattner9ce2e9d2007-12-30 00:57:42 +00005792 false));
5793 PHI->addOperand(MachineOperand::CreateMBB(BB));
Chris Lattnerb2e806e2006-10-22 23:00:53 +00005794 }
5795 }
5796
Nate Begemanf15485a2006-03-27 01:32:24 +00005797 // If we generated any switch lowering information, build and codegen any
5798 // additional DAGs necessary.
Dan Gohman7c3234c2008-08-27 23:52:12 +00005799 for (unsigned i = 0, e = SDL->SwitchCases.size(); i != e; ++i) {
Nate Begemanf15485a2006-03-27 01:32:24 +00005800 // Set the current basic block to the mbb we wish to insert the code into
Dan Gohman7c3234c2008-08-27 23:52:12 +00005801 BB = SDL->SwitchCases[i].ThisBB;
5802 SDL->setCurrentBasicBlock(BB);
Chris Lattnerd5e93c02006-09-07 01:59:34 +00005803
Nate Begemanf15485a2006-03-27 01:32:24 +00005804 // Emit the code
Dan Gohman7c3234c2008-08-27 23:52:12 +00005805 SDL->visitSwitchCase(SDL->SwitchCases[i]);
5806 CurDAG->setRoot(SDL->getRoot());
Dan Gohmanf350b272008-08-23 02:25:05 +00005807 CodeGenAndEmitDAG();
Dan Gohman7c3234c2008-08-27 23:52:12 +00005808 SDL->clear();
Chris Lattnerd5e93c02006-09-07 01:59:34 +00005809
5810 // Handle any PHI nodes in successors of this chunk, as if we were coming
5811 // from the original BB before switch expansion. Note that PHI nodes can
5812 // occur multiple times in PHINodesToUpdate. We have to be very careful to
5813 // handle them the right number of times.
Dan Gohman7c3234c2008-08-27 23:52:12 +00005814 while ((BB = SDL->SwitchCases[i].TrueBB)) { // Handle LHS and RHS.
Chris Lattnerd5e93c02006-09-07 01:59:34 +00005815 for (MachineBasicBlock::iterator Phi = BB->begin();
5816 Phi != BB->end() && Phi->getOpcode() == TargetInstrInfo::PHI; ++Phi){
5817 // This value for this PHI node is recorded in PHINodesToUpdate, get it.
5818 for (unsigned pn = 0; ; ++pn) {
Dan Gohman7c3234c2008-08-27 23:52:12 +00005819 assert(pn != SDL->PHINodesToUpdate.size() &&
5820 "Didn't find PHI entry!");
5821 if (SDL->PHINodesToUpdate[pn].first == Phi) {
5822 Phi->addOperand(MachineOperand::CreateReg(SDL->PHINodesToUpdate[pn].
Chris Lattner9ce2e9d2007-12-30 00:57:42 +00005823 second, false));
Dan Gohman7c3234c2008-08-27 23:52:12 +00005824 Phi->addOperand(MachineOperand::CreateMBB(SDL->SwitchCases[i].ThisBB));
Chris Lattnerd5e93c02006-09-07 01:59:34 +00005825 break;
5826 }
5827 }
Nate Begemanf15485a2006-03-27 01:32:24 +00005828 }
Chris Lattnerd5e93c02006-09-07 01:59:34 +00005829
5830 // Don't process RHS if same block as LHS.
Dan Gohman7c3234c2008-08-27 23:52:12 +00005831 if (BB == SDL->SwitchCases[i].FalseBB)
5832 SDL->SwitchCases[i].FalseBB = 0;
Chris Lattnerd5e93c02006-09-07 01:59:34 +00005833
5834 // If we haven't handled the RHS, do so now. Otherwise, we're done.
Dan Gohman7c3234c2008-08-27 23:52:12 +00005835 SDL->SwitchCases[i].TrueBB = SDL->SwitchCases[i].FalseBB;
5836 SDL->SwitchCases[i].FalseBB = 0;
Nate Begemanf15485a2006-03-27 01:32:24 +00005837 }
Dan Gohman7c3234c2008-08-27 23:52:12 +00005838 assert(SDL->SwitchCases[i].TrueBB == 0 && SDL->SwitchCases[i].FalseBB == 0);
Chris Lattnera33ef482005-03-30 01:10:47 +00005839 }
Dan Gohman7c3234c2008-08-27 23:52:12 +00005840 SDL->SwitchCases.clear();
5841
5842 SDL->PHINodesToUpdate.clear();
Chris Lattner1c08c712005-01-07 07:47:53 +00005843}
Evan Chenga9c20912006-01-21 02:32:06 +00005844
Jim Laskey13ec7022006-08-01 14:21:23 +00005845
Dan Gohman5e843682008-07-14 18:19:29 +00005846/// Schedule - Pick a safe ordering for instructions for each
Evan Chenga9c20912006-01-21 02:32:06 +00005847/// target node in the graph.
Dan Gohman5e843682008-07-14 18:19:29 +00005848///
Dan Gohmanf350b272008-08-23 02:25:05 +00005849ScheduleDAG *SelectionDAGISel::Schedule() {
Jim Laskeyeb577ba2006-08-02 12:30:23 +00005850 RegisterScheduler::FunctionPassCtor Ctor = RegisterScheduler::getDefault();
Jim Laskey13ec7022006-08-01 14:21:23 +00005851
5852 if (!Ctor) {
Jim Laskeyeb577ba2006-08-02 12:30:23 +00005853 Ctor = ISHeuristic;
Jim Laskey9373beb2006-08-01 19:14:14 +00005854 RegisterScheduler::setDefault(Ctor);
Evan Cheng4ef10862006-01-23 07:01:07 +00005855 }
Jim Laskey13ec7022006-08-01 14:21:23 +00005856
Dan Gohmanf350b272008-08-23 02:25:05 +00005857 ScheduleDAG *Scheduler = Ctor(this, CurDAG, BB, Fast);
Dan Gohman5e843682008-07-14 18:19:29 +00005858 Scheduler->Run();
Dan Gohman3e1a7ae2007-08-28 20:32:58 +00005859
Dan Gohman5e843682008-07-14 18:19:29 +00005860 return Scheduler;
Evan Chenga9c20912006-01-21 02:32:06 +00005861}
Chris Lattner0e43f2b2006-02-24 02:13:54 +00005862
Chris Lattner03fc53c2006-03-06 00:22:00 +00005863
Jim Laskey9ff542f2006-08-01 18:29:48 +00005864HazardRecognizer *SelectionDAGISel::CreateTargetHazardRecognizer() {
5865 return new HazardRecognizer();
5866}
5867
Chris Lattner75548062006-10-11 03:58:02 +00005868//===----------------------------------------------------------------------===//
5869// Helper functions used by the generated instruction selector.
5870//===----------------------------------------------------------------------===//
5871// Calls to these methods are generated by tblgen.
5872
5873/// CheckAndMask - The isel is trying to match something like (and X, 255). If
5874/// the dag combiner simplified the 255, we still want to match. RHS is the
5875/// actual value in the DAG on the RHS of an AND, and DesiredMaskS is the value
5876/// specified in the .td file (e.g. 255).
Dan Gohman475871a2008-07-27 21:46:04 +00005877bool SelectionDAGISel::CheckAndMask(SDValue LHS, ConstantSDNode *RHS,
Dan Gohmandc9b3d02007-07-24 23:00:27 +00005878 int64_t DesiredMaskS) const {
Dan Gohman2e68b6f2008-02-25 21:11:39 +00005879 const APInt &ActualMask = RHS->getAPIntValue();
5880 const APInt &DesiredMask = APInt(LHS.getValueSizeInBits(), DesiredMaskS);
Chris Lattner75548062006-10-11 03:58:02 +00005881
5882 // If the actual mask exactly matches, success!
5883 if (ActualMask == DesiredMask)
5884 return true;
5885
5886 // If the actual AND mask is allowing unallowed bits, this doesn't match.
Dan Gohman2e68b6f2008-02-25 21:11:39 +00005887 if (ActualMask.intersects(~DesiredMask))
Chris Lattner75548062006-10-11 03:58:02 +00005888 return false;
5889
5890 // Otherwise, the DAG Combiner may have proven that the value coming in is
5891 // either already zero or is not demanded. Check for known zero input bits.
Dan Gohman2e68b6f2008-02-25 21:11:39 +00005892 APInt NeededMask = DesiredMask & ~ActualMask;
Dan Gohmanea859be2007-06-22 14:59:07 +00005893 if (CurDAG->MaskedValueIsZero(LHS, NeededMask))
Chris Lattner75548062006-10-11 03:58:02 +00005894 return true;
5895
5896 // TODO: check to see if missing bits are just not demanded.
5897
5898 // Otherwise, this pattern doesn't match.
5899 return false;
5900}
5901
5902/// CheckOrMask - The isel is trying to match something like (or X, 255). If
5903/// the dag combiner simplified the 255, we still want to match. RHS is the
5904/// actual value in the DAG on the RHS of an OR, and DesiredMaskS is the value
5905/// specified in the .td file (e.g. 255).
Dan Gohman475871a2008-07-27 21:46:04 +00005906bool SelectionDAGISel::CheckOrMask(SDValue LHS, ConstantSDNode *RHS,
Dan Gohman2e68b6f2008-02-25 21:11:39 +00005907 int64_t DesiredMaskS) const {
5908 const APInt &ActualMask = RHS->getAPIntValue();
5909 const APInt &DesiredMask = APInt(LHS.getValueSizeInBits(), DesiredMaskS);
Chris Lattner75548062006-10-11 03:58:02 +00005910
5911 // If the actual mask exactly matches, success!
5912 if (ActualMask == DesiredMask)
5913 return true;
5914
5915 // If the actual AND mask is allowing unallowed bits, this doesn't match.
Dan Gohman2e68b6f2008-02-25 21:11:39 +00005916 if (ActualMask.intersects(~DesiredMask))
Chris Lattner75548062006-10-11 03:58:02 +00005917 return false;
5918
5919 // Otherwise, the DAG Combiner may have proven that the value coming in is
5920 // either already zero or is not demanded. Check for known zero input bits.
Dan Gohman2e68b6f2008-02-25 21:11:39 +00005921 APInt NeededMask = DesiredMask & ~ActualMask;
Chris Lattner75548062006-10-11 03:58:02 +00005922
Dan Gohman2e68b6f2008-02-25 21:11:39 +00005923 APInt KnownZero, KnownOne;
Dan Gohmanea859be2007-06-22 14:59:07 +00005924 CurDAG->ComputeMaskedBits(LHS, NeededMask, KnownZero, KnownOne);
Chris Lattner75548062006-10-11 03:58:02 +00005925
5926 // If all the missing bits in the or are already known to be set, match!
5927 if ((NeededMask & KnownOne) == NeededMask)
5928 return true;
5929
5930 // TODO: check to see if missing bits are just not demanded.
5931
5932 // Otherwise, this pattern doesn't match.
5933 return false;
5934}
5935
Jim Laskey9ff542f2006-08-01 18:29:48 +00005936
Chris Lattner0e43f2b2006-02-24 02:13:54 +00005937/// SelectInlineAsmMemoryOperands - Calls to this are automatically generated
5938/// by tblgen. Others should not call it.
5939void SelectionDAGISel::
Dan Gohmanf350b272008-08-23 02:25:05 +00005940SelectInlineAsmMemoryOperands(std::vector<SDValue> &Ops) {
Dan Gohman475871a2008-07-27 21:46:04 +00005941 std::vector<SDValue> InOps;
Chris Lattner0e43f2b2006-02-24 02:13:54 +00005942 std::swap(InOps, Ops);
5943
5944 Ops.push_back(InOps[0]); // input chain.
5945 Ops.push_back(InOps[1]); // input asm string.
5946
Chris Lattner0e43f2b2006-02-24 02:13:54 +00005947 unsigned i = 2, e = InOps.size();
5948 if (InOps[e-1].getValueType() == MVT::Flag)
5949 --e; // Don't process a flag operand if it is here.
5950
5951 while (i != e) {
5952 unsigned Flags = cast<ConstantSDNode>(InOps[i])->getValue();
5953 if ((Flags & 7) != 4 /*MEM*/) {
5954 // Just skip over this operand, copying the operands verbatim.
5955 Ops.insert(Ops.end(), InOps.begin()+i, InOps.begin()+i+(Flags >> 3) + 1);
5956 i += (Flags >> 3) + 1;
5957 } else {
5958 assert((Flags >> 3) == 1 && "Memory operand with multiple values?");
5959 // Otherwise, this is a memory operand. Ask the target to select it.
Dan Gohman475871a2008-07-27 21:46:04 +00005960 std::vector<SDValue> SelOps;
Dan Gohmanf350b272008-08-23 02:25:05 +00005961 if (SelectInlineAsmMemoryOperand(InOps[i+1], 'm', SelOps)) {
Bill Wendling832171c2006-12-07 20:04:42 +00005962 cerr << "Could not match memory address. Inline asm failure!\n";
Chris Lattner0e43f2b2006-02-24 02:13:54 +00005963 exit(1);
5964 }
5965
5966 // Add this to the output node.
Dan Gohmanf350b272008-08-23 02:25:05 +00005967 MVT IntPtrTy = CurDAG->getTargetLoweringInfo().getPointerTy();
5968 Ops.push_back(CurDAG->getTargetConstant(4/*MEM*/ | (SelOps.size() << 3),
5969 IntPtrTy));
Chris Lattner0e43f2b2006-02-24 02:13:54 +00005970 Ops.insert(Ops.end(), SelOps.begin(), SelOps.end());
5971 i += 2;
5972 }
5973 }
5974
5975 // Add the flag input back if present.
5976 if (e != InOps.size())
5977 Ops.push_back(InOps.back());
5978}
Devang Patel794fd752007-05-01 21:15:47 +00005979
Devang Patel19974732007-05-03 01:11:54 +00005980char SelectionDAGISel::ID = 0;