blob: 188d93881912a08b86a195587ce2b3deaeb624d9 [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"
16#include "SimpleBBISel.h"
Anton Korobeynikov5502bf62007-04-04 21:14:49 +000017#include "llvm/ADT/BitVector.h"
Jim Laskeyc7c3f112006-10-16 20:52:31 +000018#include "llvm/Analysis/AliasAnalysis.h"
Anton Korobeynikov5502bf62007-04-04 21:14:49 +000019#include "llvm/Constants.h"
Chris Lattneradf6a962005-05-13 18:50:42 +000020#include "llvm/CallingConv.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000021#include "llvm/DerivedTypes.h"
22#include "llvm/Function.h"
Chris Lattner36ce6912005-11-29 06:21:05 +000023#include "llvm/GlobalVariable.h"
Chris Lattnerce7518c2006-01-26 22:24:51 +000024#include "llvm/InlineAsm.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000025#include "llvm/Instructions.h"
26#include "llvm/Intrinsics.h"
Jim Laskey43970fe2006-03-23 18:06:46 +000027#include "llvm/IntrinsicInst.h"
Reid Spencer5694b6e2007-04-09 06:17:21 +000028#include "llvm/ParameterAttributes.h"
Dan Gohman78eca172008-08-19 22:33:34 +000029#include "llvm/CodeGen/FastISel.h"
Gordon Henriksen5a29c9e2008-08-17 12:56:54 +000030#include "llvm/CodeGen/GCStrategy.h"
Gordon Henriksen5eca0752008-08-17 18:44:35 +000031#include "llvm/CodeGen/GCMetadata.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000032#include "llvm/CodeGen/MachineFunction.h"
33#include "llvm/CodeGen/MachineFrameInfo.h"
34#include "llvm/CodeGen/MachineInstrBuilder.h"
Chris Lattner84bc5422007-12-31 04:13:23 +000035#include "llvm/CodeGen/MachineJumpTableInfo.h"
36#include "llvm/CodeGen/MachineModuleInfo.h"
37#include "llvm/CodeGen/MachineRegisterInfo.h"
Evan Cheng381cb072008-08-08 07:27:28 +000038#include "llvm/CodeGen/ScheduleDAG.h"
Jim Laskeyeb577ba2006-08-02 12:30:23 +000039#include "llvm/CodeGen/SchedulerRegistry.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000040#include "llvm/CodeGen/SelectionDAG.h"
Dan Gohman6f0d0242008-02-10 18:45:23 +000041#include "llvm/Target/TargetRegisterInfo.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000042#include "llvm/Target/TargetData.h"
43#include "llvm/Target/TargetFrameInfo.h"
44#include "llvm/Target/TargetInstrInfo.h"
45#include "llvm/Target/TargetLowering.h"
46#include "llvm/Target/TargetMachine.h"
Vladimir Prus12472912006-05-23 13:43:15 +000047#include "llvm/Target/TargetOptions.h"
Chris Lattnera4f0b3a2006-08-27 12:54:02 +000048#include "llvm/Support/Compiler.h"
Evan Chengdb8d56b2008-06-30 20:45:06 +000049#include "llvm/Support/Debug.h"
50#include "llvm/Support/MathExtras.h"
51#include "llvm/Support/Timer.h"
Jeff Cohen7e881032006-02-24 02:52:40 +000052#include <algorithm>
Chris Lattner1c08c712005-01-07 07:47:53 +000053using namespace llvm;
54
Chris Lattneread0d882008-06-17 06:09:18 +000055static cl::opt<bool>
Chris Lattner70587ea2008-07-10 23:37:50 +000056EnableValueProp("enable-value-prop", cl::Hidden);
57static cl::opt<bool>
Duncan Sandsf00e74f2008-07-17 17:06:03 +000058EnableLegalizeTypes("enable-legalize-types", cl::Hidden);
Dan Gohman78eca172008-08-19 22:33:34 +000059static cl::opt<bool>
60EnableFastISel("fast-isel", cl::Hidden,
61 cl::desc("Enable the experimental \"fast\" instruction selector"));
Chris Lattneread0d882008-06-17 06:09:18 +000062
63
Chris Lattnerda8abb02005-09-01 18:44:10 +000064#ifndef NDEBUG
Chris Lattner7944d9d2005-01-12 03:41:21 +000065static cl::opt<bool>
Dan Gohman462dc7f2008-07-21 20:00:07 +000066ViewDAGCombine1("view-dag-combine1-dags", cl::Hidden,
67 cl::desc("Pop up a window to show dags before the first "
68 "dag combine pass"));
69static cl::opt<bool>
70ViewLegalizeTypesDAGs("view-legalize-types-dags", cl::Hidden,
71 cl::desc("Pop up a window to show dags before legalize types"));
72static cl::opt<bool>
73ViewLegalizeDAGs("view-legalize-dags", cl::Hidden,
74 cl::desc("Pop up a window to show dags before legalize"));
75static cl::opt<bool>
76ViewDAGCombine2("view-dag-combine2-dags", cl::Hidden,
77 cl::desc("Pop up a window to show dags before the second "
78 "dag combine pass"));
79static cl::opt<bool>
Evan Chenga9c20912006-01-21 02:32:06 +000080ViewISelDAGs("view-isel-dags", cl::Hidden,
81 cl::desc("Pop up a window to show isel dags as they are selected"));
82static cl::opt<bool>
83ViewSchedDAGs("view-sched-dags", cl::Hidden,
84 cl::desc("Pop up a window to show sched dags as they are processed"));
Dan Gohman3e1a7ae2007-08-28 20:32:58 +000085static cl::opt<bool>
86ViewSUnitDAGs("view-sunit-dags", cl::Hidden,
Chris Lattner5bab7852008-01-25 17:24:52 +000087 cl::desc("Pop up a window to show SUnit dags after they are processed"));
Chris Lattner7944d9d2005-01-12 03:41:21 +000088#else
Dan Gohman462dc7f2008-07-21 20:00:07 +000089static const bool ViewDAGCombine1 = false,
90 ViewLegalizeTypesDAGs = false, ViewLegalizeDAGs = false,
91 ViewDAGCombine2 = false,
92 ViewISelDAGs = false, ViewSchedDAGs = false,
93 ViewSUnitDAGs = false;
Chris Lattner7944d9d2005-01-12 03:41:21 +000094#endif
95
Jim Laskeyeb577ba2006-08-02 12:30:23 +000096//===---------------------------------------------------------------------===//
97///
98/// RegisterScheduler class - Track the registration of instruction schedulers.
99///
100//===---------------------------------------------------------------------===//
101MachinePassRegistry RegisterScheduler::Registry;
102
103//===---------------------------------------------------------------------===//
104///
105/// ISHeuristic command line option for instruction schedulers.
106///
107//===---------------------------------------------------------------------===//
Dan Gohman844731a2008-05-13 00:00:25 +0000108static cl::opt<RegisterScheduler::FunctionPassCtor, false,
109 RegisterPassParser<RegisterScheduler> >
110ISHeuristic("pre-RA-sched",
111 cl::init(&createDefaultScheduler),
112 cl::desc("Instruction schedulers available (before register"
113 " allocation):"));
Jim Laskey13ec7022006-08-01 14:21:23 +0000114
Dan Gohman844731a2008-05-13 00:00:25 +0000115static RegisterScheduler
116defaultListDAGScheduler("default", " Best scheduler for the target",
117 createDefaultScheduler);
Evan Cheng4ef10862006-01-23 07:01:07 +0000118
Evan Cheng5c807602008-02-26 02:33:44 +0000119namespace { struct SDISelAsmOperandInfo; }
Chris Lattnerbf996f12007-04-30 17:29:31 +0000120
Dan Gohman1d685a42008-06-07 02:02:36 +0000121/// ComputeLinearIndex - Given an LLVM IR aggregate type and a sequence
122/// insertvalue or extractvalue indices that identify a member, return
123/// the linearized index of the start of the member.
124///
125static unsigned ComputeLinearIndex(const TargetLowering &TLI, const Type *Ty,
126 const unsigned *Indices,
127 const unsigned *IndicesEnd,
128 unsigned CurIndex = 0) {
129 // Base case: We're done.
Dan Gohman8f36f6d2008-06-20 00:53:00 +0000130 if (Indices && Indices == IndicesEnd)
Dan Gohman1d685a42008-06-07 02:02:36 +0000131 return CurIndex;
132
Chris Lattnerf899fce2008-04-27 23:48:12 +0000133 // Given a struct type, recursively traverse the elements.
134 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
Dan Gohman8f36f6d2008-06-20 00:53:00 +0000135 for (StructType::element_iterator EB = STy->element_begin(),
136 EI = EB,
Dan Gohman1d685a42008-06-07 02:02:36 +0000137 EE = STy->element_end();
138 EI != EE; ++EI) {
Dan Gohman8f36f6d2008-06-20 00:53:00 +0000139 if (Indices && *Indices == unsigned(EI - EB))
140 return ComputeLinearIndex(TLI, *EI, Indices+1, IndicesEnd, CurIndex);
141 CurIndex = ComputeLinearIndex(TLI, *EI, 0, 0, CurIndex);
Dan Gohman1d685a42008-06-07 02:02:36 +0000142 }
143 }
144 // Given an array type, recursively traverse the elements.
145 else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
146 const Type *EltTy = ATy->getElementType();
147 for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i) {
Dan Gohman8f36f6d2008-06-20 00:53:00 +0000148 if (Indices && *Indices == i)
149 return ComputeLinearIndex(TLI, EltTy, Indices+1, IndicesEnd, CurIndex);
150 CurIndex = ComputeLinearIndex(TLI, EltTy, 0, 0, CurIndex);
Dan Gohman1d685a42008-06-07 02:02:36 +0000151 }
152 }
153 // We haven't found the type we're looking for, so keep searching.
Dan Gohman8f36f6d2008-06-20 00:53:00 +0000154 return CurIndex + 1;
Dan Gohman1d685a42008-06-07 02:02:36 +0000155}
156
157/// ComputeValueVTs - Given an LLVM IR type, compute a sequence of
158/// MVTs that represent all the individual underlying
159/// non-aggregate types that comprise it.
160///
161/// If Offsets is non-null, it points to a vector to be filled in
162/// with the in-memory offsets of each of the individual values.
163///
164static void ComputeValueVTs(const TargetLowering &TLI, const Type *Ty,
165 SmallVectorImpl<MVT> &ValueVTs,
166 SmallVectorImpl<uint64_t> *Offsets = 0,
167 uint64_t StartingOffset = 0) {
168 // Given a struct type, recursively traverse the elements.
169 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
170 const StructLayout *SL = TLI.getTargetData()->getStructLayout(STy);
171 for (StructType::element_iterator EB = STy->element_begin(),
172 EI = EB,
173 EE = STy->element_end();
174 EI != EE; ++EI)
175 ComputeValueVTs(TLI, *EI, ValueVTs, Offsets,
176 StartingOffset + SL->getElementOffset(EI - EB));
Chris Lattnerf899fce2008-04-27 23:48:12 +0000177 return;
Dan Gohman23ce5022008-04-25 18:27:55 +0000178 }
Chris Lattnerf899fce2008-04-27 23:48:12 +0000179 // Given an array type, recursively traverse the elements.
180 if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
181 const Type *EltTy = ATy->getElementType();
Dan Gohman1d685a42008-06-07 02:02:36 +0000182 uint64_t EltSize = TLI.getTargetData()->getABITypeSize(EltTy);
Chris Lattnerf899fce2008-04-27 23:48:12 +0000183 for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i)
Dan Gohman1d685a42008-06-07 02:02:36 +0000184 ComputeValueVTs(TLI, EltTy, ValueVTs, Offsets,
185 StartingOffset + i * EltSize);
Chris Lattnerf899fce2008-04-27 23:48:12 +0000186 return;
187 }
Duncan Sands83ec4b62008-06-06 12:08:01 +0000188 // Base case: we can get an MVT for this LLVM IR type.
Chris Lattnerf899fce2008-04-27 23:48:12 +0000189 ValueVTs.push_back(TLI.getValueType(Ty));
Dan Gohman1d685a42008-06-07 02:02:36 +0000190 if (Offsets)
191 Offsets->push_back(StartingOffset);
Chris Lattnerf899fce2008-04-27 23:48:12 +0000192}
Dan Gohman23ce5022008-04-25 18:27:55 +0000193
Chris Lattnerf899fce2008-04-27 23:48:12 +0000194namespace {
Dan Gohman0fe00902008-04-28 18:10:39 +0000195 /// RegsForValue - This struct represents the registers (physical or virtual)
196 /// that a particular set of values is assigned, and the type information about
197 /// the value. The most common situation is to represent one value at a time,
198 /// but struct or array values are handled element-wise as multiple values.
199 /// The splitting of aggregates is performed recursively, so that we never
200 /// have aggregate-typed registers. The values at this point do not necessarily
201 /// have legal types, so each value may require one or more registers of some
202 /// legal type.
203 ///
Chris Lattner95255282006-06-28 23:17:24 +0000204 struct VISIBILITY_HIDDEN RegsForValue {
Dan Gohman23ce5022008-04-25 18:27:55 +0000205 /// TLI - The TargetLowering object.
Dan Gohman0fe00902008-04-28 18:10:39 +0000206 ///
Dan Gohman23ce5022008-04-25 18:27:55 +0000207 const TargetLowering *TLI;
208
Dan Gohman0fe00902008-04-28 18:10:39 +0000209 /// ValueVTs - The value types of the values, which may not be legal, and
210 /// may need be promoted or synthesized from one or more registers.
211 ///
Duncan Sands83ec4b62008-06-06 12:08:01 +0000212 SmallVector<MVT, 4> ValueVTs;
Chris Lattner864635a2006-02-22 22:37:12 +0000213
Dan Gohman0fe00902008-04-28 18:10:39 +0000214 /// RegVTs - The value types of the registers. This is the same size as
215 /// ValueVTs and it records, for each value, what the type of the assigned
216 /// register or registers are. (Individual values are never synthesized
217 /// from more than one type of register.)
218 ///
219 /// With virtual registers, the contents of RegVTs is redundant with TLI's
220 /// getRegisterType member function, however when with physical registers
221 /// it is necessary to have a separate record of the types.
Chris Lattner864635a2006-02-22 22:37:12 +0000222 ///
Duncan Sands83ec4b62008-06-06 12:08:01 +0000223 SmallVector<MVT, 4> RegVTs;
Chris Lattner864635a2006-02-22 22:37:12 +0000224
Dan Gohman0fe00902008-04-28 18:10:39 +0000225 /// Regs - This list holds the registers assigned to the values.
226 /// Each legal or promoted value requires one register, and each
227 /// expanded value requires multiple registers.
228 ///
229 SmallVector<unsigned, 4> Regs;
Chris Lattner864635a2006-02-22 22:37:12 +0000230
Dan Gohman23ce5022008-04-25 18:27:55 +0000231 RegsForValue() : TLI(0) {}
Chris Lattner864635a2006-02-22 22:37:12 +0000232
Dan Gohman23ce5022008-04-25 18:27:55 +0000233 RegsForValue(const TargetLowering &tli,
Chris Lattnerb606dba2008-04-28 06:44:42 +0000234 const SmallVector<unsigned, 4> &regs,
Duncan Sands83ec4b62008-06-06 12:08:01 +0000235 MVT regvt, MVT valuevt)
Dan Gohman0fe00902008-04-28 18:10:39 +0000236 : TLI(&tli), ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs) {}
Dan Gohman23ce5022008-04-25 18:27:55 +0000237 RegsForValue(const TargetLowering &tli,
Chris Lattnerb606dba2008-04-28 06:44:42 +0000238 const SmallVector<unsigned, 4> &regs,
Duncan Sands83ec4b62008-06-06 12:08:01 +0000239 const SmallVector<MVT, 4> &regvts,
240 const SmallVector<MVT, 4> &valuevts)
Dan Gohman0fe00902008-04-28 18:10:39 +0000241 : TLI(&tli), ValueVTs(valuevts), RegVTs(regvts), Regs(regs) {}
Dan Gohman23ce5022008-04-25 18:27:55 +0000242 RegsForValue(const TargetLowering &tli,
243 unsigned Reg, const Type *Ty) : TLI(&tli) {
244 ComputeValueVTs(tli, Ty, ValueVTs);
245
Dan Gohmanb20d4f82008-04-28 17:42:03 +0000246 for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
Duncan Sands83ec4b62008-06-06 12:08:01 +0000247 MVT ValueVT = ValueVTs[Value];
Dan Gohman23ce5022008-04-25 18:27:55 +0000248 unsigned NumRegs = TLI->getNumRegisters(ValueVT);
Duncan Sands83ec4b62008-06-06 12:08:01 +0000249 MVT RegisterVT = TLI->getRegisterType(ValueVT);
Dan Gohman23ce5022008-04-25 18:27:55 +0000250 for (unsigned i = 0; i != NumRegs; ++i)
251 Regs.push_back(Reg + i);
252 RegVTs.push_back(RegisterVT);
253 Reg += NumRegs;
254 }
Chris Lattner864635a2006-02-22 22:37:12 +0000255 }
256
Chris Lattner41f62592008-04-29 04:29:54 +0000257 /// append - Add the specified values to this one.
258 void append(const RegsForValue &RHS) {
259 TLI = RHS.TLI;
260 ValueVTs.append(RHS.ValueVTs.begin(), RHS.ValueVTs.end());
261 RegVTs.append(RHS.RegVTs.begin(), RHS.RegVTs.end());
262 Regs.append(RHS.Regs.begin(), RHS.Regs.end());
263 }
264
265
Chris Lattner864635a2006-02-22 22:37:12 +0000266 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
Dan Gohman23ce5022008-04-25 18:27:55 +0000267 /// this value and returns the result as a ValueVTs value. This uses
Chris Lattner864635a2006-02-22 22:37:12 +0000268 /// Chain/Flag as the input and updates them for the output Chain/Flag.
Dan Gohmanb6f5b002007-06-28 23:29:44 +0000269 /// If the Flag pointer is NULL, no flag is used.
Dan Gohman475871a2008-07-27 21:46:04 +0000270 SDValue getCopyFromRegs(SelectionDAG &DAG,
271 SDValue &Chain, SDValue *Flag) const;
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +0000272
273 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
274 /// specified value into the registers specified by this object. This uses
275 /// Chain/Flag as the input and updates them for the output Chain/Flag.
Dan Gohmanb6f5b002007-06-28 23:29:44 +0000276 /// If the Flag pointer is NULL, no flag is used.
Dan Gohman475871a2008-07-27 21:46:04 +0000277 void getCopyToRegs(SDValue Val, SelectionDAG &DAG,
278 SDValue &Chain, SDValue *Flag) const;
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +0000279
280 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
281 /// operand list. This adds the code marker and includes the number of
282 /// values added into it.
283 void AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
Dan Gohman475871a2008-07-27 21:46:04 +0000284 std::vector<SDValue> &Ops) const;
Chris Lattner864635a2006-02-22 22:37:12 +0000285 };
286}
Evan Cheng4ef10862006-01-23 07:01:07 +0000287
Chris Lattner1c08c712005-01-07 07:47:53 +0000288namespace llvm {
289 //===--------------------------------------------------------------------===//
Jim Laskey9373beb2006-08-01 19:14:14 +0000290 /// createDefaultScheduler - This creates an instruction scheduler appropriate
291 /// for the target.
292 ScheduleDAG* createDefaultScheduler(SelectionDAGISel *IS,
293 SelectionDAG *DAG,
Evan Cheng4576f6d2008-07-01 18:05:03 +0000294 MachineBasicBlock *BB,
295 bool Fast) {
Jim Laskey9373beb2006-08-01 19:14:14 +0000296 TargetLowering &TLI = IS->getTargetLowering();
297
298 if (TLI.getSchedulingPreference() == TargetLowering::SchedulingForLatency) {
Evan Cheng4576f6d2008-07-01 18:05:03 +0000299 return createTDListDAGScheduler(IS, DAG, BB, Fast);
Jim Laskey9373beb2006-08-01 19:14:14 +0000300 } else {
301 assert(TLI.getSchedulingPreference() ==
302 TargetLowering::SchedulingForRegPressure && "Unknown sched type!");
Evan Cheng4576f6d2008-07-01 18:05:03 +0000303 return createBURRListDAGScheduler(IS, DAG, BB, Fast);
Jim Laskey9373beb2006-08-01 19:14:14 +0000304 }
305 }
306
307
308 //===--------------------------------------------------------------------===//
Chris Lattner1c08c712005-01-07 07:47:53 +0000309 /// FunctionLoweringInfo - This contains information that is global to a
310 /// function that is used when lowering a region of the function.
Chris Lattnerf26bc8e2005-01-08 19:52:31 +0000311 class FunctionLoweringInfo {
312 public:
Chris Lattner1c08c712005-01-07 07:47:53 +0000313 TargetLowering &TLI;
314 Function &Fn;
315 MachineFunction &MF;
Chris Lattner84bc5422007-12-31 04:13:23 +0000316 MachineRegisterInfo &RegInfo;
Chris Lattner1c08c712005-01-07 07:47:53 +0000317
318 FunctionLoweringInfo(TargetLowering &TLI, Function &Fn,MachineFunction &MF);
319
320 /// MBBMap - A mapping from LLVM basic blocks to their machine code entry.
321 std::map<const BasicBlock*, MachineBasicBlock *> MBBMap;
322
323 /// ValueMap - Since we emit code for the function a basic block at a time,
324 /// we must remember which virtual registers hold the values for
325 /// cross-basic-block values.
Chris Lattner9f24ad72007-02-04 01:35:11 +0000326 DenseMap<const Value*, unsigned> ValueMap;
Chris Lattner1c08c712005-01-07 07:47:53 +0000327
328 /// StaticAllocaMap - Keep track of frame indices for fixed sized allocas in
329 /// the entry block. This allows the allocas to be efficiently referenced
330 /// anywhere in the function.
331 std::map<const AllocaInst*, int> StaticAllocaMap;
332
Duncan Sandsf4070822007-06-15 19:04:19 +0000333#ifndef NDEBUG
334 SmallSet<Instruction*, 8> CatchInfoLost;
335 SmallSet<Instruction*, 8> CatchInfoFound;
336#endif
337
Duncan Sands83ec4b62008-06-06 12:08:01 +0000338 unsigned MakeReg(MVT VT) {
Chris Lattner84bc5422007-12-31 04:13:23 +0000339 return RegInfo.createVirtualRegister(TLI.getRegClassFor(VT));
Chris Lattner1c08c712005-01-07 07:47:53 +0000340 }
Chris Lattner571e4342006-10-27 21:36:01 +0000341
342 /// isExportedInst - Return true if the specified value is an instruction
343 /// exported from its block.
344 bool isExportedInst(const Value *V) {
345 return ValueMap.count(V);
346 }
Misha Brukmanedf128a2005-04-21 22:36:52 +0000347
Chris Lattner3c384492006-03-16 19:51:18 +0000348 unsigned CreateRegForValue(const Value *V);
349
Chris Lattner1c08c712005-01-07 07:47:53 +0000350 unsigned InitializeRegForValue(const Value *V) {
351 unsigned &R = ValueMap[V];
352 assert(R == 0 && "Already initialized this value register!");
353 return R = CreateRegForValue(V);
354 }
Chris Lattneread0d882008-06-17 06:09:18 +0000355
356 struct LiveOutInfo {
357 unsigned NumSignBits;
358 APInt KnownOne, KnownZero;
359 LiveOutInfo() : NumSignBits(0) {}
360 };
361
362 /// LiveOutRegInfo - Information about live out vregs, indexed by their
363 /// register number offset by 'FirstVirtualRegister'.
364 std::vector<LiveOutInfo> LiveOutRegInfo;
Chris Lattner1c08c712005-01-07 07:47:53 +0000365 };
366}
367
Duncan Sandscf26d7c2007-07-04 20:52:51 +0000368/// isSelector - Return true if this instruction is a call to the
369/// eh.selector intrinsic.
370static bool isSelector(Instruction *I) {
Duncan Sandsf4070822007-06-15 19:04:19 +0000371 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
Anton Korobeynikov8806c7b2007-09-07 11:39:35 +0000372 return (II->getIntrinsicID() == Intrinsic::eh_selector_i32 ||
373 II->getIntrinsicID() == Intrinsic::eh_selector_i64);
Duncan Sandsf4070822007-06-15 19:04:19 +0000374 return false;
375}
376
Chris Lattner1c08c712005-01-07 07:47:53 +0000377/// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by
Nate Begemanf15485a2006-03-27 01:32:24 +0000378/// PHI nodes or outside of the basic block that defines it, or used by a
Andrew Lenharthab0b9492008-02-21 06:45:13 +0000379/// switch or atomic instruction, which may expand to multiple basic blocks.
Chris Lattner1c08c712005-01-07 07:47:53 +0000380static bool isUsedOutsideOfDefiningBlock(Instruction *I) {
381 if (isa<PHINode>(I)) return true;
382 BasicBlock *BB = I->getParent();
383 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; ++UI)
Nate Begemanf15485a2006-03-27 01:32:24 +0000384 if (cast<Instruction>(*UI)->getParent() != BB || isa<PHINode>(*UI) ||
Chris Lattner571e4342006-10-27 21:36:01 +0000385 // FIXME: Remove switchinst special case.
Nate Begemanf15485a2006-03-27 01:32:24 +0000386 isa<SwitchInst>(*UI))
Chris Lattner1c08c712005-01-07 07:47:53 +0000387 return true;
388 return false;
389}
390
Chris Lattnerbf209482005-10-30 19:42:35 +0000391/// isOnlyUsedInEntryBlock - If the specified argument is only used in the
Nate Begemanf15485a2006-03-27 01:32:24 +0000392/// entry block, return true. This includes arguments used by switches, since
393/// the switch may expand into multiple basic blocks.
Chris Lattnerbf209482005-10-30 19:42:35 +0000394static bool isOnlyUsedInEntryBlock(Argument *A) {
395 BasicBlock *Entry = A->getParent()->begin();
396 for (Value::use_iterator UI = A->use_begin(), E = A->use_end(); UI != E; ++UI)
Nate Begemanf15485a2006-03-27 01:32:24 +0000397 if (cast<Instruction>(*UI)->getParent() != Entry || isa<SwitchInst>(*UI))
Chris Lattnerbf209482005-10-30 19:42:35 +0000398 return false; // Use not in entry block.
399 return true;
400}
401
Chris Lattner1c08c712005-01-07 07:47:53 +0000402FunctionLoweringInfo::FunctionLoweringInfo(TargetLowering &tli,
Misha Brukmanedf128a2005-04-21 22:36:52 +0000403 Function &fn, MachineFunction &mf)
Chris Lattner84bc5422007-12-31 04:13:23 +0000404 : TLI(tli), Fn(fn), MF(mf), RegInfo(MF.getRegInfo()) {
Chris Lattner1c08c712005-01-07 07:47:53 +0000405
Chris Lattnerbf209482005-10-30 19:42:35 +0000406 // Create a vreg for each argument register that is not dead and is used
407 // outside of the entry block for the function.
408 for (Function::arg_iterator AI = Fn.arg_begin(), E = Fn.arg_end();
409 AI != E; ++AI)
410 if (!isOnlyUsedInEntryBlock(AI))
411 InitializeRegForValue(AI);
412
Chris Lattner1c08c712005-01-07 07:47:53 +0000413 // Initialize the mapping of values to registers. This is only set up for
414 // instruction values that are used outside of the block that defines
415 // them.
Jeff Cohen2aeaf4e2005-10-01 03:57:14 +0000416 Function::iterator BB = Fn.begin(), EB = Fn.end();
Chris Lattner1c08c712005-01-07 07:47:53 +0000417 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
418 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
Reid Spencerb83eb642006-10-20 07:07:24 +0000419 if (ConstantInt *CUI = dyn_cast<ConstantInt>(AI->getArraySize())) {
Chris Lattner1c08c712005-01-07 07:47:53 +0000420 const Type *Ty = AI->getAllocatedType();
Duncan Sands514ab342007-11-01 20:53:16 +0000421 uint64_t TySize = TLI.getTargetData()->getABITypeSize(Ty);
Nate Begemanae232e72005-11-06 09:00:38 +0000422 unsigned Align =
Chris Lattnerd2b7cec2007-02-14 05:52:17 +0000423 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
Nate Begemanae232e72005-11-06 09:00:38 +0000424 AI->getAlignment());
Chris Lattnera8217e32005-05-13 23:14:17 +0000425
Reid Spencerb83eb642006-10-20 07:07:24 +0000426 TySize *= CUI->getZExtValue(); // Get total allocated size.
Chris Lattnerd222f6a2005-10-18 22:14:06 +0000427 if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
Chris Lattner1c08c712005-01-07 07:47:53 +0000428 StaticAllocaMap[AI] =
Chris Lattner6266c182007-04-25 04:08:28 +0000429 MF.getFrameInfo()->CreateStackObject(TySize, Align);
Chris Lattner1c08c712005-01-07 07:47:53 +0000430 }
431
Jeff Cohen2aeaf4e2005-10-01 03:57:14 +0000432 for (; BB != EB; ++BB)
433 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
Chris Lattner1c08c712005-01-07 07:47:53 +0000434 if (!I->use_empty() && isUsedOutsideOfDefiningBlock(I))
435 if (!isa<AllocaInst>(I) ||
436 !StaticAllocaMap.count(cast<AllocaInst>(I)))
437 InitializeRegForValue(I);
438
439 // Create an initial MachineBasicBlock for each LLVM BasicBlock in F. This
440 // also creates the initial PHI MachineInstrs, though none of the input
441 // operands are populated.
Jeff Cohen2aeaf4e2005-10-01 03:57:14 +0000442 for (BB = Fn.begin(), EB = Fn.end(); BB != EB; ++BB) {
Dan Gohman0e5f1302008-07-07 23:02:41 +0000443 MachineBasicBlock *MBB = mf.CreateMachineBasicBlock(BB);
Chris Lattner1c08c712005-01-07 07:47:53 +0000444 MBBMap[BB] = MBB;
Dan Gohman0e5f1302008-07-07 23:02:41 +0000445 MF.push_back(MBB);
Chris Lattner1c08c712005-01-07 07:47:53 +0000446
447 // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
448 // appropriate.
449 PHINode *PN;
Chris Lattner8c494ab2006-10-27 23:50:33 +0000450 for (BasicBlock::iterator I = BB->begin();(PN = dyn_cast<PHINode>(I)); ++I){
451 if (PN->use_empty()) continue;
452
Chris Lattner8c494ab2006-10-27 23:50:33 +0000453 unsigned PHIReg = ValueMap[PN];
454 assert(PHIReg && "PHI node does not have an assigned virtual register!");
Dan Gohman6f498b02008-08-04 23:42:46 +0000455
456 SmallVector<MVT, 4> ValueVTs;
457 ComputeValueVTs(TLI, PN->getType(), ValueVTs);
458 for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
459 MVT VT = ValueVTs[vti];
460 unsigned NumRegisters = TLI.getNumRegisters(VT);
461 const TargetInstrInfo *TII = TLI.getTargetMachine().getInstrInfo();
462 for (unsigned i = 0; i != NumRegisters; ++i)
463 BuildMI(MBB, TII->get(TargetInstrInfo::PHI), PHIReg+i);
464 PHIReg += NumRegisters;
465 }
Chris Lattner8c494ab2006-10-27 23:50:33 +0000466 }
Chris Lattner1c08c712005-01-07 07:47:53 +0000467 }
468}
469
Chris Lattner3c384492006-03-16 19:51:18 +0000470/// CreateRegForValue - Allocate the appropriate number of virtual registers of
471/// the correctly promoted or expanded types. Assign these registers
472/// consecutive vreg numbers and return the first assigned number.
Dan Gohman10a6b7a2008-04-28 18:19:43 +0000473///
474/// In the case that the given value has struct or array type, this function
475/// will assign registers for each member or element.
476///
Chris Lattner3c384492006-03-16 19:51:18 +0000477unsigned FunctionLoweringInfo::CreateRegForValue(const Value *V) {
Duncan Sands83ec4b62008-06-06 12:08:01 +0000478 SmallVector<MVT, 4> ValueVTs;
Chris Lattnerb606dba2008-04-28 06:44:42 +0000479 ComputeValueVTs(TLI, V->getType(), ValueVTs);
Bill Wendling95b39552007-04-24 21:13:23 +0000480
Dan Gohman23ce5022008-04-25 18:27:55 +0000481 unsigned FirstReg = 0;
Dan Gohmanb20d4f82008-04-28 17:42:03 +0000482 for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
Duncan Sands83ec4b62008-06-06 12:08:01 +0000483 MVT ValueVT = ValueVTs[Value];
484 MVT RegisterVT = TLI.getRegisterType(ValueVT);
Dan Gohman8c8c5fc2007-06-27 14:34:07 +0000485
Chris Lattnerb606dba2008-04-28 06:44:42 +0000486 unsigned NumRegs = TLI.getNumRegisters(ValueVT);
Dan Gohman23ce5022008-04-25 18:27:55 +0000487 for (unsigned i = 0; i != NumRegs; ++i) {
488 unsigned R = MakeReg(RegisterVT);
489 if (!FirstReg) FirstReg = R;
490 }
491 }
492 return FirstReg;
Chris Lattner3c384492006-03-16 19:51:18 +0000493}
Chris Lattner1c08c712005-01-07 07:47:53 +0000494
495//===----------------------------------------------------------------------===//
496/// SelectionDAGLowering - This is the common target-independent lowering
497/// implementation that is parameterized by a TargetLowering object.
498/// Also, targets can overload any lowering method.
499///
500namespace llvm {
501class SelectionDAGLowering {
502 MachineBasicBlock *CurMBB;
503
Dan Gohman475871a2008-07-27 21:46:04 +0000504 DenseMap<const Value*, SDValue> NodeMap;
Chris Lattner1c08c712005-01-07 07:47:53 +0000505
Chris Lattnerd3948112005-01-17 22:19:26 +0000506 /// PendingLoads - Loads are not emitted to the program immediately. We bunch
507 /// them up and then emit token factor nodes when possible. This allows us to
508 /// get simple disambiguation between loads without worrying about alias
509 /// analysis.
Dan Gohman475871a2008-07-27 21:46:04 +0000510 SmallVector<SDValue, 8> PendingLoads;
Chris Lattnerd3948112005-01-17 22:19:26 +0000511
Dan Gohman86e1ebf2008-03-27 19:56:19 +0000512 /// PendingExports - CopyToReg nodes that copy values to virtual registers
513 /// for export to other blocks need to be emitted before any terminator
514 /// instruction, but they have no other ordering requirements. We bunch them
515 /// up and the emit a single tokenfactor for them just before terminator
516 /// instructions.
Dan Gohman475871a2008-07-27 21:46:04 +0000517 std::vector<SDValue> PendingExports;
Dan Gohman86e1ebf2008-03-27 19:56:19 +0000518
Anton Korobeynikov5502bf62007-04-04 21:14:49 +0000519 /// Case - A struct to record the Value for a switch case, and the
520 /// case's target basic block.
521 struct Case {
522 Constant* Low;
523 Constant* High;
524 MachineBasicBlock* BB;
525
526 Case() : Low(0), High(0), BB(0) { }
527 Case(Constant* low, Constant* high, MachineBasicBlock* bb) :
528 Low(low), High(high), BB(bb) { }
529 uint64_t size() const {
530 uint64_t rHigh = cast<ConstantInt>(High)->getSExtValue();
531 uint64_t rLow = cast<ConstantInt>(Low)->getSExtValue();
532 return (rHigh - rLow + 1ULL);
533 }
534 };
535
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000536 struct CaseBits {
537 uint64_t Mask;
538 MachineBasicBlock* BB;
539 unsigned Bits;
540
541 CaseBits(uint64_t mask, MachineBasicBlock* bb, unsigned bits):
542 Mask(mask), BB(bb), Bits(bits) { }
543 };
544
Anton Korobeynikov5502bf62007-04-04 21:14:49 +0000545 typedef std::vector<Case> CaseVector;
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000546 typedef std::vector<CaseBits> CaseBitsVector;
Anton Korobeynikov5502bf62007-04-04 21:14:49 +0000547 typedef CaseVector::iterator CaseItr;
548 typedef std::pair<CaseItr, CaseItr> CaseRange;
Nate Begemanf15485a2006-03-27 01:32:24 +0000549
550 /// CaseRec - A struct with ctor used in lowering switches to a binary tree
551 /// of conditional branches.
552 struct CaseRec {
553 CaseRec(MachineBasicBlock *bb, Constant *lt, Constant *ge, CaseRange r) :
554 CaseBB(bb), LT(lt), GE(ge), Range(r) {}
555
556 /// CaseBB - The MBB in which to emit the compare and branch
557 MachineBasicBlock *CaseBB;
558 /// LT, GE - If nonzero, we know the current case value must be less-than or
559 /// greater-than-or-equal-to these Constants.
560 Constant *LT;
561 Constant *GE;
562 /// Range - A pair of iterators representing the range of case values to be
563 /// processed at this point in the binary search tree.
564 CaseRange Range;
565 };
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +0000566
567 typedef std::vector<CaseRec> CaseRecVector;
Anton Korobeynikov5502bf62007-04-04 21:14:49 +0000568
569 /// The comparison function for sorting the switch case values in the vector.
570 /// WARNING: Case ranges should be disjoint!
Nate Begemanf15485a2006-03-27 01:32:24 +0000571 struct CaseCmp {
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000572 bool operator () (const Case& C1, const Case& C2) {
Anton Korobeynikov5502bf62007-04-04 21:14:49 +0000573 assert(isa<ConstantInt>(C1.Low) && isa<ConstantInt>(C2.High));
574 const ConstantInt* CI1 = cast<const ConstantInt>(C1.Low);
575 const ConstantInt* CI2 = cast<const ConstantInt>(C2.High);
576 return CI1->getValue().slt(CI2->getValue());
Nate Begemanf15485a2006-03-27 01:32:24 +0000577 }
578 };
Anton Korobeynikov5502bf62007-04-04 21:14:49 +0000579
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000580 struct CaseBitsCmp {
581 bool operator () (const CaseBits& C1, const CaseBits& C2) {
582 return C1.Bits > C2.Bits;
583 }
584 };
585
Anton Korobeynikov5502bf62007-04-04 21:14:49 +0000586 unsigned Clusterify(CaseVector& Cases, const SwitchInst &SI);
Nate Begemanf15485a2006-03-27 01:32:24 +0000587
Chris Lattner1c08c712005-01-07 07:47:53 +0000588public:
589 // TLI - This is information that describes the available target features we
590 // need for lowering. This indicates when operations are unavailable,
591 // implemented with a libcall, etc.
592 TargetLowering &TLI;
593 SelectionDAG &DAG;
Owen Andersona69571c2006-05-03 01:29:57 +0000594 const TargetData *TD;
Dan Gohman5f43f922007-08-27 16:26:13 +0000595 AliasAnalysis &AA;
Chris Lattner1c08c712005-01-07 07:47:53 +0000596
Nate Begemanf15485a2006-03-27 01:32:24 +0000597 /// SwitchCases - Vector of CaseBlock structures used to communicate
598 /// SwitchInst code generation information.
599 std::vector<SelectionDAGISel::CaseBlock> SwitchCases;
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +0000600 /// JTCases - Vector of JumpTable structures used to communicate
601 /// SwitchInst code generation information.
602 std::vector<SelectionDAGISel::JumpTableBlock> JTCases;
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000603 std::vector<SelectionDAGISel::BitTestBlock> BitTestCases;
Nate Begemanf15485a2006-03-27 01:32:24 +0000604
Chris Lattner1c08c712005-01-07 07:47:53 +0000605 /// FuncInfo - Information about the function as a whole.
606 ///
607 FunctionLoweringInfo &FuncInfo;
Gordon Henriksence224772008-01-07 01:30:38 +0000608
Gordon Henriksen5eca0752008-08-17 18:44:35 +0000609 /// GFI - Garbage collection metadata for the function.
610 GCFunctionInfo *GFI;
Chris Lattner1c08c712005-01-07 07:47:53 +0000611
612 SelectionDAGLowering(SelectionDAG &dag, TargetLowering &tli,
Dan Gohman5f43f922007-08-27 16:26:13 +0000613 AliasAnalysis &aa,
Gordon Henriksence224772008-01-07 01:30:38 +0000614 FunctionLoweringInfo &funcinfo,
Gordon Henriksen5eca0752008-08-17 18:44:35 +0000615 GCFunctionInfo *gfi)
Dan Gohman5f43f922007-08-27 16:26:13 +0000616 : TLI(tli), DAG(dag), TD(DAG.getTarget().getTargetData()), AA(aa),
Gordon Henriksen5eca0752008-08-17 18:44:35 +0000617 FuncInfo(funcinfo), GFI(gfi) {
Chris Lattner1c08c712005-01-07 07:47:53 +0000618 }
619
Dan Gohman86e1ebf2008-03-27 19:56:19 +0000620 /// getRoot - Return the current virtual root of the Selection DAG,
621 /// flushing any PendingLoad items. This must be done before emitting
622 /// a store or any other node that may need to be ordered after any
623 /// prior load instructions.
Chris Lattnera651cf62005-01-17 19:43:36 +0000624 ///
Dan Gohman475871a2008-07-27 21:46:04 +0000625 SDValue getRoot() {
Chris Lattnerd3948112005-01-17 22:19:26 +0000626 if (PendingLoads.empty())
627 return DAG.getRoot();
Misha Brukmanedf128a2005-04-21 22:36:52 +0000628
Chris Lattnerd3948112005-01-17 22:19:26 +0000629 if (PendingLoads.size() == 1) {
Dan Gohman475871a2008-07-27 21:46:04 +0000630 SDValue Root = PendingLoads[0];
Chris Lattnerd3948112005-01-17 22:19:26 +0000631 DAG.setRoot(Root);
632 PendingLoads.clear();
633 return Root;
634 }
635
636 // Otherwise, we have to make a token factor node.
Dan Gohman475871a2008-07-27 21:46:04 +0000637 SDValue Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
Chris Lattnerbd564bf2006-08-08 02:23:42 +0000638 &PendingLoads[0], PendingLoads.size());
Chris Lattnerd3948112005-01-17 22:19:26 +0000639 PendingLoads.clear();
640 DAG.setRoot(Root);
641 return Root;
Chris Lattnera651cf62005-01-17 19:43:36 +0000642 }
643
Dan Gohman86e1ebf2008-03-27 19:56:19 +0000644 /// getControlRoot - Similar to getRoot, but instead of flushing all the
645 /// PendingLoad items, flush all the PendingExports items. It is necessary
646 /// to do this before emitting a terminator instruction.
647 ///
Dan Gohman475871a2008-07-27 21:46:04 +0000648 SDValue getControlRoot() {
649 SDValue Root = DAG.getRoot();
Dan Gohman86e1ebf2008-03-27 19:56:19 +0000650
651 if (PendingExports.empty())
652 return Root;
653
654 // Turn all of the CopyToReg chains into one factored node.
655 if (Root.getOpcode() != ISD::EntryToken) {
656 unsigned i = 0, e = PendingExports.size();
657 for (; i != e; ++i) {
658 assert(PendingExports[i].Val->getNumOperands() > 1);
659 if (PendingExports[i].Val->getOperand(0) == Root)
660 break; // Don't add the root if we already indirectly depend on it.
661 }
662
663 if (i == e)
664 PendingExports.push_back(Root);
665 }
666
667 Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
668 &PendingExports[0],
669 PendingExports.size());
670 PendingExports.clear();
671 DAG.setRoot(Root);
672 return Root;
673 }
674
675 void CopyValueToVirtualRegister(Value *V, unsigned Reg);
Chris Lattner571e4342006-10-27 21:36:01 +0000676
Chris Lattner1c08c712005-01-07 07:47:53 +0000677 void visit(Instruction &I) { visit(I.getOpcode(), I); }
678
679 void visit(unsigned Opcode, User &I) {
Chris Lattner1e7aa5c2006-11-10 04:41:34 +0000680 // Note: this doesn't use InstVisitor, because it has to work with
681 // ConstantExpr's in addition to instructions.
Chris Lattner1c08c712005-01-07 07:47:53 +0000682 switch (Opcode) {
683 default: assert(0 && "Unknown instruction type encountered!");
684 abort();
685 // Build the switch statement using the Instruction.def file.
686#define HANDLE_INST(NUM, OPCODE, CLASS) \
687 case Instruction::OPCODE:return visit##OPCODE((CLASS&)I);
688#include "llvm/Instruction.def"
689 }
690 }
691
692 void setCurrentBasicBlock(MachineBasicBlock *MBB) { CurMBB = MBB; }
693
Dan Gohman475871a2008-07-27 21:46:04 +0000694 SDValue getValue(const Value *V);
Chris Lattner1c08c712005-01-07 07:47:53 +0000695
Dan Gohman475871a2008-07-27 21:46:04 +0000696 void setValue(const Value *V, SDValue NewN) {
697 SDValue &N = NodeMap[V];
Chris Lattner1c08c712005-01-07 07:47:53 +0000698 assert(N.Val == 0 && "Already set a value for this node!");
Chris Lattner0da331f2007-02-04 01:31:47 +0000699 N = NewN;
Chris Lattner1c08c712005-01-07 07:47:53 +0000700 }
Chris Lattner4e4b5762006-02-01 18:59:47 +0000701
Evan Cheng5c807602008-02-26 02:33:44 +0000702 void GetRegistersForValue(SDISelAsmOperandInfo &OpInfo, bool HasEarlyClobber,
Chris Lattnere7cf56a2007-04-30 21:11:17 +0000703 std::set<unsigned> &OutputRegs,
704 std::set<unsigned> &InputRegs);
Nate Begemanf15485a2006-03-27 01:32:24 +0000705
Chris Lattner571e4342006-10-27 21:36:01 +0000706 void FindMergedConditions(Value *Cond, MachineBasicBlock *TBB,
707 MachineBasicBlock *FBB, MachineBasicBlock *CurBB,
708 unsigned Opc);
Chris Lattner8c494ab2006-10-27 23:50:33 +0000709 bool isExportableFromCurrentBlock(Value *V, const BasicBlock *FromBB);
Chris Lattner571e4342006-10-27 21:36:01 +0000710 void ExportFromCurrentBlock(Value *V);
Dan Gohman475871a2008-07-27 21:46:04 +0000711 void LowerCallTo(CallSite CS, SDValue Callee, bool IsTailCall,
Anton Korobeynikov070280e2007-05-23 11:08:31 +0000712 MachineBasicBlock *LandingPad = NULL);
Duncan Sandsdc024672007-11-27 13:23:08 +0000713
Chris Lattner1c08c712005-01-07 07:47:53 +0000714 // Terminator instructions.
715 void visitRet(ReturnInst &I);
716 void visitBr(BranchInst &I);
Nate Begemanf15485a2006-03-27 01:32:24 +0000717 void visitSwitch(SwitchInst &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000718 void visitUnreachable(UnreachableInst &I) { /* noop */ }
719
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +0000720 // Helpers for visitSwitch
Anton Korobeynikovdd433212007-03-27 12:05:48 +0000721 bool handleSmallSwitchRange(CaseRec& CR,
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +0000722 CaseRecVector& WorkList,
723 Value* SV,
724 MachineBasicBlock* Default);
Anton Korobeynikovdd433212007-03-27 12:05:48 +0000725 bool handleJTSwitchCase(CaseRec& CR,
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +0000726 CaseRecVector& WorkList,
727 Value* SV,
728 MachineBasicBlock* Default);
Anton Korobeynikovdd433212007-03-27 12:05:48 +0000729 bool handleBTSplitSwitchCase(CaseRec& CR,
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +0000730 CaseRecVector& WorkList,
731 Value* SV,
732 MachineBasicBlock* Default);
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000733 bool handleBitTestsSwitchCase(CaseRec& CR,
734 CaseRecVector& WorkList,
735 Value* SV,
736 MachineBasicBlock* Default);
Nate Begemanf15485a2006-03-27 01:32:24 +0000737 void visitSwitchCase(SelectionDAGISel::CaseBlock &CB);
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000738 void visitBitTestHeader(SelectionDAGISel::BitTestBlock &B);
739 void visitBitTestCase(MachineBasicBlock* NextMBB,
740 unsigned Reg,
741 SelectionDAGISel::BitTestCase &B);
Nate Begeman37efe672006-04-22 18:53:45 +0000742 void visitJumpTable(SelectionDAGISel::JumpTable &JT);
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +0000743 void visitJumpTableHeader(SelectionDAGISel::JumpTable &JT,
744 SelectionDAGISel::JumpTableHeader &JTH);
Nate Begemanf15485a2006-03-27 01:32:24 +0000745
Chris Lattner1c08c712005-01-07 07:47:53 +0000746 // These all get lowered before this pass.
Jim Laskeyb180aa12007-02-21 22:53:45 +0000747 void visitInvoke(InvokeInst &I);
748 void visitUnwind(UnwindInst &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000749
Dan Gohman7f321562007-06-25 16:23:39 +0000750 void visitBinary(User &I, unsigned OpCode);
Nate Begemane21ea612005-11-18 07:42:56 +0000751 void visitShift(User &I, unsigned Opcode);
Nate Begeman5fbb5d22005-11-19 00:36:38 +0000752 void visitAdd(User &I) {
Dan Gohman7f321562007-06-25 16:23:39 +0000753 if (I.getType()->isFPOrFPVector())
754 visitBinary(I, ISD::FADD);
Reid Spencer1628cec2006-10-26 06:15:43 +0000755 else
Dan Gohman7f321562007-06-25 16:23:39 +0000756 visitBinary(I, ISD::ADD);
Chris Lattner01b3d732005-09-28 22:28:18 +0000757 }
Chris Lattnerb9fccc42005-04-02 05:04:50 +0000758 void visitSub(User &I);
Reid Spencer1628cec2006-10-26 06:15:43 +0000759 void visitMul(User &I) {
Dan Gohman7f321562007-06-25 16:23:39 +0000760 if (I.getType()->isFPOrFPVector())
761 visitBinary(I, ISD::FMUL);
Reid Spencer1628cec2006-10-26 06:15:43 +0000762 else
Dan Gohman7f321562007-06-25 16:23:39 +0000763 visitBinary(I, ISD::MUL);
Chris Lattner01b3d732005-09-28 22:28:18 +0000764 }
Dan Gohman7f321562007-06-25 16:23:39 +0000765 void visitURem(User &I) { visitBinary(I, ISD::UREM); }
766 void visitSRem(User &I) { visitBinary(I, ISD::SREM); }
767 void visitFRem(User &I) { visitBinary(I, ISD::FREM); }
768 void visitUDiv(User &I) { visitBinary(I, ISD::UDIV); }
769 void visitSDiv(User &I) { visitBinary(I, ISD::SDIV); }
770 void visitFDiv(User &I) { visitBinary(I, ISD::FDIV); }
771 void visitAnd (User &I) { visitBinary(I, ISD::AND); }
772 void visitOr (User &I) { visitBinary(I, ISD::OR); }
773 void visitXor (User &I) { visitBinary(I, ISD::XOR); }
Reid Spencer24d6da52007-01-21 00:29:26 +0000774 void visitShl (User &I) { visitShift(I, ISD::SHL); }
Reid Spencer3822ff52006-11-08 06:47:33 +0000775 void visitLShr(User &I) { visitShift(I, ISD::SRL); }
776 void visitAShr(User &I) { visitShift(I, ISD::SRA); }
Reid Spencer45fb3f32006-11-20 01:22:35 +0000777 void visitICmp(User &I);
778 void visitFCmp(User &I);
Nate Begemanb43e9c12008-05-12 19:40:03 +0000779 void visitVICmp(User &I);
780 void visitVFCmp(User &I);
Reid Spencer3da59db2006-11-27 01:05:10 +0000781 // Visit the conversion instructions
782 void visitTrunc(User &I);
783 void visitZExt(User &I);
784 void visitSExt(User &I);
785 void visitFPTrunc(User &I);
786 void visitFPExt(User &I);
787 void visitFPToUI(User &I);
788 void visitFPToSI(User &I);
789 void visitUIToFP(User &I);
790 void visitSIToFP(User &I);
791 void visitPtrToInt(User &I);
792 void visitIntToPtr(User &I);
793 void visitBitCast(User &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000794
Chris Lattner2bbd8102006-03-29 00:11:43 +0000795 void visitExtractElement(User &I);
796 void visitInsertElement(User &I);
Chris Lattner3e104b12006-04-08 04:15:24 +0000797 void visitShuffleVector(User &I);
Chris Lattnerc7029802006-03-18 01:44:44 +0000798
Dan Gohman1d685a42008-06-07 02:02:36 +0000799 void visitExtractValue(ExtractValueInst &I);
800 void visitInsertValue(InsertValueInst &I);
Dan Gohman041e2eb2008-05-15 19:50:34 +0000801
Chris Lattner1c08c712005-01-07 07:47:53 +0000802 void visitGetElementPtr(User &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000803 void visitSelect(User &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000804
805 void visitMalloc(MallocInst &I);
806 void visitFree(FreeInst &I);
807 void visitAlloca(AllocaInst &I);
808 void visitLoad(LoadInst &I);
809 void visitStore(StoreInst &I);
810 void visitPHI(PHINode &I) { } // PHI nodes are handled specially.
811 void visitCall(CallInst &I);
Duncan Sandsfd7b3262007-12-17 18:08:19 +0000812 void visitInlineAsm(CallSite CS);
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +0000813 const char *visitIntrinsicCall(CallInst &I, unsigned Intrinsic);
Chris Lattner0eade312006-03-24 02:22:33 +0000814 void visitTargetIntrinsic(CallInst &I, unsigned Intrinsic);
Chris Lattner1c08c712005-01-07 07:47:53 +0000815
Chris Lattner1c08c712005-01-07 07:47:53 +0000816 void visitVAStart(CallInst &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000817 void visitVAArg(VAArgInst &I);
818 void visitVAEnd(CallInst &I);
819 void visitVACopy(CallInst &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000820
Chris Lattner1c08c712005-01-07 07:47:53 +0000821 void visitUserOp1(Instruction &I) {
822 assert(0 && "UserOp1 should not exist at instruction selection time!");
823 abort();
824 }
825 void visitUserOp2(Instruction &I) {
826 assert(0 && "UserOp2 should not exist at instruction selection time!");
827 abort();
828 }
Mon P Wang63307c32008-05-05 19:05:59 +0000829
830private:
831 inline const char *implVisitBinaryAtomic(CallInst& I, ISD::NodeType Op);
832
Chris Lattner1c08c712005-01-07 07:47:53 +0000833};
834} // end namespace llvm
835
Dan Gohman6183f782007-07-05 20:12:34 +0000836
Duncan Sandsb988bac2008-02-11 20:58:28 +0000837/// getCopyFromParts - Create a value that contains the specified legal parts
838/// combined into the value they represent. If the parts combine to a type
839/// larger then ValueVT then AssertOp can be used to specify whether the extra
840/// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
Chris Lattner4468c1f2008-03-09 09:38:46 +0000841/// (ISD::AssertSext).
Dan Gohman475871a2008-07-27 21:46:04 +0000842static SDValue getCopyFromParts(SelectionDAG &DAG,
843 const SDValue *Parts,
Dan Gohman6183f782007-07-05 20:12:34 +0000844 unsigned NumParts,
Duncan Sands83ec4b62008-06-06 12:08:01 +0000845 MVT PartVT,
846 MVT ValueVT,
Chris Lattner4468c1f2008-03-09 09:38:46 +0000847 ISD::NodeType AssertOp = ISD::DELETED_NODE) {
Duncan Sands014e04a2008-02-12 20:46:31 +0000848 assert(NumParts > 0 && "No parts to assemble!");
849 TargetLowering &TLI = DAG.getTargetLoweringInfo();
Dan Gohman475871a2008-07-27 21:46:04 +0000850 SDValue Val = Parts[0];
Dan Gohman6183f782007-07-05 20:12:34 +0000851
Duncan Sands014e04a2008-02-12 20:46:31 +0000852 if (NumParts > 1) {
853 // Assemble the value from multiple parts.
Duncan Sands83ec4b62008-06-06 12:08:01 +0000854 if (!ValueVT.isVector()) {
855 unsigned PartBits = PartVT.getSizeInBits();
856 unsigned ValueBits = ValueVT.getSizeInBits();
Dan Gohman6183f782007-07-05 20:12:34 +0000857
Duncan Sands014e04a2008-02-12 20:46:31 +0000858 // Assemble the power of 2 part.
859 unsigned RoundParts = NumParts & (NumParts - 1) ?
860 1 << Log2_32(NumParts) : NumParts;
861 unsigned RoundBits = PartBits * RoundParts;
Duncan Sands83ec4b62008-06-06 12:08:01 +0000862 MVT RoundVT = RoundBits == ValueBits ?
863 ValueVT : MVT::getIntegerVT(RoundBits);
Dan Gohman475871a2008-07-27 21:46:04 +0000864 SDValue Lo, Hi;
Duncan Sands014e04a2008-02-12 20:46:31 +0000865
866 if (RoundParts > 2) {
Duncan Sands83ec4b62008-06-06 12:08:01 +0000867 MVT HalfVT = MVT::getIntegerVT(RoundBits/2);
Duncan Sands014e04a2008-02-12 20:46:31 +0000868 Lo = getCopyFromParts(DAG, Parts, RoundParts/2, PartVT, HalfVT);
869 Hi = getCopyFromParts(DAG, Parts+RoundParts/2, RoundParts/2,
870 PartVT, HalfVT);
Dan Gohman6183f782007-07-05 20:12:34 +0000871 } else {
Duncan Sands014e04a2008-02-12 20:46:31 +0000872 Lo = Parts[0];
873 Hi = Parts[1];
Dan Gohman6183f782007-07-05 20:12:34 +0000874 }
Duncan Sands014e04a2008-02-12 20:46:31 +0000875 if (TLI.isBigEndian())
876 std::swap(Lo, Hi);
877 Val = DAG.getNode(ISD::BUILD_PAIR, RoundVT, Lo, Hi);
878
879 if (RoundParts < NumParts) {
880 // Assemble the trailing non-power-of-2 part.
881 unsigned OddParts = NumParts - RoundParts;
Duncan Sands83ec4b62008-06-06 12:08:01 +0000882 MVT OddVT = MVT::getIntegerVT(OddParts * PartBits);
Duncan Sands014e04a2008-02-12 20:46:31 +0000883 Hi = getCopyFromParts(DAG, Parts+RoundParts, OddParts, PartVT, OddVT);
884
885 // Combine the round and odd parts.
886 Lo = Val;
887 if (TLI.isBigEndian())
888 std::swap(Lo, Hi);
Duncan Sands83ec4b62008-06-06 12:08:01 +0000889 MVT TotalVT = MVT::getIntegerVT(NumParts * PartBits);
Duncan Sands014e04a2008-02-12 20:46:31 +0000890 Hi = DAG.getNode(ISD::ANY_EXTEND, TotalVT, Hi);
891 Hi = DAG.getNode(ISD::SHL, TotalVT, Hi,
Duncan Sands83ec4b62008-06-06 12:08:01 +0000892 DAG.getConstant(Lo.getValueType().getSizeInBits(),
Duncan Sands014e04a2008-02-12 20:46:31 +0000893 TLI.getShiftAmountTy()));
894 Lo = DAG.getNode(ISD::ZERO_EXTEND, TotalVT, Lo);
895 Val = DAG.getNode(ISD::OR, TotalVT, Lo, Hi);
896 }
897 } else {
898 // Handle a multi-element vector.
Duncan Sands83ec4b62008-06-06 12:08:01 +0000899 MVT IntermediateVT, RegisterVT;
Duncan Sands014e04a2008-02-12 20:46:31 +0000900 unsigned NumIntermediates;
901 unsigned NumRegs =
902 TLI.getVectorTypeBreakdown(ValueVT, IntermediateVT, NumIntermediates,
903 RegisterVT);
Duncan Sands014e04a2008-02-12 20:46:31 +0000904 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
Evan Cheng35213342008-05-14 20:29:30 +0000905 NumParts = NumRegs; // Silence a compiler warning.
Duncan Sands014e04a2008-02-12 20:46:31 +0000906 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
907 assert(RegisterVT == Parts[0].getValueType() &&
908 "Part type doesn't match part!");
909
910 // Assemble the parts into intermediate operands.
Dan Gohman475871a2008-07-27 21:46:04 +0000911 SmallVector<SDValue, 8> Ops(NumIntermediates);
Duncan Sands014e04a2008-02-12 20:46:31 +0000912 if (NumIntermediates == NumParts) {
913 // If the register was not expanded, truncate or copy the value,
914 // as appropriate.
915 for (unsigned i = 0; i != NumParts; ++i)
916 Ops[i] = getCopyFromParts(DAG, &Parts[i], 1,
917 PartVT, IntermediateVT);
918 } else if (NumParts > 0) {
919 // If the intermediate type was expanded, build the intermediate operands
920 // from the parts.
921 assert(NumParts % NumIntermediates == 0 &&
922 "Must expand into a divisible number of parts!");
923 unsigned Factor = NumParts / NumIntermediates;
924 for (unsigned i = 0; i != NumIntermediates; ++i)
925 Ops[i] = getCopyFromParts(DAG, &Parts[i * Factor], Factor,
926 PartVT, IntermediateVT);
927 }
928
929 // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the intermediate
930 // operands.
Duncan Sands83ec4b62008-06-06 12:08:01 +0000931 Val = DAG.getNode(IntermediateVT.isVector() ?
Duncan Sands014e04a2008-02-12 20:46:31 +0000932 ISD::CONCAT_VECTORS : ISD::BUILD_VECTOR,
933 ValueVT, &Ops[0], NumIntermediates);
Dan Gohman6183f782007-07-05 20:12:34 +0000934 }
Dan Gohman6183f782007-07-05 20:12:34 +0000935 }
936
Duncan Sands014e04a2008-02-12 20:46:31 +0000937 // There is now one part, held in Val. Correct it to match ValueVT.
938 PartVT = Val.getValueType();
Dan Gohman6183f782007-07-05 20:12:34 +0000939
Duncan Sands014e04a2008-02-12 20:46:31 +0000940 if (PartVT == ValueVT)
941 return Val;
Dan Gohman6183f782007-07-05 20:12:34 +0000942
Duncan Sands83ec4b62008-06-06 12:08:01 +0000943 if (PartVT.isVector()) {
944 assert(ValueVT.isVector() && "Unknown vector conversion!");
Duncan Sands014e04a2008-02-12 20:46:31 +0000945 return DAG.getNode(ISD::BIT_CONVERT, ValueVT, Val);
Dan Gohman6183f782007-07-05 20:12:34 +0000946 }
Duncan Sands014e04a2008-02-12 20:46:31 +0000947
Duncan Sands83ec4b62008-06-06 12:08:01 +0000948 if (ValueVT.isVector()) {
949 assert(ValueVT.getVectorElementType() == PartVT &&
950 ValueVT.getVectorNumElements() == 1 &&
Duncan Sands014e04a2008-02-12 20:46:31 +0000951 "Only trivial scalar-to-vector conversions should get here!");
952 return DAG.getNode(ISD::BUILD_VECTOR, ValueVT, Val);
953 }
954
Duncan Sands83ec4b62008-06-06 12:08:01 +0000955 if (PartVT.isInteger() &&
956 ValueVT.isInteger()) {
Duncan Sands8e4eb092008-06-08 20:54:56 +0000957 if (ValueVT.bitsLT(PartVT)) {
Duncan Sands014e04a2008-02-12 20:46:31 +0000958 // For a truncate, see if we have any information to
959 // indicate whether the truncated bits will always be
960 // zero or sign-extension.
961 if (AssertOp != ISD::DELETED_NODE)
962 Val = DAG.getNode(AssertOp, PartVT, Val,
963 DAG.getValueType(ValueVT));
964 return DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
965 } else {
966 return DAG.getNode(ISD::ANY_EXTEND, ValueVT, Val);
967 }
968 }
969
Duncan Sands83ec4b62008-06-06 12:08:01 +0000970 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
Duncan Sands8e4eb092008-06-08 20:54:56 +0000971 if (ValueVT.bitsLT(Val.getValueType()))
Chris Lattner4468c1f2008-03-09 09:38:46 +0000972 // FP_ROUND's are always exact here.
Chris Lattnerd43d85c2008-03-09 07:47:22 +0000973 return DAG.getNode(ISD::FP_ROUND, ValueVT, Val,
Chris Lattner4468c1f2008-03-09 09:38:46 +0000974 DAG.getIntPtrConstant(1));
Chris Lattnerd43d85c2008-03-09 07:47:22 +0000975 return DAG.getNode(ISD::FP_EXTEND, ValueVT, Val);
976 }
Duncan Sands014e04a2008-02-12 20:46:31 +0000977
Duncan Sands83ec4b62008-06-06 12:08:01 +0000978 if (PartVT.getSizeInBits() == ValueVT.getSizeInBits())
Duncan Sands014e04a2008-02-12 20:46:31 +0000979 return DAG.getNode(ISD::BIT_CONVERT, ValueVT, Val);
980
981 assert(0 && "Unknown mismatch!");
Dan Gohman475871a2008-07-27 21:46:04 +0000982 return SDValue();
Dan Gohman6183f782007-07-05 20:12:34 +0000983}
984
Duncan Sandsb988bac2008-02-11 20:58:28 +0000985/// getCopyToParts - Create a series of nodes that contain the specified value
986/// split into legal parts. If the parts contain more bits than Val, then, for
987/// integers, ExtendKind can be used to specify how to generate the extra bits.
Dan Gohman6183f782007-07-05 20:12:34 +0000988static void getCopyToParts(SelectionDAG &DAG,
Dan Gohman475871a2008-07-27 21:46:04 +0000989 SDValue Val,
990 SDValue *Parts,
Dan Gohman6183f782007-07-05 20:12:34 +0000991 unsigned NumParts,
Duncan Sands83ec4b62008-06-06 12:08:01 +0000992 MVT PartVT,
Duncan Sandsb988bac2008-02-11 20:58:28 +0000993 ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
Dan Gohman25ac7e82007-08-10 14:59:38 +0000994 TargetLowering &TLI = DAG.getTargetLoweringInfo();
Duncan Sands83ec4b62008-06-06 12:08:01 +0000995 MVT PtrVT = TLI.getPointerTy();
996 MVT ValueVT = Val.getValueType();
997 unsigned PartBits = PartVT.getSizeInBits();
Duncan Sands014e04a2008-02-12 20:46:31 +0000998 assert(TLI.isTypeLegal(PartVT) && "Copying to an illegal type!");
Dan Gohman6183f782007-07-05 20:12:34 +0000999
Duncan Sands014e04a2008-02-12 20:46:31 +00001000 if (!NumParts)
1001 return;
1002
Duncan Sands83ec4b62008-06-06 12:08:01 +00001003 if (!ValueVT.isVector()) {
Duncan Sands014e04a2008-02-12 20:46:31 +00001004 if (PartVT == ValueVT) {
1005 assert(NumParts == 1 && "No-op copy with multiple parts!");
1006 Parts[0] = Val;
Dan Gohman6183f782007-07-05 20:12:34 +00001007 return;
1008 }
1009
Duncan Sands83ec4b62008-06-06 12:08:01 +00001010 if (NumParts * PartBits > ValueVT.getSizeInBits()) {
Duncan Sands014e04a2008-02-12 20:46:31 +00001011 // If the parts cover more bits than the value has, promote the value.
Duncan Sands83ec4b62008-06-06 12:08:01 +00001012 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
Duncan Sands014e04a2008-02-12 20:46:31 +00001013 assert(NumParts == 1 && "Do not know what to promote to!");
Dan Gohman6183f782007-07-05 20:12:34 +00001014 Val = DAG.getNode(ISD::FP_EXTEND, PartVT, Val);
Duncan Sands83ec4b62008-06-06 12:08:01 +00001015 } else if (PartVT.isInteger() && ValueVT.isInteger()) {
1016 ValueVT = MVT::getIntegerVT(NumParts * PartBits);
Duncan Sands014e04a2008-02-12 20:46:31 +00001017 Val = DAG.getNode(ExtendKind, ValueVT, Val);
1018 } else {
1019 assert(0 && "Unknown mismatch!");
1020 }
Duncan Sands83ec4b62008-06-06 12:08:01 +00001021 } else if (PartBits == ValueVT.getSizeInBits()) {
Duncan Sands014e04a2008-02-12 20:46:31 +00001022 // Different types of the same size.
1023 assert(NumParts == 1 && PartVT != ValueVT);
1024 Val = DAG.getNode(ISD::BIT_CONVERT, PartVT, Val);
Duncan Sands83ec4b62008-06-06 12:08:01 +00001025 } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
Duncan Sands014e04a2008-02-12 20:46:31 +00001026 // If the parts cover less bits than value has, truncate the value.
Duncan Sands83ec4b62008-06-06 12:08:01 +00001027 if (PartVT.isInteger() && ValueVT.isInteger()) {
1028 ValueVT = MVT::getIntegerVT(NumParts * PartBits);
Duncan Sands014e04a2008-02-12 20:46:31 +00001029 Val = DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
Dan Gohman6183f782007-07-05 20:12:34 +00001030 } else {
1031 assert(0 && "Unknown mismatch!");
1032 }
1033 }
Duncan Sands014e04a2008-02-12 20:46:31 +00001034
1035 // The value may have changed - recompute ValueVT.
1036 ValueVT = Val.getValueType();
Duncan Sands83ec4b62008-06-06 12:08:01 +00001037 assert(NumParts * PartBits == ValueVT.getSizeInBits() &&
Duncan Sands014e04a2008-02-12 20:46:31 +00001038 "Failed to tile the value with PartVT!");
1039
1040 if (NumParts == 1) {
1041 assert(PartVT == ValueVT && "Type conversion failed!");
1042 Parts[0] = Val;
1043 return;
1044 }
1045
1046 // Expand the value into multiple parts.
1047 if (NumParts & (NumParts - 1)) {
1048 // The number of parts is not a power of 2. Split off and copy the tail.
Duncan Sands83ec4b62008-06-06 12:08:01 +00001049 assert(PartVT.isInteger() && ValueVT.isInteger() &&
Duncan Sands014e04a2008-02-12 20:46:31 +00001050 "Do not know what to expand to!");
1051 unsigned RoundParts = 1 << Log2_32(NumParts);
1052 unsigned RoundBits = RoundParts * PartBits;
1053 unsigned OddParts = NumParts - RoundParts;
Dan Gohman475871a2008-07-27 21:46:04 +00001054 SDValue OddVal = DAG.getNode(ISD::SRL, ValueVT, Val,
Duncan Sands014e04a2008-02-12 20:46:31 +00001055 DAG.getConstant(RoundBits,
1056 TLI.getShiftAmountTy()));
1057 getCopyToParts(DAG, OddVal, Parts + RoundParts, OddParts, PartVT);
1058 if (TLI.isBigEndian())
1059 // The odd parts were reversed by getCopyToParts - unreverse them.
1060 std::reverse(Parts + RoundParts, Parts + NumParts);
1061 NumParts = RoundParts;
Duncan Sands83ec4b62008-06-06 12:08:01 +00001062 ValueVT = MVT::getIntegerVT(NumParts * PartBits);
Duncan Sands014e04a2008-02-12 20:46:31 +00001063 Val = DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
1064 }
1065
1066 // The number of parts is a power of 2. Repeatedly bisect the value using
1067 // EXTRACT_ELEMENT.
Duncan Sands25eb0432008-03-12 20:30:08 +00001068 Parts[0] = DAG.getNode(ISD::BIT_CONVERT,
Duncan Sands83ec4b62008-06-06 12:08:01 +00001069 MVT::getIntegerVT(ValueVT.getSizeInBits()),
Duncan Sands25eb0432008-03-12 20:30:08 +00001070 Val);
Duncan Sands014e04a2008-02-12 20:46:31 +00001071 for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
1072 for (unsigned i = 0; i < NumParts; i += StepSize) {
1073 unsigned ThisBits = StepSize * PartBits / 2;
Duncan Sands83ec4b62008-06-06 12:08:01 +00001074 MVT ThisVT = MVT::getIntegerVT (ThisBits);
Dan Gohman475871a2008-07-27 21:46:04 +00001075 SDValue &Part0 = Parts[i];
1076 SDValue &Part1 = Parts[i+StepSize/2];
Duncan Sands014e04a2008-02-12 20:46:31 +00001077
Duncan Sands25eb0432008-03-12 20:30:08 +00001078 Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, ThisVT, Part0,
1079 DAG.getConstant(1, PtrVT));
1080 Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, ThisVT, Part0,
1081 DAG.getConstant(0, PtrVT));
1082
1083 if (ThisBits == PartBits && ThisVT != PartVT) {
1084 Part0 = DAG.getNode(ISD::BIT_CONVERT, PartVT, Part0);
1085 Part1 = DAG.getNode(ISD::BIT_CONVERT, PartVT, Part1);
1086 }
Duncan Sands014e04a2008-02-12 20:46:31 +00001087 }
1088 }
1089
1090 if (TLI.isBigEndian())
1091 std::reverse(Parts, Parts + NumParts);
1092
1093 return;
1094 }
1095
1096 // Vector ValueVT.
1097 if (NumParts == 1) {
1098 if (PartVT != ValueVT) {
Duncan Sands83ec4b62008-06-06 12:08:01 +00001099 if (PartVT.isVector()) {
Duncan Sands014e04a2008-02-12 20:46:31 +00001100 Val = DAG.getNode(ISD::BIT_CONVERT, PartVT, Val);
1101 } else {
Duncan Sands83ec4b62008-06-06 12:08:01 +00001102 assert(ValueVT.getVectorElementType() == PartVT &&
1103 ValueVT.getVectorNumElements() == 1 &&
Duncan Sands014e04a2008-02-12 20:46:31 +00001104 "Only trivial vector-to-scalar conversions should get here!");
1105 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, PartVT, Val,
1106 DAG.getConstant(0, PtrVT));
1107 }
1108 }
1109
Dan Gohman6183f782007-07-05 20:12:34 +00001110 Parts[0] = Val;
1111 return;
1112 }
1113
1114 // Handle a multi-element vector.
Duncan Sands83ec4b62008-06-06 12:08:01 +00001115 MVT IntermediateVT, RegisterVT;
Dan Gohman6183f782007-07-05 20:12:34 +00001116 unsigned NumIntermediates;
1117 unsigned NumRegs =
1118 DAG.getTargetLoweringInfo()
1119 .getVectorTypeBreakdown(ValueVT, IntermediateVT, NumIntermediates,
1120 RegisterVT);
Duncan Sands83ec4b62008-06-06 12:08:01 +00001121 unsigned NumElements = ValueVT.getVectorNumElements();
Dan Gohman6183f782007-07-05 20:12:34 +00001122
1123 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
Evan Cheng35213342008-05-14 20:29:30 +00001124 NumParts = NumRegs; // Silence a compiler warning.
Dan Gohman6183f782007-07-05 20:12:34 +00001125 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
1126
1127 // Split the vector into intermediate operands.
Dan Gohman475871a2008-07-27 21:46:04 +00001128 SmallVector<SDValue, 8> Ops(NumIntermediates);
Dan Gohman6183f782007-07-05 20:12:34 +00001129 for (unsigned i = 0; i != NumIntermediates; ++i)
Duncan Sands83ec4b62008-06-06 12:08:01 +00001130 if (IntermediateVT.isVector())
Dan Gohman6183f782007-07-05 20:12:34 +00001131 Ops[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR,
1132 IntermediateVT, Val,
1133 DAG.getConstant(i * (NumElements / NumIntermediates),
Dan Gohman25ac7e82007-08-10 14:59:38 +00001134 PtrVT));
Dan Gohman6183f782007-07-05 20:12:34 +00001135 else
1136 Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
1137 IntermediateVT, Val,
Dan Gohman25ac7e82007-08-10 14:59:38 +00001138 DAG.getConstant(i, PtrVT));
Dan Gohman6183f782007-07-05 20:12:34 +00001139
1140 // Split the intermediate operands into legal parts.
1141 if (NumParts == NumIntermediates) {
1142 // If the register was not expanded, promote or copy the value,
1143 // as appropriate.
1144 for (unsigned i = 0; i != NumParts; ++i)
Dan Gohman532dc2e2007-07-09 20:59:04 +00001145 getCopyToParts(DAG, Ops[i], &Parts[i], 1, PartVT);
Dan Gohman6183f782007-07-05 20:12:34 +00001146 } else if (NumParts > 0) {
1147 // If the intermediate type was expanded, split each the value into
1148 // legal parts.
1149 assert(NumParts % NumIntermediates == 0 &&
1150 "Must expand into a divisible number of parts!");
1151 unsigned Factor = NumParts / NumIntermediates;
1152 for (unsigned i = 0; i != NumIntermediates; ++i)
Dan Gohman532dc2e2007-07-09 20:59:04 +00001153 getCopyToParts(DAG, Ops[i], &Parts[i * Factor], Factor, PartVT);
Dan Gohman6183f782007-07-05 20:12:34 +00001154 }
1155}
1156
1157
Dan Gohman475871a2008-07-27 21:46:04 +00001158SDValue SelectionDAGLowering::getValue(const Value *V) {
1159 SDValue &N = NodeMap[V];
Chris Lattner199862b2006-03-16 19:57:50 +00001160 if (N.Val) return N;
1161
Chris Lattner199862b2006-03-16 19:57:50 +00001162 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V))) {
Duncan Sands83ec4b62008-06-06 12:08:01 +00001163 MVT VT = TLI.getValueType(V->getType(), true);
Chris Lattnerb606dba2008-04-28 06:44:42 +00001164
1165 if (ConstantInt *CI = dyn_cast<ConstantInt>(C))
1166 return N = DAG.getConstant(CI->getValue(), VT);
1167
1168 if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
Chris Lattner199862b2006-03-16 19:57:50 +00001169 return N = DAG.getGlobalAddress(GV, VT);
Chris Lattnerb606dba2008-04-28 06:44:42 +00001170
1171 if (isa<ConstantPointerNull>(C))
Chris Lattner199862b2006-03-16 19:57:50 +00001172 return N = DAG.getConstant(0, TLI.getPointerTy());
Chris Lattnerb606dba2008-04-28 06:44:42 +00001173
1174 if (ConstantFP *CFP = dyn_cast<ConstantFP>(C))
1175 return N = DAG.getConstantFP(CFP->getValueAPF(), VT);
1176
Dan Gohman1d685a42008-06-07 02:02:36 +00001177 if (isa<UndefValue>(C) && !isa<VectorType>(V->getType()) &&
1178 !V->getType()->isAggregateType())
Chris Lattner6833b062008-04-28 07:16:35 +00001179 return N = DAG.getNode(ISD::UNDEF, VT);
Chris Lattnerb606dba2008-04-28 06:44:42 +00001180
1181 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
1182 visit(CE->getOpcode(), *CE);
Dan Gohman475871a2008-07-27 21:46:04 +00001183 SDValue N1 = NodeMap[V];
Chris Lattnerb606dba2008-04-28 06:44:42 +00001184 assert(N1.Val && "visit didn't populate the ValueMap!");
1185 return N1;
1186 }
1187
Dan Gohman1d685a42008-06-07 02:02:36 +00001188 if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
Dan Gohman475871a2008-07-27 21:46:04 +00001189 SmallVector<SDValue, 4> Constants;
Dan Gohman1d685a42008-06-07 02:02:36 +00001190 for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end();
1191 OI != OE; ++OI) {
1192 SDNode *Val = getValue(*OI).Val;
Duncan Sands4bdcb612008-07-02 17:40:58 +00001193 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
Dan Gohman475871a2008-07-27 21:46:04 +00001194 Constants.push_back(SDValue(Val, i));
Dan Gohman1d685a42008-06-07 02:02:36 +00001195 }
Duncan Sands4bdcb612008-07-02 17:40:58 +00001196 return DAG.getMergeValues(&Constants[0], Constants.size());
Dan Gohman1d685a42008-06-07 02:02:36 +00001197 }
1198
Dan Gohman1f565bc2008-08-04 23:30:41 +00001199 if (isa<StructType>(C->getType()) || isa<ArrayType>(C->getType())) {
Dan Gohman1d685a42008-06-07 02:02:36 +00001200 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
Dan Gohman1f565bc2008-08-04 23:30:41 +00001201 "Unknown struct or array constant!");
Dan Gohman1d685a42008-06-07 02:02:36 +00001202
Dan Gohman1f565bc2008-08-04 23:30:41 +00001203 SmallVector<MVT, 4> ValueVTs;
1204 ComputeValueVTs(TLI, C->getType(), ValueVTs);
1205 unsigned NumElts = ValueVTs.size();
Dan Gohman8a6ccb52008-06-09 15:21:47 +00001206 if (NumElts == 0)
Dan Gohman475871a2008-07-27 21:46:04 +00001207 return SDValue(); // empty struct
1208 SmallVector<SDValue, 4> Constants(NumElts);
Dan Gohman1f565bc2008-08-04 23:30:41 +00001209 for (unsigned i = 0; i != NumElts; ++i) {
1210 MVT EltVT = ValueVTs[i];
Dan Gohman1d685a42008-06-07 02:02:36 +00001211 if (isa<UndefValue>(C))
1212 Constants[i] = DAG.getNode(ISD::UNDEF, EltVT);
1213 else if (EltVT.isFloatingPoint())
1214 Constants[i] = DAG.getConstantFP(0, EltVT);
1215 else
1216 Constants[i] = DAG.getConstant(0, EltVT);
1217 }
Dan Gohman1f565bc2008-08-04 23:30:41 +00001218 return DAG.getMergeValues(&Constants[0], NumElts);
Dan Gohman1d685a42008-06-07 02:02:36 +00001219 }
1220
Chris Lattner6833b062008-04-28 07:16:35 +00001221 const VectorType *VecTy = cast<VectorType>(V->getType());
Chris Lattnerb606dba2008-04-28 06:44:42 +00001222 unsigned NumElements = VecTy->getNumElements();
Chris Lattnerb606dba2008-04-28 06:44:42 +00001223
Chris Lattner6833b062008-04-28 07:16:35 +00001224 // Now that we know the number and type of the elements, get that number of
1225 // elements into the Ops array based on what kind of constant it is.
Dan Gohman475871a2008-07-27 21:46:04 +00001226 SmallVector<SDValue, 16> Ops;
Chris Lattnerb606dba2008-04-28 06:44:42 +00001227 if (ConstantVector *CP = dyn_cast<ConstantVector>(C)) {
1228 for (unsigned i = 0; i != NumElements; ++i)
1229 Ops.push_back(getValue(CP->getOperand(i)));
1230 } else {
Chris Lattner6833b062008-04-28 07:16:35 +00001231 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
1232 "Unknown vector constant!");
Duncan Sands83ec4b62008-06-06 12:08:01 +00001233 MVT EltVT = TLI.getValueType(VecTy->getElementType());
Chris Lattner6833b062008-04-28 07:16:35 +00001234
Dan Gohman475871a2008-07-27 21:46:04 +00001235 SDValue Op;
Chris Lattner6833b062008-04-28 07:16:35 +00001236 if (isa<UndefValue>(C))
1237 Op = DAG.getNode(ISD::UNDEF, EltVT);
Duncan Sands83ec4b62008-06-06 12:08:01 +00001238 else if (EltVT.isFloatingPoint())
Chris Lattner6833b062008-04-28 07:16:35 +00001239 Op = DAG.getConstantFP(0, EltVT);
Chris Lattnerb606dba2008-04-28 06:44:42 +00001240 else
Chris Lattner6833b062008-04-28 07:16:35 +00001241 Op = DAG.getConstant(0, EltVT);
Chris Lattnerb606dba2008-04-28 06:44:42 +00001242 Ops.assign(NumElements, Op);
1243 }
1244
1245 // Create a BUILD_VECTOR node.
1246 return NodeMap[V] = DAG.getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
Chris Lattner199862b2006-03-16 19:57:50 +00001247 }
1248
Chris Lattnerb606dba2008-04-28 06:44:42 +00001249 // If this is a static alloca, generate it as the frameindex instead of
1250 // computation.
Chris Lattner199862b2006-03-16 19:57:50 +00001251 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1252 std::map<const AllocaInst*, int>::iterator SI =
Chris Lattnerb606dba2008-04-28 06:44:42 +00001253 FuncInfo.StaticAllocaMap.find(AI);
Chris Lattner199862b2006-03-16 19:57:50 +00001254 if (SI != FuncInfo.StaticAllocaMap.end())
1255 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
1256 }
1257
Chris Lattner251db182007-02-25 18:40:32 +00001258 unsigned InReg = FuncInfo.ValueMap[V];
1259 assert(InReg && "Value not in map!");
Chris Lattner199862b2006-03-16 19:57:50 +00001260
Chris Lattner6833b062008-04-28 07:16:35 +00001261 RegsForValue RFV(TLI, InReg, V->getType());
Dan Gohman475871a2008-07-27 21:46:04 +00001262 SDValue Chain = DAG.getEntryNode();
Dan Gohmanb6f5b002007-06-28 23:29:44 +00001263 return RFV.getCopyFromRegs(DAG, Chain, NULL);
Chris Lattner199862b2006-03-16 19:57:50 +00001264}
1265
1266
Chris Lattner1c08c712005-01-07 07:47:53 +00001267void SelectionDAGLowering::visitRet(ReturnInst &I) {
1268 if (I.getNumOperands() == 0) {
Dan Gohman86e1ebf2008-03-27 19:56:19 +00001269 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getControlRoot()));
Chris Lattner1c08c712005-01-07 07:47:53 +00001270 return;
1271 }
Chris Lattnerb606dba2008-04-28 06:44:42 +00001272
Dan Gohman475871a2008-07-27 21:46:04 +00001273 SmallVector<SDValue, 8> NewValues;
Dan Gohman86e1ebf2008-03-27 19:56:19 +00001274 NewValues.push_back(getControlRoot());
1275 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
Dan Gohman475871a2008-07-27 21:46:04 +00001276 SDValue RetOp = getValue(I.getOperand(i));
Duncan Sandsb988bac2008-02-11 20:58:28 +00001277
Dan Gohmanab8ec0a2008-06-20 01:29:26 +00001278 SmallVector<MVT, 4> ValueVTs;
1279 ComputeValueVTs(TLI, I.getOperand(i)->getType(), ValueVTs);
1280 for (unsigned j = 0, f = ValueVTs.size(); j != f; ++j) {
1281 MVT VT = ValueVTs[j];
Duncan Sandsb988bac2008-02-11 20:58:28 +00001282
Dan Gohmanab8ec0a2008-06-20 01:29:26 +00001283 // FIXME: C calling convention requires the return type to be promoted to
1284 // at least 32-bit. But this is not necessary for non-C calling conventions.
1285 if (VT.isInteger()) {
1286 MVT MinVT = TLI.getRegisterType(MVT::i32);
1287 if (VT.bitsLT(MinVT))
1288 VT = MinVT;
1289 }
Duncan Sandsb988bac2008-02-11 20:58:28 +00001290
Dan Gohmanab8ec0a2008-06-20 01:29:26 +00001291 unsigned NumParts = TLI.getNumRegisters(VT);
1292 MVT PartVT = TLI.getRegisterType(VT);
Dan Gohman475871a2008-07-27 21:46:04 +00001293 SmallVector<SDValue, 4> Parts(NumParts);
Dan Gohmanab8ec0a2008-06-20 01:29:26 +00001294 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
1295
1296 const Function *F = I.getParent()->getParent();
1297 if (F->paramHasAttr(0, ParamAttr::SExt))
1298 ExtendKind = ISD::SIGN_EXTEND;
1299 else if (F->paramHasAttr(0, ParamAttr::ZExt))
1300 ExtendKind = ISD::ZERO_EXTEND;
Duncan Sandsb988bac2008-02-11 20:58:28 +00001301
Dan Gohman475871a2008-07-27 21:46:04 +00001302 getCopyToParts(DAG, SDValue(RetOp.Val, RetOp.ResNo + j),
Dan Gohmanab8ec0a2008-06-20 01:29:26 +00001303 &Parts[0], NumParts, PartVT, ExtendKind);
Duncan Sandsb988bac2008-02-11 20:58:28 +00001304
Dan Gohmanab8ec0a2008-06-20 01:29:26 +00001305 for (unsigned i = 0; i < NumParts; ++i) {
1306 NewValues.push_back(Parts[i]);
1307 NewValues.push_back(DAG.getArgFlags(ISD::ArgFlagsTy()));
1308 }
Nate Begemanee625572006-01-27 21:09:22 +00001309 }
Chris Lattner1c08c712005-01-07 07:47:53 +00001310 }
Chris Lattnerbd564bf2006-08-08 02:23:42 +00001311 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other,
1312 &NewValues[0], NewValues.size()));
Chris Lattner1c08c712005-01-07 07:47:53 +00001313}
1314
Chris Lattner571e4342006-10-27 21:36:01 +00001315/// ExportFromCurrentBlock - If this condition isn't known to be exported from
1316/// the current basic block, add it to ValueMap now so that we'll get a
1317/// CopyTo/FromReg.
1318void SelectionDAGLowering::ExportFromCurrentBlock(Value *V) {
1319 // No need to export constants.
1320 if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
1321
1322 // Already exported?
1323 if (FuncInfo.isExportedInst(V)) return;
1324
1325 unsigned Reg = FuncInfo.InitializeRegForValue(V);
Dan Gohman86e1ebf2008-03-27 19:56:19 +00001326 CopyValueToVirtualRegister(V, Reg);
Chris Lattner571e4342006-10-27 21:36:01 +00001327}
1328
Chris Lattner8c494ab2006-10-27 23:50:33 +00001329bool SelectionDAGLowering::isExportableFromCurrentBlock(Value *V,
1330 const BasicBlock *FromBB) {
1331 // The operands of the setcc have to be in this block. We don't know
1332 // how to export them from some other block.
1333 if (Instruction *VI = dyn_cast<Instruction>(V)) {
1334 // Can export from current BB.
1335 if (VI->getParent() == FromBB)
1336 return true;
1337
1338 // Is already exported, noop.
1339 return FuncInfo.isExportedInst(V);
1340 }
1341
1342 // If this is an argument, we can export it if the BB is the entry block or
1343 // if it is already exported.
1344 if (isa<Argument>(V)) {
1345 if (FromBB == &FromBB->getParent()->getEntryBlock())
1346 return true;
1347
1348 // Otherwise, can only export this if it is already exported.
1349 return FuncInfo.isExportedInst(V);
1350 }
1351
1352 // Otherwise, constants can always be exported.
1353 return true;
1354}
1355
Chris Lattner6a586c82006-10-29 21:01:20 +00001356static bool InBlock(const Value *V, const BasicBlock *BB) {
1357 if (const Instruction *I = dyn_cast<Instruction>(V))
1358 return I->getParent() == BB;
1359 return true;
1360}
1361
Chris Lattner571e4342006-10-27 21:36:01 +00001362/// FindMergedConditions - If Cond is an expression like
1363void SelectionDAGLowering::FindMergedConditions(Value *Cond,
1364 MachineBasicBlock *TBB,
1365 MachineBasicBlock *FBB,
1366 MachineBasicBlock *CurBB,
1367 unsigned Opc) {
Chris Lattner571e4342006-10-27 21:36:01 +00001368 // If this node is not part of the or/and tree, emit it as a branch.
Reid Spencere4d87aa2006-12-23 06:05:41 +00001369 Instruction *BOp = dyn_cast<Instruction>(Cond);
Chris Lattner571e4342006-10-27 21:36:01 +00001370
Reid Spencere4d87aa2006-12-23 06:05:41 +00001371 if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
1372 (unsigned)BOp->getOpcode() != Opc || !BOp->hasOneUse() ||
Chris Lattner6a586c82006-10-29 21:01:20 +00001373 BOp->getParent() != CurBB->getBasicBlock() ||
1374 !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
1375 !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
Chris Lattner571e4342006-10-27 21:36:01 +00001376 const BasicBlock *BB = CurBB->getBasicBlock();
1377
Reid Spencere4d87aa2006-12-23 06:05:41 +00001378 // If the leaf of the tree is a comparison, merge the condition into
1379 // the caseblock.
1380 if ((isa<ICmpInst>(Cond) || isa<FCmpInst>(Cond)) &&
1381 // The operands of the cmp have to be in this block. We don't know
Chris Lattner5a145f02006-10-29 18:23:37 +00001382 // how to export them from some other block. If this is the first block
1383 // of the sequence, no exporting is needed.
1384 (CurBB == CurMBB ||
1385 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
1386 isExportableFromCurrentBlock(BOp->getOperand(1), BB)))) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00001387 BOp = cast<Instruction>(Cond);
1388 ISD::CondCode Condition;
1389 if (ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
1390 switch (IC->getPredicate()) {
1391 default: assert(0 && "Unknown icmp predicate opcode!");
1392 case ICmpInst::ICMP_EQ: Condition = ISD::SETEQ; break;
1393 case ICmpInst::ICMP_NE: Condition = ISD::SETNE; break;
1394 case ICmpInst::ICMP_SLE: Condition = ISD::SETLE; break;
1395 case ICmpInst::ICMP_ULE: Condition = ISD::SETULE; break;
1396 case ICmpInst::ICMP_SGE: Condition = ISD::SETGE; break;
1397 case ICmpInst::ICMP_UGE: Condition = ISD::SETUGE; break;
1398 case ICmpInst::ICMP_SLT: Condition = ISD::SETLT; break;
1399 case ICmpInst::ICMP_ULT: Condition = ISD::SETULT; break;
1400 case ICmpInst::ICMP_SGT: Condition = ISD::SETGT; break;
1401 case ICmpInst::ICMP_UGT: Condition = ISD::SETUGT; break;
1402 }
1403 } else if (FCmpInst *FC = dyn_cast<FCmpInst>(Cond)) {
1404 ISD::CondCode FPC, FOC;
1405 switch (FC->getPredicate()) {
1406 default: assert(0 && "Unknown fcmp predicate opcode!");
1407 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
1408 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
1409 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
1410 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
1411 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
1412 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
1413 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
Chris Lattner6bf30ab2008-05-01 07:26:11 +00001414 case FCmpInst::FCMP_ORD: FOC = FPC = ISD::SETO; break;
1415 case FCmpInst::FCMP_UNO: FOC = FPC = ISD::SETUO; break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00001416 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
1417 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
1418 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
1419 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
1420 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
1421 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
1422 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
1423 }
1424 if (FiniteOnlyFPMath())
1425 Condition = FOC;
1426 else
1427 Condition = FPC;
1428 } else {
Chris Lattner0da331f2007-02-04 01:31:47 +00001429 Condition = ISD::SETEQ; // silence warning.
Reid Spencere4d87aa2006-12-23 06:05:41 +00001430 assert(0 && "Unknown compare instruction");
Chris Lattner571e4342006-10-27 21:36:01 +00001431 }
1432
Chris Lattner571e4342006-10-27 21:36:01 +00001433 SelectionDAGISel::CaseBlock CB(Condition, BOp->getOperand(0),
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001434 BOp->getOperand(1), NULL, TBB, FBB, CurBB);
Chris Lattner571e4342006-10-27 21:36:01 +00001435 SwitchCases.push_back(CB);
1436 return;
1437 }
1438
1439 // Create a CaseBlock record representing this branch.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001440 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, Cond, ConstantInt::getTrue(),
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001441 NULL, TBB, FBB, CurBB);
Chris Lattner571e4342006-10-27 21:36:01 +00001442 SwitchCases.push_back(CB);
Chris Lattner571e4342006-10-27 21:36:01 +00001443 return;
1444 }
1445
Chris Lattnerd2f9ee92006-10-27 21:54:23 +00001446
1447 // Create TmpBB after CurBB.
Chris Lattner571e4342006-10-27 21:36:01 +00001448 MachineFunction::iterator BBI = CurBB;
Dan Gohman0e5f1302008-07-07 23:02:41 +00001449 MachineFunction &MF = DAG.getMachineFunction();
1450 MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
1451 CurBB->getParent()->insert(++BBI, TmpBB);
Chris Lattner571e4342006-10-27 21:36:01 +00001452
Chris Lattnerd2f9ee92006-10-27 21:54:23 +00001453 if (Opc == Instruction::Or) {
1454 // Codegen X | Y as:
1455 // jmp_if_X TBB
1456 // jmp TmpBB
1457 // TmpBB:
1458 // jmp_if_Y TBB
1459 // jmp FBB
1460 //
Chris Lattner571e4342006-10-27 21:36:01 +00001461
Chris Lattnerd2f9ee92006-10-27 21:54:23 +00001462 // Emit the LHS condition.
1463 FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, Opc);
1464
1465 // Emit the RHS condition into TmpBB.
1466 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
1467 } else {
1468 assert(Opc == Instruction::And && "Unknown merge op!");
1469 // Codegen X & Y as:
1470 // jmp_if_X TmpBB
1471 // jmp FBB
1472 // TmpBB:
1473 // jmp_if_Y TBB
1474 // jmp FBB
1475 //
1476 // This requires creation of TmpBB after CurBB.
1477
1478 // Emit the LHS condition.
1479 FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, Opc);
1480
1481 // Emit the RHS condition into TmpBB.
1482 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
1483 }
Chris Lattner571e4342006-10-27 21:36:01 +00001484}
1485
Chris Lattnerdf19f272006-10-31 22:37:42 +00001486/// If the set of cases should be emitted as a series of branches, return true.
1487/// If we should emit this as a bunch of and/or'd together conditions, return
1488/// false.
1489static bool
1490ShouldEmitAsBranches(const std::vector<SelectionDAGISel::CaseBlock> &Cases) {
1491 if (Cases.size() != 2) return true;
1492
Chris Lattner0ccb5002006-10-31 23:06:00 +00001493 // If this is two comparisons of the same values or'd or and'd together, they
1494 // will get folded into a single comparison, so don't emit two blocks.
1495 if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
1496 Cases[0].CmpRHS == Cases[1].CmpRHS) ||
1497 (Cases[0].CmpRHS == Cases[1].CmpLHS &&
1498 Cases[0].CmpLHS == Cases[1].CmpRHS)) {
1499 return false;
1500 }
1501
Chris Lattnerdf19f272006-10-31 22:37:42 +00001502 return true;
1503}
1504
Chris Lattner1c08c712005-01-07 07:47:53 +00001505void SelectionDAGLowering::visitBr(BranchInst &I) {
1506 // Update machine-CFG edges.
1507 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
Chris Lattner1c08c712005-01-07 07:47:53 +00001508
1509 // Figure out which block is immediately after the current one.
1510 MachineBasicBlock *NextBlock = 0;
1511 MachineFunction::iterator BBI = CurMBB;
1512 if (++BBI != CurMBB->getParent()->end())
1513 NextBlock = BBI;
1514
1515 if (I.isUnconditional()) {
Owen Anderson2d389e82008-06-07 00:00:23 +00001516 // Update machine-CFG edges.
1517 CurMBB->addSuccessor(Succ0MBB);
1518
Chris Lattner1c08c712005-01-07 07:47:53 +00001519 // If this is not a fall-through branch, emit the branch.
1520 if (Succ0MBB != NextBlock)
Dan Gohman86e1ebf2008-03-27 19:56:19 +00001521 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getControlRoot(),
Misha Brukmandedf2bd2005-04-22 04:01:18 +00001522 DAG.getBasicBlock(Succ0MBB)));
Chris Lattner57ab6592006-10-24 17:57:59 +00001523 return;
1524 }
1525
1526 // If this condition is one of the special cases we handle, do special stuff
1527 // now.
1528 Value *CondVal = I.getCondition();
Chris Lattner57ab6592006-10-24 17:57:59 +00001529 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
Chris Lattner571e4342006-10-27 21:36:01 +00001530
1531 // If this is a series of conditions that are or'd or and'd together, emit
1532 // this as a sequence of branches instead of setcc's with and/or operations.
1533 // For example, instead of something like:
1534 // cmp A, B
1535 // C = seteq
1536 // cmp D, E
1537 // F = setle
1538 // or C, F
1539 // jnz foo
1540 // Emit:
1541 // cmp A, B
1542 // je foo
1543 // cmp D, E
1544 // jle foo
1545 //
1546 if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
1547 if (BOp->hasOneUse() &&
Chris Lattnerd2f9ee92006-10-27 21:54:23 +00001548 (BOp->getOpcode() == Instruction::And ||
Chris Lattner571e4342006-10-27 21:36:01 +00001549 BOp->getOpcode() == Instruction::Or)) {
1550 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, CurMBB, BOp->getOpcode());
Chris Lattner0ccb5002006-10-31 23:06:00 +00001551 // If the compares in later blocks need to use values not currently
1552 // exported from this block, export them now. This block should always
1553 // be the first entry.
1554 assert(SwitchCases[0].ThisBB == CurMBB && "Unexpected lowering!");
1555
Chris Lattnerdf19f272006-10-31 22:37:42 +00001556 // Allow some cases to be rejected.
1557 if (ShouldEmitAsBranches(SwitchCases)) {
Chris Lattnerdf19f272006-10-31 22:37:42 +00001558 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
1559 ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
1560 ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
1561 }
1562
1563 // Emit the branch for this block.
1564 visitSwitchCase(SwitchCases[0]);
1565 SwitchCases.erase(SwitchCases.begin());
1566 return;
Chris Lattner5a145f02006-10-29 18:23:37 +00001567 }
1568
Chris Lattner0ccb5002006-10-31 23:06:00 +00001569 // Okay, we decided not to do this, remove any inserted MBB's and clear
1570 // SwitchCases.
1571 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
Dan Gohman0e5f1302008-07-07 23:02:41 +00001572 CurMBB->getParent()->erase(SwitchCases[i].ThisBB);
Chris Lattner0ccb5002006-10-31 23:06:00 +00001573
Chris Lattnerdf19f272006-10-31 22:37:42 +00001574 SwitchCases.clear();
Chris Lattner571e4342006-10-27 21:36:01 +00001575 }
1576 }
Chris Lattner24525952006-10-24 18:07:37 +00001577
1578 // Create a CaseBlock record representing this branch.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001579 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(),
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001580 NULL, Succ0MBB, Succ1MBB, CurMBB);
Chris Lattner24525952006-10-24 18:07:37 +00001581 // Use visitSwitchCase to actually insert the fast branch sequence for this
1582 // cond branch.
1583 visitSwitchCase(CB);
Chris Lattner1c08c712005-01-07 07:47:53 +00001584}
1585
Nate Begemanf15485a2006-03-27 01:32:24 +00001586/// visitSwitchCase - Emits the necessary code to represent a single node in
1587/// the binary search tree resulting from lowering a switch instruction.
1588void SelectionDAGLowering::visitSwitchCase(SelectionDAGISel::CaseBlock &CB) {
Dan Gohman475871a2008-07-27 21:46:04 +00001589 SDValue Cond;
1590 SDValue CondLHS = getValue(CB.CmpLHS);
Chris Lattner57ab6592006-10-24 17:57:59 +00001591
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001592 // Build the setcc now.
1593 if (CB.CmpMHS == NULL) {
1594 // Fold "(X == true)" to X and "(X == false)" to !X to
1595 // handle common cases produced by branch lowering.
1596 if (CB.CmpRHS == ConstantInt::getTrue() && CB.CC == ISD::SETEQ)
1597 Cond = CondLHS;
1598 else if (CB.CmpRHS == ConstantInt::getFalse() && CB.CC == ISD::SETEQ) {
Dan Gohman475871a2008-07-27 21:46:04 +00001599 SDValue True = DAG.getConstant(1, CondLHS.getValueType());
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001600 Cond = DAG.getNode(ISD::XOR, CondLHS.getValueType(), CondLHS, True);
1601 } else
1602 Cond = DAG.getSetCC(MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
1603 } else {
1604 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001605
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001606 uint64_t Low = cast<ConstantInt>(CB.CmpLHS)->getSExtValue();
1607 uint64_t High = cast<ConstantInt>(CB.CmpRHS)->getSExtValue();
1608
Dan Gohman475871a2008-07-27 21:46:04 +00001609 SDValue CmpOp = getValue(CB.CmpMHS);
Duncan Sands83ec4b62008-06-06 12:08:01 +00001610 MVT VT = CmpOp.getValueType();
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001611
1612 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
1613 Cond = DAG.getSetCC(MVT::i1, CmpOp, DAG.getConstant(High, VT), ISD::SETLE);
1614 } else {
Dan Gohman475871a2008-07-27 21:46:04 +00001615 SDValue SUB = DAG.getNode(ISD::SUB, VT, CmpOp, DAG.getConstant(Low, VT));
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001616 Cond = DAG.getSetCC(MVT::i1, SUB,
1617 DAG.getConstant(High-Low, VT), ISD::SETULE);
1618 }
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001619 }
1620
Owen Anderson2d389e82008-06-07 00:00:23 +00001621 // Update successor info
1622 CurMBB->addSuccessor(CB.TrueBB);
1623 CurMBB->addSuccessor(CB.FalseBB);
1624
Nate Begemanf15485a2006-03-27 01:32:24 +00001625 // Set NextBlock to be the MBB immediately after the current one, if any.
1626 // This is used to avoid emitting unnecessary branches to the next block.
1627 MachineBasicBlock *NextBlock = 0;
1628 MachineFunction::iterator BBI = CurMBB;
1629 if (++BBI != CurMBB->getParent()->end())
1630 NextBlock = BBI;
1631
1632 // If the lhs block is the next block, invert the condition so that we can
1633 // fall through to the lhs instead of the rhs block.
Chris Lattner57ab6592006-10-24 17:57:59 +00001634 if (CB.TrueBB == NextBlock) {
1635 std::swap(CB.TrueBB, CB.FalseBB);
Dan Gohman475871a2008-07-27 21:46:04 +00001636 SDValue True = DAG.getConstant(1, Cond.getValueType());
Nate Begemanf15485a2006-03-27 01:32:24 +00001637 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
1638 }
Dan Gohman475871a2008-07-27 21:46:04 +00001639 SDValue BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, getControlRoot(), Cond,
Chris Lattner57ab6592006-10-24 17:57:59 +00001640 DAG.getBasicBlock(CB.TrueBB));
Owen Andersonbd3ba462008-08-04 23:54:43 +00001641
1642 // If the branch was constant folded, fix up the CFG.
1643 if (BrCond.getOpcode() == ISD::BR) {
Owen Anderson3bc9c6f2008-08-05 18:27:54 +00001644 CurMBB->removeSuccessor(CB.FalseBB);
Nate Begemanf15485a2006-03-27 01:32:24 +00001645 DAG.setRoot(BrCond);
Owen Andersonbd3ba462008-08-04 23:54:43 +00001646 } else {
1647 // Otherwise, go ahead and insert the false branch.
1648 if (BrCond == getControlRoot())
Owen Anderson3bc9c6f2008-08-05 18:27:54 +00001649 CurMBB->removeSuccessor(CB.TrueBB);
Owen Andersonbd3ba462008-08-04 23:54:43 +00001650
1651 if (CB.FalseBB == NextBlock)
1652 DAG.setRoot(BrCond);
1653 else
1654 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond,
1655 DAG.getBasicBlock(CB.FalseBB)));
1656 }
Nate Begemanf15485a2006-03-27 01:32:24 +00001657}
1658
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001659/// visitJumpTable - Emit JumpTable node in the current MBB
Nate Begeman37efe672006-04-22 18:53:45 +00001660void SelectionDAGLowering::visitJumpTable(SelectionDAGISel::JumpTable &JT) {
Nate Begeman37efe672006-04-22 18:53:45 +00001661 // Emit the code for the jump table
Scott Michelf147a8d2007-04-24 01:24:20 +00001662 assert(JT.Reg != -1U && "Should lower JT Header first!");
Duncan Sands83ec4b62008-06-06 12:08:01 +00001663 MVT PTy = TLI.getPointerTy();
Dan Gohman475871a2008-07-27 21:46:04 +00001664 SDValue Index = DAG.getCopyFromReg(getControlRoot(), JT.Reg, PTy);
1665 SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
Evan Cheng3d4ce112006-10-30 08:00:44 +00001666 DAG.setRoot(DAG.getNode(ISD::BR_JT, MVT::Other, Index.getValue(1),
1667 Table, Index));
1668 return;
Nate Begeman37efe672006-04-22 18:53:45 +00001669}
1670
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001671/// visitJumpTableHeader - This function emits necessary code to produce index
1672/// in the JumpTable from switch case.
1673void SelectionDAGLowering::visitJumpTableHeader(SelectionDAGISel::JumpTable &JT,
1674 SelectionDAGISel::JumpTableHeader &JTH) {
1675 // Subtract the lowest switch case value from the value being switched on
1676 // and conditional branch to default mbb if the result is greater than the
1677 // difference between smallest and largest cases.
Dan Gohman475871a2008-07-27 21:46:04 +00001678 SDValue SwitchOp = getValue(JTH.SValue);
Duncan Sands83ec4b62008-06-06 12:08:01 +00001679 MVT VT = SwitchOp.getValueType();
Dan Gohman475871a2008-07-27 21:46:04 +00001680 SDValue SUB = DAG.getNode(ISD::SUB, VT, SwitchOp,
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001681 DAG.getConstant(JTH.First, VT));
1682
1683 // The SDNode we just created, which holds the value being switched on
1684 // minus the the smallest case value, needs to be copied to a virtual
1685 // register so it can be used as an index into the jump table in a
1686 // subsequent basic block. This value may be smaller or larger than the
1687 // target's pointer type, and therefore require extension or truncating.
Duncan Sands8e4eb092008-06-08 20:54:56 +00001688 if (VT.bitsGT(TLI.getPointerTy()))
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001689 SwitchOp = DAG.getNode(ISD::TRUNCATE, TLI.getPointerTy(), SUB);
1690 else
1691 SwitchOp = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(), SUB);
1692
1693 unsigned JumpTableReg = FuncInfo.MakeReg(TLI.getPointerTy());
Dan Gohman475871a2008-07-27 21:46:04 +00001694 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), JumpTableReg, SwitchOp);
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001695 JT.Reg = JumpTableReg;
1696
1697 // Emit the range check for the jump table, and branch to the default
1698 // block for the switch statement if the value being switched on exceeds
1699 // the largest case in the switch.
Dan Gohman475871a2008-07-27 21:46:04 +00001700 SDValue CMP = DAG.getSetCC(TLI.getSetCCResultType(SUB), SUB,
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001701 DAG.getConstant(JTH.Last-JTH.First,VT),
1702 ISD::SETUGT);
1703
1704 // Set NextBlock to be the MBB immediately after the current one, if any.
1705 // This is used to avoid emitting unnecessary branches to the next block.
1706 MachineBasicBlock *NextBlock = 0;
1707 MachineFunction::iterator BBI = CurMBB;
1708 if (++BBI != CurMBB->getParent()->end())
1709 NextBlock = BBI;
1710
Dan Gohman475871a2008-07-27 21:46:04 +00001711 SDValue BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, CopyTo, CMP,
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001712 DAG.getBasicBlock(JT.Default));
1713
1714 if (JT.MBB == NextBlock)
1715 DAG.setRoot(BrCond);
1716 else
1717 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond,
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001718 DAG.getBasicBlock(JT.MBB)));
1719
1720 return;
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001721}
1722
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001723/// visitBitTestHeader - This function emits necessary code to produce value
1724/// suitable for "bit tests"
1725void SelectionDAGLowering::visitBitTestHeader(SelectionDAGISel::BitTestBlock &B) {
1726 // Subtract the minimum value
Dan Gohman475871a2008-07-27 21:46:04 +00001727 SDValue SwitchOp = getValue(B.SValue);
Duncan Sands83ec4b62008-06-06 12:08:01 +00001728 MVT VT = SwitchOp.getValueType();
Dan Gohman475871a2008-07-27 21:46:04 +00001729 SDValue SUB = DAG.getNode(ISD::SUB, VT, SwitchOp,
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001730 DAG.getConstant(B.First, VT));
1731
1732 // Check range
Dan Gohman475871a2008-07-27 21:46:04 +00001733 SDValue RangeCmp = DAG.getSetCC(TLI.getSetCCResultType(SUB), SUB,
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001734 DAG.getConstant(B.Range, VT),
1735 ISD::SETUGT);
1736
Dan Gohman475871a2008-07-27 21:46:04 +00001737 SDValue ShiftOp;
Duncan Sands8e4eb092008-06-08 20:54:56 +00001738 if (VT.bitsGT(TLI.getShiftAmountTy()))
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001739 ShiftOp = DAG.getNode(ISD::TRUNCATE, TLI.getShiftAmountTy(), SUB);
1740 else
1741 ShiftOp = DAG.getNode(ISD::ZERO_EXTEND, TLI.getShiftAmountTy(), SUB);
1742
1743 // Make desired shift
Dan Gohman475871a2008-07-27 21:46:04 +00001744 SDValue SwitchVal = DAG.getNode(ISD::SHL, TLI.getPointerTy(),
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001745 DAG.getConstant(1, TLI.getPointerTy()),
1746 ShiftOp);
1747
1748 unsigned SwitchReg = FuncInfo.MakeReg(TLI.getPointerTy());
Dan Gohman475871a2008-07-27 21:46:04 +00001749 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), SwitchReg, SwitchVal);
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001750 B.Reg = SwitchReg;
1751
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001752 // Set NextBlock to be the MBB immediately after the current one, if any.
1753 // This is used to avoid emitting unnecessary branches to the next block.
1754 MachineBasicBlock *NextBlock = 0;
1755 MachineFunction::iterator BBI = CurMBB;
1756 if (++BBI != CurMBB->getParent()->end())
1757 NextBlock = BBI;
1758
1759 MachineBasicBlock* MBB = B.Cases[0].ThisBB;
Owen Anderson2d389e82008-06-07 00:00:23 +00001760
1761 CurMBB->addSuccessor(B.Default);
1762 CurMBB->addSuccessor(MBB);
1763
Dan Gohman475871a2008-07-27 21:46:04 +00001764 SDValue BrRange = DAG.getNode(ISD::BRCOND, MVT::Other, CopyTo, RangeCmp,
Owen Anderson2d389e82008-06-07 00:00:23 +00001765 DAG.getBasicBlock(B.Default));
1766
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001767 if (MBB == NextBlock)
1768 DAG.setRoot(BrRange);
1769 else
1770 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, CopyTo,
1771 DAG.getBasicBlock(MBB)));
1772
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001773 return;
1774}
1775
1776/// visitBitTestCase - this function produces one "bit test"
1777void SelectionDAGLowering::visitBitTestCase(MachineBasicBlock* NextMBB,
1778 unsigned Reg,
1779 SelectionDAGISel::BitTestCase &B) {
1780 // Emit bit tests and jumps
Dan Gohman475871a2008-07-27 21:46:04 +00001781 SDValue SwitchVal = DAG.getCopyFromReg(getControlRoot(), Reg,
Chris Lattneread0d882008-06-17 06:09:18 +00001782 TLI.getPointerTy());
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001783
Dan Gohman475871a2008-07-27 21:46:04 +00001784 SDValue AndOp = DAG.getNode(ISD::AND, TLI.getPointerTy(), SwitchVal,
Chris Lattneread0d882008-06-17 06:09:18 +00001785 DAG.getConstant(B.Mask, TLI.getPointerTy()));
Dan Gohman475871a2008-07-27 21:46:04 +00001786 SDValue AndCmp = DAG.getSetCC(TLI.getSetCCResultType(AndOp), AndOp,
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001787 DAG.getConstant(0, TLI.getPointerTy()),
1788 ISD::SETNE);
Owen Anderson2d389e82008-06-07 00:00:23 +00001789
1790 CurMBB->addSuccessor(B.TargetBB);
1791 CurMBB->addSuccessor(NextMBB);
1792
Dan Gohman475871a2008-07-27 21:46:04 +00001793 SDValue BrAnd = DAG.getNode(ISD::BRCOND, MVT::Other, getControlRoot(),
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001794 AndCmp, DAG.getBasicBlock(B.TargetBB));
1795
1796 // Set NextBlock to be the MBB immediately after the current one, if any.
1797 // This is used to avoid emitting unnecessary branches to the next block.
1798 MachineBasicBlock *NextBlock = 0;
1799 MachineFunction::iterator BBI = CurMBB;
1800 if (++BBI != CurMBB->getParent()->end())
1801 NextBlock = BBI;
1802
1803 if (NextMBB == NextBlock)
1804 DAG.setRoot(BrAnd);
1805 else
1806 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrAnd,
1807 DAG.getBasicBlock(NextMBB)));
1808
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001809 return;
1810}
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001811
Jim Laskeyb180aa12007-02-21 22:53:45 +00001812void SelectionDAGLowering::visitInvoke(InvokeInst &I) {
1813 // Retrieve successors.
1814 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
Duncan Sandsf19f6bb2007-06-13 05:51:31 +00001815 MachineBasicBlock *LandingPad = FuncInfo.MBBMap[I.getSuccessor(1)];
Duncan Sands9fac0b52007-06-06 10:05:18 +00001816
Duncan Sandsfd7b3262007-12-17 18:08:19 +00001817 if (isa<InlineAsm>(I.getCalledValue()))
1818 visitInlineAsm(&I);
1819 else
Duncan Sands6f74b482007-12-19 09:48:52 +00001820 LowerCallTo(&I, getValue(I.getOperand(0)), false, LandingPad);
Duncan Sands9fac0b52007-06-06 10:05:18 +00001821
Duncan Sandsf19f6bb2007-06-13 05:51:31 +00001822 // If the value of the invoke is used outside of its defining block, make it
1823 // available as a virtual register.
1824 if (!I.use_empty()) {
1825 DenseMap<const Value*, unsigned>::iterator VMI = FuncInfo.ValueMap.find(&I);
1826 if (VMI != FuncInfo.ValueMap.end())
Dan Gohman86e1ebf2008-03-27 19:56:19 +00001827 CopyValueToVirtualRegister(&I, VMI->second);
Jim Laskey183f47f2007-02-25 21:43:59 +00001828 }
Duncan Sandsf19f6bb2007-06-13 05:51:31 +00001829
Duncan Sandsf19f6bb2007-06-13 05:51:31 +00001830 // Update successor info
1831 CurMBB->addSuccessor(Return);
1832 CurMBB->addSuccessor(LandingPad);
Owen Anderson2d389e82008-06-07 00:00:23 +00001833
1834 // Drop into normal successor.
1835 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getControlRoot(),
1836 DAG.getBasicBlock(Return)));
Jim Laskeyb180aa12007-02-21 22:53:45 +00001837}
1838
1839void SelectionDAGLowering::visitUnwind(UnwindInst &I) {
1840}
1841
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001842/// handleSmallSwitchCaseRange - Emit a series of specific tests (suitable for
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001843/// small case ranges).
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001844bool SelectionDAGLowering::handleSmallSwitchRange(CaseRec& CR,
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001845 CaseRecVector& WorkList,
1846 Value* SV,
1847 MachineBasicBlock* Default) {
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001848 Case& BackCase = *(CR.Range.second-1);
1849
1850 // Size is the number of Cases represented by this range.
1851 unsigned Size = CR.Range.second - CR.Range.first;
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001852 if (Size > 3)
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001853 return false;
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001854
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001855 // Get the MachineFunction which holds the current MBB. This is used when
1856 // inserting any additional MBBs necessary to represent the switch.
1857 MachineFunction *CurMF = CurMBB->getParent();
1858
1859 // Figure out which block is immediately after the current one.
1860 MachineBasicBlock *NextBlock = 0;
1861 MachineFunction::iterator BBI = CR.CaseBB;
1862
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001863 if (++BBI != CurMBB->getParent()->end())
1864 NextBlock = BBI;
1865
1866 // TODO: If any two of the cases has the same destination, and if one value
1867 // is the same as the other, but has one bit unset that the other has set,
1868 // use bit manipulation to do two compares at once. For example:
1869 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
1870
1871 // Rearrange the case blocks so that the last one falls through if possible.
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001872 if (NextBlock && Default != NextBlock && BackCase.BB != NextBlock) {
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001873 // The last case block won't fall through into 'NextBlock' if we emit the
1874 // branches in this order. See if rearranging a case value would help.
1875 for (CaseItr I = CR.Range.first, E = CR.Range.second-1; I != E; ++I) {
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001876 if (I->BB == NextBlock) {
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001877 std::swap(*I, BackCase);
1878 break;
1879 }
1880 }
1881 }
1882
1883 // Create a CaseBlock record representing a conditional branch to
1884 // the Case's target mbb if the value being switched on SV is equal
1885 // to C.
1886 MachineBasicBlock *CurBlock = CR.CaseBB;
1887 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I) {
1888 MachineBasicBlock *FallThrough;
1889 if (I != E-1) {
Dan Gohman0e5f1302008-07-07 23:02:41 +00001890 FallThrough = CurMF->CreateMachineBasicBlock(CurBlock->getBasicBlock());
1891 CurMF->insert(BBI, FallThrough);
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001892 } else {
1893 // If the last case doesn't match, go to the default block.
1894 FallThrough = Default;
1895 }
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001896
1897 Value *RHS, *LHS, *MHS;
1898 ISD::CondCode CC;
1899 if (I->High == I->Low) {
1900 // This is just small small case range :) containing exactly 1 case
1901 CC = ISD::SETEQ;
1902 LHS = SV; RHS = I->High; MHS = NULL;
1903 } else {
1904 CC = ISD::SETLE;
1905 LHS = I->Low; MHS = SV; RHS = I->High;
1906 }
1907 SelectionDAGISel::CaseBlock CB(CC, LHS, RHS, MHS,
1908 I->BB, FallThrough, CurBlock);
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001909
1910 // If emitting the first comparison, just call visitSwitchCase to emit the
1911 // code into the current block. Otherwise, push the CaseBlock onto the
1912 // vector to be later processed by SDISel, and insert the node's MBB
1913 // before the next MBB.
1914 if (CurBlock == CurMBB)
1915 visitSwitchCase(CB);
1916 else
1917 SwitchCases.push_back(CB);
1918
1919 CurBlock = FallThrough;
1920 }
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001921
1922 return true;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001923}
1924
Anton Korobeynikov7294b582007-05-09 20:07:08 +00001925static inline bool areJTsAllowed(const TargetLowering &TLI) {
Dale Johannesen72324642008-07-31 18:13:12 +00001926 return !DisableJumpTables &&
1927 (TLI.isOperationLegal(ISD::BR_JT, MVT::Other) ||
1928 TLI.isOperationLegal(ISD::BRIND, MVT::Other));
Anton Korobeynikov7294b582007-05-09 20:07:08 +00001929}
1930
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001931/// handleJTSwitchCase - Emit jumptable for current switch case range
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001932bool SelectionDAGLowering::handleJTSwitchCase(CaseRec& CR,
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001933 CaseRecVector& WorkList,
1934 Value* SV,
1935 MachineBasicBlock* Default) {
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001936 Case& FrontCase = *CR.Range.first;
1937 Case& BackCase = *(CR.Range.second-1);
1938
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001939 int64_t First = cast<ConstantInt>(FrontCase.Low)->getSExtValue();
1940 int64_t Last = cast<ConstantInt>(BackCase.High)->getSExtValue();
1941
1942 uint64_t TSize = 0;
1943 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1944 I!=E; ++I)
1945 TSize += I->size();
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001946
Anton Korobeynikov7294b582007-05-09 20:07:08 +00001947 if (!areJTsAllowed(TLI) || TSize <= 3)
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001948 return false;
1949
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001950 double Density = (double)TSize / (double)((Last - First) + 1ULL);
1951 if (Density < 0.4)
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001952 return false;
1953
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001954 DOUT << "Lowering jump table\n"
1955 << "First entry: " << First << ". Last entry: " << Last << "\n"
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001956 << "Size: " << TSize << ". Density: " << Density << "\n\n";
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001957
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001958 // Get the MachineFunction which holds the current MBB. This is used when
1959 // inserting any additional MBBs necessary to represent the switch.
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001960 MachineFunction *CurMF = CurMBB->getParent();
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001961
1962 // Figure out which block is immediately after the current one.
1963 MachineBasicBlock *NextBlock = 0;
1964 MachineFunction::iterator BBI = CR.CaseBB;
1965
1966 if (++BBI != CurMBB->getParent()->end())
1967 NextBlock = BBI;
1968
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001969 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1970
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001971 // Create a new basic block to hold the code for loading the address
1972 // of the jump table, and jumping to it. Update successor information;
1973 // we will either branch to the default case for the switch, or the jump
1974 // table.
Dan Gohman0e5f1302008-07-07 23:02:41 +00001975 MachineBasicBlock *JumpTableBB = CurMF->CreateMachineBasicBlock(LLVMBB);
1976 CurMF->insert(BBI, JumpTableBB);
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001977 CR.CaseBB->addSuccessor(Default);
1978 CR.CaseBB->addSuccessor(JumpTableBB);
1979
1980 // Build a vector of destination BBs, corresponding to each target
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001981 // of the jump table. If the value of the jump table slot corresponds to
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001982 // a case statement, push the case's BB onto the vector, otherwise, push
1983 // the default BB.
1984 std::vector<MachineBasicBlock*> DestBBs;
1985 int64_t TEI = First;
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001986 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++TEI) {
1987 int64_t Low = cast<ConstantInt>(I->Low)->getSExtValue();
1988 int64_t High = cast<ConstantInt>(I->High)->getSExtValue();
1989
1990 if ((Low <= TEI) && (TEI <= High)) {
1991 DestBBs.push_back(I->BB);
1992 if (TEI==High)
1993 ++I;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001994 } else {
1995 DestBBs.push_back(Default);
1996 }
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001997 }
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001998
1999 // Update successor info. Add one edge to each unique successor.
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002000 BitVector SuccsHandled(CR.CaseBB->getParent()->getNumBlockIDs());
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00002001 for (std::vector<MachineBasicBlock*>::iterator I = DestBBs.begin(),
2002 E = DestBBs.end(); I != E; ++I) {
2003 if (!SuccsHandled[(*I)->getNumber()]) {
2004 SuccsHandled[(*I)->getNumber()] = true;
2005 JumpTableBB->addSuccessor(*I);
2006 }
2007 }
2008
2009 // Create a jump table index for this jump table, or return an existing
2010 // one.
2011 unsigned JTI = CurMF->getJumpTableInfo()->getJumpTableIndex(DestBBs);
2012
2013 // Set the jump table information so that we can codegen it as a second
2014 // MachineBasicBlock
Scott Michelf147a8d2007-04-24 01:24:20 +00002015 SelectionDAGISel::JumpTable JT(-1U, JTI, JumpTableBB, Default);
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00002016 SelectionDAGISel::JumpTableHeader JTH(First, Last, SV, CR.CaseBB,
2017 (CR.CaseBB == CurMBB));
2018 if (CR.CaseBB == CurMBB)
2019 visitJumpTableHeader(JT, JTH);
2020
2021 JTCases.push_back(SelectionDAGISel::JumpTableBlock(JTH, JT));
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00002022
Anton Korobeynikovdd433212007-03-27 12:05:48 +00002023 return true;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00002024}
2025
2026/// handleBTSplitSwitchCase - emit comparison and split binary search tree into
2027/// 2 subtrees.
Anton Korobeynikovdd433212007-03-27 12:05:48 +00002028bool SelectionDAGLowering::handleBTSplitSwitchCase(CaseRec& CR,
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00002029 CaseRecVector& WorkList,
2030 Value* SV,
2031 MachineBasicBlock* Default) {
2032 // Get the MachineFunction which holds the current MBB. This is used when
2033 // inserting any additional MBBs necessary to represent the switch.
2034 MachineFunction *CurMF = CurMBB->getParent();
2035
2036 // Figure out which block is immediately after the current one.
2037 MachineBasicBlock *NextBlock = 0;
2038 MachineFunction::iterator BBI = CR.CaseBB;
2039
2040 if (++BBI != CurMBB->getParent()->end())
2041 NextBlock = BBI;
2042
2043 Case& FrontCase = *CR.Range.first;
2044 Case& BackCase = *(CR.Range.second-1);
2045 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
2046
2047 // Size is the number of Cases represented by this range.
2048 unsigned Size = CR.Range.second - CR.Range.first;
2049
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002050 int64_t First = cast<ConstantInt>(FrontCase.Low)->getSExtValue();
2051 int64_t Last = cast<ConstantInt>(BackCase.High)->getSExtValue();
Anton Korobeynikov4198c582007-04-09 12:31:58 +00002052 double FMetric = 0;
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002053 CaseItr Pivot = CR.Range.first + Size/2;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00002054
2055 // Select optimal pivot, maximizing sum density of LHS and RHS. This will
2056 // (heuristically) allow us to emit JumpTable's later.
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002057 uint64_t TSize = 0;
2058 for (CaseItr I = CR.Range.first, E = CR.Range.second;
2059 I!=E; ++I)
2060 TSize += I->size();
2061
2062 uint64_t LSize = FrontCase.size();
2063 uint64_t RSize = TSize-LSize;
Anton Korobeynikov4198c582007-04-09 12:31:58 +00002064 DOUT << "Selecting best pivot: \n"
2065 << "First: " << First << ", Last: " << Last <<"\n"
2066 << "LSize: " << LSize << ", RSize: " << RSize << "\n";
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00002067 for (CaseItr I = CR.Range.first, J=I+1, E = CR.Range.second;
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002068 J!=E; ++I, ++J) {
2069 int64_t LEnd = cast<ConstantInt>(I->High)->getSExtValue();
2070 int64_t RBegin = cast<ConstantInt>(J->Low)->getSExtValue();
Anton Korobeynikov4198c582007-04-09 12:31:58 +00002071 assert((RBegin-LEnd>=1) && "Invalid case distance");
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00002072 double LDensity = (double)LSize / (double)((LEnd - First) + 1ULL);
2073 double RDensity = (double)RSize / (double)((Last - RBegin) + 1ULL);
Anton Korobeynikov54e2b142007-04-09 21:57:03 +00002074 double Metric = Log2_64(RBegin-LEnd)*(LDensity+RDensity);
Anton Korobeynikov4198c582007-04-09 12:31:58 +00002075 // Should always split in some non-trivial place
2076 DOUT <<"=>Step\n"
2077 << "LEnd: " << LEnd << ", RBegin: " << RBegin << "\n"
2078 << "LDensity: " << LDensity << ", RDensity: " << RDensity << "\n"
2079 << "Metric: " << Metric << "\n";
2080 if (FMetric < Metric) {
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00002081 Pivot = J;
Anton Korobeynikov4198c582007-04-09 12:31:58 +00002082 FMetric = Metric;
2083 DOUT << "Current metric set to: " << FMetric << "\n";
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00002084 }
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002085
2086 LSize += J->size();
2087 RSize -= J->size();
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00002088 }
Anton Korobeynikov7294b582007-05-09 20:07:08 +00002089 if (areJTsAllowed(TLI)) {
2090 // If our case is dense we *really* should handle it earlier!
2091 assert((FMetric > 0) && "Should handle dense range earlier!");
2092 } else {
2093 Pivot = CR.Range.first + Size/2;
2094 }
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00002095
2096 CaseRange LHSR(CR.Range.first, Pivot);
2097 CaseRange RHSR(Pivot, CR.Range.second);
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002098 Constant *C = Pivot->Low;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00002099 MachineBasicBlock *FalseBB = 0, *TrueBB = 0;
2100
2101 // We know that we branch to the LHS if the Value being switched on is
2102 // less than the Pivot value, C. We use this to optimize our binary
2103 // tree a bit, by recognizing that if SV is greater than or equal to the
2104 // LHS's Case Value, and that Case Value is exactly one less than the
2105 // Pivot's Value, then we can branch directly to the LHS's Target,
2106 // rather than creating a leaf node for it.
2107 if ((LHSR.second - LHSR.first) == 1 &&
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002108 LHSR.first->High == CR.GE &&
2109 cast<ConstantInt>(C)->getSExtValue() ==
2110 (cast<ConstantInt>(CR.GE)->getSExtValue() + 1LL)) {
2111 TrueBB = LHSR.first->BB;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00002112 } else {
Dan Gohman0e5f1302008-07-07 23:02:41 +00002113 TrueBB = CurMF->CreateMachineBasicBlock(LLVMBB);
2114 CurMF->insert(BBI, TrueBB);
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00002115 WorkList.push_back(CaseRec(TrueBB, C, CR.GE, LHSR));
2116 }
2117
2118 // Similar to the optimization above, if the Value being switched on is
2119 // known to be less than the Constant CR.LT, and the current Case Value
2120 // is CR.LT - 1, then we can branch directly to the target block for
2121 // the current Case Value, rather than emitting a RHS leaf node for it.
2122 if ((RHSR.second - RHSR.first) == 1 && CR.LT &&
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002123 cast<ConstantInt>(RHSR.first->Low)->getSExtValue() ==
2124 (cast<ConstantInt>(CR.LT)->getSExtValue() - 1LL)) {
2125 FalseBB = RHSR.first->BB;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00002126 } else {
Dan Gohman0e5f1302008-07-07 23:02:41 +00002127 FalseBB = CurMF->CreateMachineBasicBlock(LLVMBB);
2128 CurMF->insert(BBI, FalseBB);
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00002129 WorkList.push_back(CaseRec(FalseBB,CR.LT,C,RHSR));
2130 }
2131
2132 // Create a CaseBlock record representing a conditional branch to
2133 // the LHS node if the value being switched on SV is less than C.
2134 // Otherwise, branch to LHS.
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002135 SelectionDAGISel::CaseBlock CB(ISD::SETLT, SV, C, NULL,
2136 TrueBB, FalseBB, CR.CaseBB);
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00002137
2138 if (CR.CaseBB == CurMBB)
2139 visitSwitchCase(CB);
2140 else
2141 SwitchCases.push_back(CB);
Anton Korobeynikovdd433212007-03-27 12:05:48 +00002142
2143 return true;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00002144}
2145
Anton Korobeynikov4198c582007-04-09 12:31:58 +00002146/// handleBitTestsSwitchCase - if current case range has few destination and
2147/// range span less, than machine word bitwidth, encode case range into series
2148/// of masks and emit bit tests with these masks.
2149bool SelectionDAGLowering::handleBitTestsSwitchCase(CaseRec& CR,
2150 CaseRecVector& WorkList,
2151 Value* SV,
Chris Lattner3ff98172007-04-14 02:26:56 +00002152 MachineBasicBlock* Default){
Duncan Sands83ec4b62008-06-06 12:08:01 +00002153 unsigned IntPtrBits = TLI.getPointerTy().getSizeInBits();
Anton Korobeynikov4198c582007-04-09 12:31:58 +00002154
2155 Case& FrontCase = *CR.Range.first;
2156 Case& BackCase = *(CR.Range.second-1);
2157
2158 // Get the MachineFunction which holds the current MBB. This is used when
2159 // inserting any additional MBBs necessary to represent the switch.
2160 MachineFunction *CurMF = CurMBB->getParent();
2161
2162 unsigned numCmps = 0;
2163 for (CaseItr I = CR.Range.first, E = CR.Range.second;
2164 I!=E; ++I) {
2165 // Single case counts one, case range - two.
2166 if (I->Low == I->High)
2167 numCmps +=1;
2168 else
2169 numCmps +=2;
2170 }
2171
2172 // Count unique destinations
2173 SmallSet<MachineBasicBlock*, 4> Dests;
2174 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
2175 Dests.insert(I->BB);
2176 if (Dests.size() > 3)
2177 // Don't bother the code below, if there are too much unique destinations
2178 return false;
2179 }
2180 DOUT << "Total number of unique destinations: " << Dests.size() << "\n"
2181 << "Total number of comparisons: " << numCmps << "\n";
2182
2183 // Compute span of values.
2184 Constant* minValue = FrontCase.Low;
2185 Constant* maxValue = BackCase.High;
2186 uint64_t range = cast<ConstantInt>(maxValue)->getSExtValue() -
2187 cast<ConstantInt>(minValue)->getSExtValue();
2188 DOUT << "Compare range: " << range << "\n"
2189 << "Low bound: " << cast<ConstantInt>(minValue)->getSExtValue() << "\n"
2190 << "High bound: " << cast<ConstantInt>(maxValue)->getSExtValue() << "\n";
2191
Anton Korobeynikovab8fd402007-04-26 20:44:04 +00002192 if (range>=IntPtrBits ||
Anton Korobeynikov4198c582007-04-09 12:31:58 +00002193 (!(Dests.size() == 1 && numCmps >= 3) &&
2194 !(Dests.size() == 2 && numCmps >= 5) &&
2195 !(Dests.size() >= 3 && numCmps >= 6)))
2196 return false;
2197
2198 DOUT << "Emitting bit tests\n";
2199 int64_t lowBound = 0;
2200
2201 // Optimize the case where all the case values fit in a
2202 // word without having to subtract minValue. In this case,
2203 // we can optimize away the subtraction.
2204 if (cast<ConstantInt>(minValue)->getSExtValue() >= 0 &&
Anton Korobeynikove01017b2007-04-14 13:25:55 +00002205 cast<ConstantInt>(maxValue)->getSExtValue() < IntPtrBits) {
Anton Korobeynikov4198c582007-04-09 12:31:58 +00002206 range = cast<ConstantInt>(maxValue)->getSExtValue();
2207 } else {
2208 lowBound = cast<ConstantInt>(minValue)->getSExtValue();
2209 }
2210
2211 CaseBitsVector CasesBits;
2212 unsigned i, count = 0;
2213
2214 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
2215 MachineBasicBlock* Dest = I->BB;
2216 for (i = 0; i < count; ++i)
2217 if (Dest == CasesBits[i].BB)
2218 break;
2219
2220 if (i == count) {
2221 assert((count < 3) && "Too much destinations to test!");
2222 CasesBits.push_back(CaseBits(0, Dest, 0));
2223 count++;
2224 }
2225
2226 uint64_t lo = cast<ConstantInt>(I->Low)->getSExtValue() - lowBound;
2227 uint64_t hi = cast<ConstantInt>(I->High)->getSExtValue() - lowBound;
2228
2229 for (uint64_t j = lo; j <= hi; j++) {
Anton Korobeynikove01017b2007-04-14 13:25:55 +00002230 CasesBits[i].Mask |= 1ULL << j;
Anton Korobeynikov4198c582007-04-09 12:31:58 +00002231 CasesBits[i].Bits++;
2232 }
2233
2234 }
2235 std::sort(CasesBits.begin(), CasesBits.end(), CaseBitsCmp());
2236
2237 SelectionDAGISel::BitTestInfo BTC;
2238
2239 // Figure out which block is immediately after the current one.
2240 MachineFunction::iterator BBI = CR.CaseBB;
2241 ++BBI;
2242
2243 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
2244
2245 DOUT << "Cases:\n";
2246 for (unsigned i = 0, e = CasesBits.size(); i!=e; ++i) {
2247 DOUT << "Mask: " << CasesBits[i].Mask << ", Bits: " << CasesBits[i].Bits
2248 << ", BB: " << CasesBits[i].BB << "\n";
2249
Dan Gohman0e5f1302008-07-07 23:02:41 +00002250 MachineBasicBlock *CaseBB = CurMF->CreateMachineBasicBlock(LLVMBB);
2251 CurMF->insert(BBI, CaseBB);
Anton Korobeynikov4198c582007-04-09 12:31:58 +00002252 BTC.push_back(SelectionDAGISel::BitTestCase(CasesBits[i].Mask,
2253 CaseBB,
2254 CasesBits[i].BB));
2255 }
2256
2257 SelectionDAGISel::BitTestBlock BTB(lowBound, range, SV,
Jeff Cohenefc36622007-04-09 14:32:59 +00002258 -1U, (CR.CaseBB == CurMBB),
Anton Korobeynikov4198c582007-04-09 12:31:58 +00002259 CR.CaseBB, Default, BTC);
2260
2261 if (CR.CaseBB == CurMBB)
2262 visitBitTestHeader(BTB);
2263
2264 BitTestCases.push_back(BTB);
2265
2266 return true;
2267}
2268
2269
Dan Gohman86e1ebf2008-03-27 19:56:19 +00002270/// Clusterify - Transform simple list of Cases into list of CaseRange's
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002271unsigned SelectionDAGLowering::Clusterify(CaseVector& Cases,
2272 const SwitchInst& SI) {
2273 unsigned numCmps = 0;
2274
2275 // Start with "simple" cases
2276 for (unsigned i = 1; i < SI.getNumSuccessors(); ++i) {
2277 MachineBasicBlock *SMBB = FuncInfo.MBBMap[SI.getSuccessor(i)];
2278 Cases.push_back(Case(SI.getSuccessorValue(i),
2279 SI.getSuccessorValue(i),
2280 SMBB));
2281 }
Chris Lattnerb3d9cdb2007-11-27 06:14:32 +00002282 std::sort(Cases.begin(), Cases.end(), CaseCmp());
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002283
2284 // Merge case into clusters
2285 if (Cases.size()>=2)
David Greenea2a48852007-06-29 03:42:23 +00002286 // Must recompute end() each iteration because it may be
2287 // invalidated by erase if we hold on to it
Chris Lattner27a6c732007-11-24 07:07:01 +00002288 for (CaseItr I=Cases.begin(), J=++(Cases.begin()); J!=Cases.end(); ) {
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002289 int64_t nextValue = cast<ConstantInt>(J->Low)->getSExtValue();
2290 int64_t currentValue = cast<ConstantInt>(I->High)->getSExtValue();
2291 MachineBasicBlock* nextBB = J->BB;
2292 MachineBasicBlock* currentBB = I->BB;
2293
2294 // If the two neighboring cases go to the same destination, merge them
2295 // into a single case.
2296 if ((nextValue-currentValue==1) && (currentBB == nextBB)) {
2297 I->High = J->High;
2298 J = Cases.erase(J);
2299 } else {
2300 I = J++;
2301 }
2302 }
2303
2304 for (CaseItr I=Cases.begin(), E=Cases.end(); I!=E; ++I, ++numCmps) {
2305 if (I->Low != I->High)
2306 // A range counts double, since it requires two compares.
2307 ++numCmps;
2308 }
2309
2310 return numCmps;
2311}
2312
2313void SelectionDAGLowering::visitSwitch(SwitchInst &SI) {
Nate Begemanf15485a2006-03-27 01:32:24 +00002314 // Figure out which block is immediately after the current one.
2315 MachineBasicBlock *NextBlock = 0;
2316 MachineFunction::iterator BBI = CurMBB;
Bill Wendlingc70ddad2006-10-19 21:46:38 +00002317
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002318 MachineBasicBlock *Default = FuncInfo.MBBMap[SI.getDefaultDest()];
Chris Lattnerd2c1d222006-10-22 21:36:53 +00002319
Nate Begemanf15485a2006-03-27 01:32:24 +00002320 // If there is only the default destination, branch to it if it is not the
2321 // next basic block. Otherwise, just fall through.
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002322 if (SI.getNumOperands() == 2) {
Nate Begemanf15485a2006-03-27 01:32:24 +00002323 // Update machine-CFG edges.
Bill Wendlingc70ddad2006-10-19 21:46:38 +00002324
Nate Begemanf15485a2006-03-27 01:32:24 +00002325 // If this is not a fall-through branch, emit the branch.
Owen Anderson2d389e82008-06-07 00:00:23 +00002326 CurMBB->addSuccessor(Default);
Chris Lattnerd2c1d222006-10-22 21:36:53 +00002327 if (Default != NextBlock)
Dan Gohman86e1ebf2008-03-27 19:56:19 +00002328 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getControlRoot(),
Chris Lattnerd2c1d222006-10-22 21:36:53 +00002329 DAG.getBasicBlock(Default)));
Owen Anderson2d389e82008-06-07 00:00:23 +00002330
Nate Begemanf15485a2006-03-27 01:32:24 +00002331 return;
2332 }
2333
2334 // If there are any non-default case statements, create a vector of Cases
2335 // representing each one, and sort the vector so that we can efficiently
2336 // create a binary search tree from them.
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002337 CaseVector Cases;
2338 unsigned numCmps = Clusterify(Cases, SI);
2339 DOUT << "Clusterify finished. Total clusters: " << Cases.size()
2340 << ". Total compares: " << numCmps << "\n";
Bill Wendlingc70ddad2006-10-19 21:46:38 +00002341
Nate Begemanf15485a2006-03-27 01:32:24 +00002342 // Get the Value to be switched on and default basic blocks, which will be
2343 // inserted into CaseBlock records, representing basic blocks in the binary
2344 // search tree.
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002345 Value *SV = SI.getOperand(0);
Nate Begeman37efe672006-04-22 18:53:45 +00002346
Nate Begemanf15485a2006-03-27 01:32:24 +00002347 // Push the initial CaseRec onto the worklist
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00002348 CaseRecVector WorkList;
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00002349 WorkList.push_back(CaseRec(CurMBB,0,0,CaseRange(Cases.begin(),Cases.end())));
2350
2351 while (!WorkList.empty()) {
Nate Begemanf15485a2006-03-27 01:32:24 +00002352 // Grab a record representing a case range to process off the worklist
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00002353 CaseRec CR = WorkList.back();
2354 WorkList.pop_back();
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00002355
Anton Korobeynikov4198c582007-04-09 12:31:58 +00002356 if (handleBitTestsSwitchCase(CR, WorkList, SV, Default))
2357 continue;
2358
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00002359 // If the range has few cases (two or less) emit a series of specific
2360 // tests.
Anton Korobeynikovdd433212007-03-27 12:05:48 +00002361 if (handleSmallSwitchRange(CR, WorkList, SV, Default))
2362 continue;
2363
Anton Korobeynikov4198c582007-04-09 12:31:58 +00002364 // If the switch has more than 5 blocks, and at least 40% dense, and the
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00002365 // target supports indirect branches, then emit a jump table rather than
2366 // lowering the switch to a binary tree of conditional branches.
Anton Korobeynikovdd433212007-03-27 12:05:48 +00002367 if (handleJTSwitchCase(CR, WorkList, SV, Default))
2368 continue;
2369
2370 // Emit binary tree. We need to pick a pivot, and push left and right ranges
2371 // onto the worklist. Leafs are handled via handleSmallSwitchRange() call.
2372 handleBTSplitSwitchCase(CR, WorkList, SV, Default);
Nate Begemanf15485a2006-03-27 01:32:24 +00002373 }
2374}
2375
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00002376
Chris Lattnerb9fccc42005-04-02 05:04:50 +00002377void SelectionDAGLowering::visitSub(User &I) {
2378 // -0.0 - X --> fneg
Reid Spencer24d6da52007-01-21 00:29:26 +00002379 const Type *Ty = I.getType();
Reid Spencer9d6565a2007-02-15 02:26:10 +00002380 if (isa<VectorType>(Ty)) {
Dan Gohman7f321562007-06-25 16:23:39 +00002381 if (ConstantVector *CV = dyn_cast<ConstantVector>(I.getOperand(0))) {
2382 const VectorType *DestTy = cast<VectorType>(I.getType());
2383 const Type *ElTy = DestTy->getElementType();
Evan Chengc45453f2007-06-29 21:44:35 +00002384 if (ElTy->isFloatingPoint()) {
2385 unsigned VL = DestTy->getNumElements();
Dale Johannesen9e3d3ab2007-09-14 22:26:36 +00002386 std::vector<Constant*> NZ(VL, ConstantFP::getNegativeZero(ElTy));
Evan Chengc45453f2007-06-29 21:44:35 +00002387 Constant *CNZ = ConstantVector::get(&NZ[0], NZ.size());
2388 if (CV == CNZ) {
Dan Gohman475871a2008-07-27 21:46:04 +00002389 SDValue Op2 = getValue(I.getOperand(1));
Evan Chengc45453f2007-06-29 21:44:35 +00002390 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
2391 return;
2392 }
Dan Gohman7f321562007-06-25 16:23:39 +00002393 }
2394 }
2395 }
2396 if (Ty->isFloatingPoint()) {
Chris Lattner01b3d732005-09-28 22:28:18 +00002397 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
Dale Johannesen9e3d3ab2007-09-14 22:26:36 +00002398 if (CFP->isExactlyValue(ConstantFP::getNegativeZero(Ty)->getValueAPF())) {
Dan Gohman475871a2008-07-27 21:46:04 +00002399 SDValue Op2 = getValue(I.getOperand(1));
Chris Lattner01b3d732005-09-28 22:28:18 +00002400 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
2401 return;
2402 }
Dan Gohman7f321562007-06-25 16:23:39 +00002403 }
2404
2405 visitBinary(I, Ty->isFPOrFPVector() ? ISD::FSUB : ISD::SUB);
Chris Lattnerb9fccc42005-04-02 05:04:50 +00002406}
2407
Dan Gohman7f321562007-06-25 16:23:39 +00002408void SelectionDAGLowering::visitBinary(User &I, unsigned OpCode) {
Dan Gohman475871a2008-07-27 21:46:04 +00002409 SDValue Op1 = getValue(I.getOperand(0));
2410 SDValue Op2 = getValue(I.getOperand(1));
Reid Spencer24d6da52007-01-21 00:29:26 +00002411
2412 setValue(&I, DAG.getNode(OpCode, Op1.getValueType(), Op1, Op2));
Reid Spencer1628cec2006-10-26 06:15:43 +00002413}
2414
Nate Begemane21ea612005-11-18 07:42:56 +00002415void SelectionDAGLowering::visitShift(User &I, unsigned Opcode) {
Dan Gohman475871a2008-07-27 21:46:04 +00002416 SDValue Op1 = getValue(I.getOperand(0));
2417 SDValue Op2 = getValue(I.getOperand(1));
Nate Begeman5bc1ea02008-07-29 15:49:41 +00002418 if (!isa<VectorType>(I.getType())) {
2419 if (TLI.getShiftAmountTy().bitsLT(Op2.getValueType()))
2420 Op2 = DAG.getNode(ISD::TRUNCATE, TLI.getShiftAmountTy(), Op2);
2421 else if (TLI.getShiftAmountTy().bitsGT(Op2.getValueType()))
2422 Op2 = DAG.getNode(ISD::ANY_EXTEND, TLI.getShiftAmountTy(), Op2);
2423 }
Nate Begemane21ea612005-11-18 07:42:56 +00002424
Chris Lattner1c08c712005-01-07 07:47:53 +00002425 setValue(&I, DAG.getNode(Opcode, Op1.getValueType(), Op1, Op2));
2426}
2427
Reid Spencer45fb3f32006-11-20 01:22:35 +00002428void SelectionDAGLowering::visitICmp(User &I) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002429 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
2430 if (ICmpInst *IC = dyn_cast<ICmpInst>(&I))
2431 predicate = IC->getPredicate();
2432 else if (ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
2433 predicate = ICmpInst::Predicate(IC->getPredicate());
Dan Gohman475871a2008-07-27 21:46:04 +00002434 SDValue Op1 = getValue(I.getOperand(0));
2435 SDValue Op2 = getValue(I.getOperand(1));
Reid Spencer45fb3f32006-11-20 01:22:35 +00002436 ISD::CondCode Opcode;
Reid Spencere4d87aa2006-12-23 06:05:41 +00002437 switch (predicate) {
Reid Spencer45fb3f32006-11-20 01:22:35 +00002438 case ICmpInst::ICMP_EQ : Opcode = ISD::SETEQ; break;
2439 case ICmpInst::ICMP_NE : Opcode = ISD::SETNE; break;
2440 case ICmpInst::ICMP_UGT : Opcode = ISD::SETUGT; break;
2441 case ICmpInst::ICMP_UGE : Opcode = ISD::SETUGE; break;
2442 case ICmpInst::ICMP_ULT : Opcode = ISD::SETULT; break;
2443 case ICmpInst::ICMP_ULE : Opcode = ISD::SETULE; break;
2444 case ICmpInst::ICMP_SGT : Opcode = ISD::SETGT; break;
2445 case ICmpInst::ICMP_SGE : Opcode = ISD::SETGE; break;
2446 case ICmpInst::ICMP_SLT : Opcode = ISD::SETLT; break;
2447 case ICmpInst::ICMP_SLE : Opcode = ISD::SETLE; break;
2448 default:
2449 assert(!"Invalid ICmp predicate value");
2450 Opcode = ISD::SETEQ;
2451 break;
2452 }
2453 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Opcode));
2454}
2455
2456void SelectionDAGLowering::visitFCmp(User &I) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002457 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
2458 if (FCmpInst *FC = dyn_cast<FCmpInst>(&I))
2459 predicate = FC->getPredicate();
2460 else if (ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
2461 predicate = FCmpInst::Predicate(FC->getPredicate());
Dan Gohman475871a2008-07-27 21:46:04 +00002462 SDValue Op1 = getValue(I.getOperand(0));
2463 SDValue Op2 = getValue(I.getOperand(1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00002464 ISD::CondCode Condition, FOC, FPC;
2465 switch (predicate) {
2466 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
2467 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
2468 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
2469 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
2470 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
2471 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
2472 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
Dan Gohmancba3b442008-05-01 23:40:44 +00002473 case FCmpInst::FCMP_ORD: FOC = FPC = ISD::SETO; break;
2474 case FCmpInst::FCMP_UNO: FOC = FPC = ISD::SETUO; break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00002475 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
2476 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
2477 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
2478 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
2479 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
2480 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
2481 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
2482 default:
2483 assert(!"Invalid FCmp predicate value");
2484 FOC = FPC = ISD::SETFALSE;
2485 break;
2486 }
2487 if (FiniteOnlyFPMath())
2488 Condition = FOC;
2489 else
2490 Condition = FPC;
2491 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Condition));
Chris Lattner1c08c712005-01-07 07:47:53 +00002492}
2493
Nate Begemanb43e9c12008-05-12 19:40:03 +00002494void SelectionDAGLowering::visitVICmp(User &I) {
2495 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
2496 if (VICmpInst *IC = dyn_cast<VICmpInst>(&I))
2497 predicate = IC->getPredicate();
2498 else if (ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
2499 predicate = ICmpInst::Predicate(IC->getPredicate());
Dan Gohman475871a2008-07-27 21:46:04 +00002500 SDValue Op1 = getValue(I.getOperand(0));
2501 SDValue Op2 = getValue(I.getOperand(1));
Nate Begemanb43e9c12008-05-12 19:40:03 +00002502 ISD::CondCode Opcode;
2503 switch (predicate) {
2504 case ICmpInst::ICMP_EQ : Opcode = ISD::SETEQ; break;
2505 case ICmpInst::ICMP_NE : Opcode = ISD::SETNE; break;
2506 case ICmpInst::ICMP_UGT : Opcode = ISD::SETUGT; break;
2507 case ICmpInst::ICMP_UGE : Opcode = ISD::SETUGE; break;
2508 case ICmpInst::ICMP_ULT : Opcode = ISD::SETULT; break;
2509 case ICmpInst::ICMP_ULE : Opcode = ISD::SETULE; break;
2510 case ICmpInst::ICMP_SGT : Opcode = ISD::SETGT; break;
2511 case ICmpInst::ICMP_SGE : Opcode = ISD::SETGE; break;
2512 case ICmpInst::ICMP_SLT : Opcode = ISD::SETLT; break;
2513 case ICmpInst::ICMP_SLE : Opcode = ISD::SETLE; break;
2514 default:
2515 assert(!"Invalid ICmp predicate value");
2516 Opcode = ISD::SETEQ;
2517 break;
2518 }
2519 setValue(&I, DAG.getVSetCC(Op1.getValueType(), Op1, Op2, Opcode));
2520}
2521
2522void SelectionDAGLowering::visitVFCmp(User &I) {
2523 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
2524 if (VFCmpInst *FC = dyn_cast<VFCmpInst>(&I))
2525 predicate = FC->getPredicate();
2526 else if (ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
2527 predicate = FCmpInst::Predicate(FC->getPredicate());
Dan Gohman475871a2008-07-27 21:46:04 +00002528 SDValue Op1 = getValue(I.getOperand(0));
2529 SDValue Op2 = getValue(I.getOperand(1));
Nate Begemanb43e9c12008-05-12 19:40:03 +00002530 ISD::CondCode Condition, FOC, FPC;
2531 switch (predicate) {
2532 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
2533 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
2534 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
2535 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
2536 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
2537 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
2538 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
2539 case FCmpInst::FCMP_ORD: FOC = FPC = ISD::SETO; break;
2540 case FCmpInst::FCMP_UNO: FOC = FPC = ISD::SETUO; break;
2541 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
2542 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
2543 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
2544 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
2545 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
2546 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
2547 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
2548 default:
2549 assert(!"Invalid VFCmp predicate value");
2550 FOC = FPC = ISD::SETFALSE;
2551 break;
2552 }
2553 if (FiniteOnlyFPMath())
2554 Condition = FOC;
2555 else
2556 Condition = FPC;
2557
Duncan Sands83ec4b62008-06-06 12:08:01 +00002558 MVT DestVT = TLI.getValueType(I.getType());
Nate Begemanb43e9c12008-05-12 19:40:03 +00002559
2560 setValue(&I, DAG.getVSetCC(DestVT, Op1, Op2, Condition));
2561}
2562
Chris Lattner1c08c712005-01-07 07:47:53 +00002563void SelectionDAGLowering::visitSelect(User &I) {
Dan Gohman475871a2008-07-27 21:46:04 +00002564 SDValue Cond = getValue(I.getOperand(0));
2565 SDValue TrueVal = getValue(I.getOperand(1));
2566 SDValue FalseVal = getValue(I.getOperand(2));
Dan Gohman7f321562007-06-25 16:23:39 +00002567 setValue(&I, DAG.getNode(ISD::SELECT, TrueVal.getValueType(), Cond,
2568 TrueVal, FalseVal));
Chris Lattner1c08c712005-01-07 07:47:53 +00002569}
2570
Reid Spencer3da59db2006-11-27 01:05:10 +00002571
2572void SelectionDAGLowering::visitTrunc(User &I) {
2573 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
Dan Gohman475871a2008-07-27 21:46:04 +00002574 SDValue N = getValue(I.getOperand(0));
Duncan Sands83ec4b62008-06-06 12:08:01 +00002575 MVT DestVT = TLI.getValueType(I.getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00002576 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
2577}
2578
2579void SelectionDAGLowering::visitZExt(User &I) {
2580 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2581 // ZExt also can't be a cast to bool for same reason. So, nothing much to do
Dan Gohman475871a2008-07-27 21:46:04 +00002582 SDValue N = getValue(I.getOperand(0));
Duncan Sands83ec4b62008-06-06 12:08:01 +00002583 MVT DestVT = TLI.getValueType(I.getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00002584 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
2585}
2586
2587void SelectionDAGLowering::visitSExt(User &I) {
2588 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2589 // SExt also can't be a cast to bool for same reason. So, nothing much to do
Dan Gohman475871a2008-07-27 21:46:04 +00002590 SDValue N = getValue(I.getOperand(0));
Duncan Sands83ec4b62008-06-06 12:08:01 +00002591 MVT DestVT = TLI.getValueType(I.getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00002592 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, DestVT, N));
2593}
2594
2595void SelectionDAGLowering::visitFPTrunc(User &I) {
2596 // FPTrunc is never a no-op cast, no need to check
Dan Gohman475871a2008-07-27 21:46:04 +00002597 SDValue N = getValue(I.getOperand(0));
Duncan Sands83ec4b62008-06-06 12:08:01 +00002598 MVT DestVT = TLI.getValueType(I.getType());
Chris Lattner0bd48932008-01-17 07:00:52 +00002599 setValue(&I, DAG.getNode(ISD::FP_ROUND, DestVT, N, DAG.getIntPtrConstant(0)));
Reid Spencer3da59db2006-11-27 01:05:10 +00002600}
2601
2602void SelectionDAGLowering::visitFPExt(User &I){
2603 // FPTrunc is never a no-op cast, no need to check
Dan Gohman475871a2008-07-27 21:46:04 +00002604 SDValue N = getValue(I.getOperand(0));
Duncan Sands83ec4b62008-06-06 12:08:01 +00002605 MVT DestVT = TLI.getValueType(I.getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00002606 setValue(&I, DAG.getNode(ISD::FP_EXTEND, DestVT, N));
2607}
2608
2609void SelectionDAGLowering::visitFPToUI(User &I) {
2610 // FPToUI is never a no-op cast, no need to check
Dan Gohman475871a2008-07-27 21:46:04 +00002611 SDValue N = getValue(I.getOperand(0));
Duncan Sands83ec4b62008-06-06 12:08:01 +00002612 MVT DestVT = TLI.getValueType(I.getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00002613 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, DestVT, N));
2614}
2615
2616void SelectionDAGLowering::visitFPToSI(User &I) {
2617 // FPToSI is never a no-op cast, no need to check
Dan Gohman475871a2008-07-27 21:46:04 +00002618 SDValue N = getValue(I.getOperand(0));
Duncan Sands83ec4b62008-06-06 12:08:01 +00002619 MVT DestVT = TLI.getValueType(I.getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00002620 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, DestVT, N));
2621}
2622
2623void SelectionDAGLowering::visitUIToFP(User &I) {
2624 // UIToFP is never a no-op cast, no need to check
Dan Gohman475871a2008-07-27 21:46:04 +00002625 SDValue N = getValue(I.getOperand(0));
Duncan Sands83ec4b62008-06-06 12:08:01 +00002626 MVT DestVT = TLI.getValueType(I.getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00002627 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, DestVT, N));
2628}
2629
2630void SelectionDAGLowering::visitSIToFP(User &I){
2631 // UIToFP is never a no-op cast, no need to check
Dan Gohman475871a2008-07-27 21:46:04 +00002632 SDValue N = getValue(I.getOperand(0));
Duncan Sands83ec4b62008-06-06 12:08:01 +00002633 MVT DestVT = TLI.getValueType(I.getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00002634 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, DestVT, N));
2635}
2636
2637void SelectionDAGLowering::visitPtrToInt(User &I) {
2638 // What to do depends on the size of the integer and the size of the pointer.
2639 // We can either truncate, zero extend, or no-op, accordingly.
Dan Gohman475871a2008-07-27 21:46:04 +00002640 SDValue N = getValue(I.getOperand(0));
Duncan Sands83ec4b62008-06-06 12:08:01 +00002641 MVT SrcVT = N.getValueType();
2642 MVT DestVT = TLI.getValueType(I.getType());
Dan Gohman475871a2008-07-27 21:46:04 +00002643 SDValue Result;
Duncan Sands8e4eb092008-06-08 20:54:56 +00002644 if (DestVT.bitsLT(SrcVT))
Reid Spencer3da59db2006-11-27 01:05:10 +00002645 Result = DAG.getNode(ISD::TRUNCATE, DestVT, N);
2646 else
2647 // Note: ZERO_EXTEND can handle cases where the sizes are equal too
2648 Result = DAG.getNode(ISD::ZERO_EXTEND, DestVT, N);
2649 setValue(&I, Result);
2650}
Chris Lattner1c08c712005-01-07 07:47:53 +00002651
Reid Spencer3da59db2006-11-27 01:05:10 +00002652void SelectionDAGLowering::visitIntToPtr(User &I) {
2653 // What to do depends on the size of the integer and the size of the pointer.
2654 // We can either truncate, zero extend, or no-op, accordingly.
Dan Gohman475871a2008-07-27 21:46:04 +00002655 SDValue N = getValue(I.getOperand(0));
Duncan Sands83ec4b62008-06-06 12:08:01 +00002656 MVT SrcVT = N.getValueType();
2657 MVT DestVT = TLI.getValueType(I.getType());
Duncan Sands8e4eb092008-06-08 20:54:56 +00002658 if (DestVT.bitsLT(SrcVT))
Reid Spencer3da59db2006-11-27 01:05:10 +00002659 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
2660 else
2661 // Note: ZERO_EXTEND can handle cases where the sizes are equal too
2662 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
2663}
2664
2665void SelectionDAGLowering::visitBitCast(User &I) {
Dan Gohman475871a2008-07-27 21:46:04 +00002666 SDValue N = getValue(I.getOperand(0));
Duncan Sands83ec4b62008-06-06 12:08:01 +00002667 MVT DestVT = TLI.getValueType(I.getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00002668
2669 // BitCast assures us that source and destination are the same size so this
2670 // is either a BIT_CONVERT or a no-op.
2671 if (DestVT != N.getValueType())
2672 setValue(&I, DAG.getNode(ISD::BIT_CONVERT, DestVT, N)); // convert types
2673 else
2674 setValue(&I, N); // noop cast.
Chris Lattner1c08c712005-01-07 07:47:53 +00002675}
2676
Chris Lattner2bbd8102006-03-29 00:11:43 +00002677void SelectionDAGLowering::visitInsertElement(User &I) {
Dan Gohman475871a2008-07-27 21:46:04 +00002678 SDValue InVec = getValue(I.getOperand(0));
2679 SDValue InVal = getValue(I.getOperand(1));
2680 SDValue InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
Chris Lattnerc7029802006-03-18 01:44:44 +00002681 getValue(I.getOperand(2)));
2682
Dan Gohman7f321562007-06-25 16:23:39 +00002683 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT,
2684 TLI.getValueType(I.getType()),
2685 InVec, InVal, InIdx));
Chris Lattnerc7029802006-03-18 01:44:44 +00002686}
2687
Chris Lattner2bbd8102006-03-29 00:11:43 +00002688void SelectionDAGLowering::visitExtractElement(User &I) {
Dan Gohman475871a2008-07-27 21:46:04 +00002689 SDValue InVec = getValue(I.getOperand(0));
2690 SDValue InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
Chris Lattner384504c2006-03-21 20:44:12 +00002691 getValue(I.getOperand(1)));
Dan Gohman7f321562007-06-25 16:23:39 +00002692 setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
Chris Lattner384504c2006-03-21 20:44:12 +00002693 TLI.getValueType(I.getType()), InVec, InIdx));
2694}
Chris Lattnerc7029802006-03-18 01:44:44 +00002695
Chris Lattner3e104b12006-04-08 04:15:24 +00002696void SelectionDAGLowering::visitShuffleVector(User &I) {
Dan Gohman475871a2008-07-27 21:46:04 +00002697 SDValue V1 = getValue(I.getOperand(0));
2698 SDValue V2 = getValue(I.getOperand(1));
2699 SDValue Mask = getValue(I.getOperand(2));
Chris Lattner3e104b12006-04-08 04:15:24 +00002700
Dan Gohman7f321562007-06-25 16:23:39 +00002701 setValue(&I, DAG.getNode(ISD::VECTOR_SHUFFLE,
2702 TLI.getValueType(I.getType()),
2703 V1, V2, Mask));
Chris Lattner3e104b12006-04-08 04:15:24 +00002704}
2705
Dan Gohman1d685a42008-06-07 02:02:36 +00002706void SelectionDAGLowering::visitInsertValue(InsertValueInst &I) {
2707 const Value *Op0 = I.getOperand(0);
2708 const Value *Op1 = I.getOperand(1);
2709 const Type *AggTy = I.getType();
2710 const Type *ValTy = Op1->getType();
2711 bool IntoUndef = isa<UndefValue>(Op0);
2712 bool FromUndef = isa<UndefValue>(Op1);
2713
2714 unsigned LinearIndex = ComputeLinearIndex(TLI, AggTy,
2715 I.idx_begin(), I.idx_end());
2716
2717 SmallVector<MVT, 4> AggValueVTs;
2718 ComputeValueVTs(TLI, AggTy, AggValueVTs);
2719 SmallVector<MVT, 4> ValValueVTs;
2720 ComputeValueVTs(TLI, ValTy, ValValueVTs);
2721
2722 unsigned NumAggValues = AggValueVTs.size();
2723 unsigned NumValValues = ValValueVTs.size();
Dan Gohman475871a2008-07-27 21:46:04 +00002724 SmallVector<SDValue, 4> Values(NumAggValues);
Dan Gohman1d685a42008-06-07 02:02:36 +00002725
Dan Gohman475871a2008-07-27 21:46:04 +00002726 SDValue Agg = getValue(Op0);
2727 SDValue Val = getValue(Op1);
Dan Gohman1d685a42008-06-07 02:02:36 +00002728 unsigned i = 0;
2729 // Copy the beginning value(s) from the original aggregate.
2730 for (; i != LinearIndex; ++i)
2731 Values[i] = IntoUndef ? DAG.getNode(ISD::UNDEF, AggValueVTs[i]) :
Dan Gohman475871a2008-07-27 21:46:04 +00002732 SDValue(Agg.Val, Agg.ResNo + i);
Dan Gohman1d685a42008-06-07 02:02:36 +00002733 // Copy values from the inserted value(s).
2734 for (; i != LinearIndex + NumValValues; ++i)
2735 Values[i] = FromUndef ? DAG.getNode(ISD::UNDEF, AggValueVTs[i]) :
Dan Gohman475871a2008-07-27 21:46:04 +00002736 SDValue(Val.Val, Val.ResNo + i - LinearIndex);
Dan Gohman1d685a42008-06-07 02:02:36 +00002737 // Copy remaining value(s) from the original aggregate.
2738 for (; i != NumAggValues; ++i)
2739 Values[i] = IntoUndef ? DAG.getNode(ISD::UNDEF, AggValueVTs[i]) :
Dan Gohman475871a2008-07-27 21:46:04 +00002740 SDValue(Agg.Val, Agg.ResNo + i);
Dan Gohman1d685a42008-06-07 02:02:36 +00002741
Duncan Sandsf9516202008-06-30 10:19:09 +00002742 setValue(&I, DAG.getMergeValues(DAG.getVTList(&AggValueVTs[0], NumAggValues),
2743 &Values[0], NumAggValues));
Dan Gohman041e2eb2008-05-15 19:50:34 +00002744}
2745
Dan Gohman1d685a42008-06-07 02:02:36 +00002746void SelectionDAGLowering::visitExtractValue(ExtractValueInst &I) {
2747 const Value *Op0 = I.getOperand(0);
2748 const Type *AggTy = Op0->getType();
2749 const Type *ValTy = I.getType();
2750 bool OutOfUndef = isa<UndefValue>(Op0);
2751
2752 unsigned LinearIndex = ComputeLinearIndex(TLI, AggTy,
2753 I.idx_begin(), I.idx_end());
2754
2755 SmallVector<MVT, 4> ValValueVTs;
2756 ComputeValueVTs(TLI, ValTy, ValValueVTs);
2757
2758 unsigned NumValValues = ValValueVTs.size();
Dan Gohman475871a2008-07-27 21:46:04 +00002759 SmallVector<SDValue, 4> Values(NumValValues);
Dan Gohman1d685a42008-06-07 02:02:36 +00002760
Dan Gohman475871a2008-07-27 21:46:04 +00002761 SDValue Agg = getValue(Op0);
Dan Gohman1d685a42008-06-07 02:02:36 +00002762 // Copy out the selected value(s).
2763 for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
2764 Values[i - LinearIndex] =
Dan Gohmandded0fd2008-06-20 00:54:19 +00002765 OutOfUndef ? DAG.getNode(ISD::UNDEF, Agg.Val->getValueType(Agg.ResNo + i)) :
Dan Gohman475871a2008-07-27 21:46:04 +00002766 SDValue(Agg.Val, Agg.ResNo + i);
Dan Gohman1d685a42008-06-07 02:02:36 +00002767
Duncan Sandsf9516202008-06-30 10:19:09 +00002768 setValue(&I, DAG.getMergeValues(DAG.getVTList(&ValValueVTs[0], NumValValues),
2769 &Values[0], NumValValues));
Dan Gohman041e2eb2008-05-15 19:50:34 +00002770}
2771
Chris Lattner3e104b12006-04-08 04:15:24 +00002772
Chris Lattner1c08c712005-01-07 07:47:53 +00002773void SelectionDAGLowering::visitGetElementPtr(User &I) {
Dan Gohman475871a2008-07-27 21:46:04 +00002774 SDValue N = getValue(I.getOperand(0));
Chris Lattner1c08c712005-01-07 07:47:53 +00002775 const Type *Ty = I.getOperand(0)->getType();
Chris Lattner1c08c712005-01-07 07:47:53 +00002776
2777 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
2778 OI != E; ++OI) {
2779 Value *Idx = *OI;
Chris Lattnerc88d8e92005-12-05 07:10:48 +00002780 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002781 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
Chris Lattner1c08c712005-01-07 07:47:53 +00002782 if (Field) {
2783 // N = N + Offset
Chris Lattnerb1919e22007-02-10 19:55:17 +00002784 uint64_t Offset = TD->getStructLayout(StTy)->getElementOffset(Field);
Chris Lattner1c08c712005-01-07 07:47:53 +00002785 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
Chris Lattner0bd48932008-01-17 07:00:52 +00002786 DAG.getIntPtrConstant(Offset));
Chris Lattner1c08c712005-01-07 07:47:53 +00002787 }
2788 Ty = StTy->getElementType(Field);
2789 } else {
2790 Ty = cast<SequentialType>(Ty)->getElementType();
Chris Lattner7cc47772005-01-07 21:56:57 +00002791
Chris Lattner7c0104b2005-11-09 04:45:33 +00002792 // If this is a constant subscript, handle it quickly.
2793 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002794 if (CI->getZExtValue() == 0) continue;
Reid Spencer47857812006-12-31 05:55:36 +00002795 uint64_t Offs =
Dale Johannesena7ac2bd2007-10-01 23:08:35 +00002796 TD->getABITypeSize(Ty)*cast<ConstantInt>(CI)->getSExtValue();
Chris Lattner0bd48932008-01-17 07:00:52 +00002797 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
2798 DAG.getIntPtrConstant(Offs));
Chris Lattner7c0104b2005-11-09 04:45:33 +00002799 continue;
Chris Lattner1c08c712005-01-07 07:47:53 +00002800 }
Chris Lattner7c0104b2005-11-09 04:45:33 +00002801
2802 // N = N + Idx * ElementSize;
Dale Johannesena7ac2bd2007-10-01 23:08:35 +00002803 uint64_t ElementSize = TD->getABITypeSize(Ty);
Dan Gohman475871a2008-07-27 21:46:04 +00002804 SDValue IdxN = getValue(Idx);
Chris Lattner7c0104b2005-11-09 04:45:33 +00002805
2806 // If the index is smaller or larger than intptr_t, truncate or extend
2807 // it.
Duncan Sands8e4eb092008-06-08 20:54:56 +00002808 if (IdxN.getValueType().bitsLT(N.getValueType())) {
Reid Spencer47857812006-12-31 05:55:36 +00002809 IdxN = DAG.getNode(ISD::SIGN_EXTEND, N.getValueType(), IdxN);
Duncan Sands8e4eb092008-06-08 20:54:56 +00002810 } else if (IdxN.getValueType().bitsGT(N.getValueType()))
Chris Lattner7c0104b2005-11-09 04:45:33 +00002811 IdxN = DAG.getNode(ISD::TRUNCATE, N.getValueType(), IdxN);
2812
2813 // If this is a multiply by a power of two, turn it into a shl
2814 // immediately. This is a very common case.
2815 if (isPowerOf2_64(ElementSize)) {
2816 unsigned Amt = Log2_64(ElementSize);
2817 IdxN = DAG.getNode(ISD::SHL, N.getValueType(), IdxN,
Chris Lattner6b2d6962005-11-09 16:50:40 +00002818 DAG.getConstant(Amt, TLI.getShiftAmountTy()));
Chris Lattner7c0104b2005-11-09 04:45:33 +00002819 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
2820 continue;
2821 }
2822
Dan Gohman475871a2008-07-27 21:46:04 +00002823 SDValue Scale = DAG.getIntPtrConstant(ElementSize);
Chris Lattner7c0104b2005-11-09 04:45:33 +00002824 IdxN = DAG.getNode(ISD::MUL, N.getValueType(), IdxN, Scale);
2825 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
Chris Lattner1c08c712005-01-07 07:47:53 +00002826 }
2827 }
2828 setValue(&I, N);
2829}
2830
2831void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
2832 // If this is a fixed sized alloca in the entry block of the function,
2833 // allocate it statically on the stack.
2834 if (FuncInfo.StaticAllocaMap.count(&I))
2835 return; // getValue will auto-populate this.
2836
2837 const Type *Ty = I.getAllocatedType();
Duncan Sands514ab342007-11-01 20:53:16 +00002838 uint64_t TySize = TLI.getTargetData()->getABITypeSize(Ty);
Chris Lattner58092e32007-01-20 22:35:55 +00002839 unsigned Align =
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00002840 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
Chris Lattner58092e32007-01-20 22:35:55 +00002841 I.getAlignment());
Chris Lattner1c08c712005-01-07 07:47:53 +00002842
Dan Gohman475871a2008-07-27 21:46:04 +00002843 SDValue AllocSize = getValue(I.getArraySize());
Duncan Sands83ec4b62008-06-06 12:08:01 +00002844 MVT IntPtr = TLI.getPointerTy();
Duncan Sands8e4eb092008-06-08 20:54:56 +00002845 if (IntPtr.bitsLT(AllocSize.getValueType()))
Chris Lattner68cd65e2005-01-22 23:04:37 +00002846 AllocSize = DAG.getNode(ISD::TRUNCATE, IntPtr, AllocSize);
Duncan Sands8e4eb092008-06-08 20:54:56 +00002847 else if (IntPtr.bitsGT(AllocSize.getValueType()))
Chris Lattner68cd65e2005-01-22 23:04:37 +00002848 AllocSize = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, AllocSize);
Chris Lattner1c08c712005-01-07 07:47:53 +00002849
Chris Lattner68cd65e2005-01-22 23:04:37 +00002850 AllocSize = DAG.getNode(ISD::MUL, IntPtr, AllocSize,
Chris Lattner0bd48932008-01-17 07:00:52 +00002851 DAG.getIntPtrConstant(TySize));
Chris Lattner1c08c712005-01-07 07:47:53 +00002852
Evan Cheng45157792007-08-16 23:46:29 +00002853 // Handle alignment. If the requested alignment is less than or equal to
2854 // the stack alignment, ignore it. If the size is greater than or equal to
2855 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
Chris Lattner1c08c712005-01-07 07:47:53 +00002856 unsigned StackAlign =
2857 TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
Evan Cheng45157792007-08-16 23:46:29 +00002858 if (Align <= StackAlign)
Chris Lattner1c08c712005-01-07 07:47:53 +00002859 Align = 0;
Evan Cheng45157792007-08-16 23:46:29 +00002860
2861 // Round the size of the allocation up to the stack alignment size
2862 // by add SA-1 to the size.
2863 AllocSize = DAG.getNode(ISD::ADD, AllocSize.getValueType(), AllocSize,
Chris Lattner0bd48932008-01-17 07:00:52 +00002864 DAG.getIntPtrConstant(StackAlign-1));
Evan Cheng45157792007-08-16 23:46:29 +00002865 // Mask out the low bits for alignment purposes.
2866 AllocSize = DAG.getNode(ISD::AND, AllocSize.getValueType(), AllocSize,
Chris Lattner0bd48932008-01-17 07:00:52 +00002867 DAG.getIntPtrConstant(~(uint64_t)(StackAlign-1)));
Chris Lattner1c08c712005-01-07 07:47:53 +00002868
Dan Gohman475871a2008-07-27 21:46:04 +00002869 SDValue Ops[] = { getRoot(), AllocSize, DAG.getIntPtrConstant(Align) };
Duncan Sands83ec4b62008-06-06 12:08:01 +00002870 const MVT *VTs = DAG.getNodeValueTypes(AllocSize.getValueType(),
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00002871 MVT::Other);
Dan Gohman475871a2008-07-27 21:46:04 +00002872 SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, VTs, 2, Ops, 3);
Chris Lattner0da331f2007-02-04 01:31:47 +00002873 setValue(&I, DSA);
2874 DAG.setRoot(DSA.getValue(1));
Chris Lattner1c08c712005-01-07 07:47:53 +00002875
2876 // Inform the Frame Information that we have just allocated a variable-sized
2877 // object.
2878 CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
2879}
2880
Chris Lattner1c08c712005-01-07 07:47:53 +00002881void SelectionDAGLowering::visitLoad(LoadInst &I) {
Dan Gohman8a6ccb52008-06-09 15:21:47 +00002882 const Value *SV = I.getOperand(0);
Dan Gohman475871a2008-07-27 21:46:04 +00002883 SDValue Ptr = getValue(SV);
Dan Gohman8a6ccb52008-06-09 15:21:47 +00002884
2885 const Type *Ty = I.getType();
2886 bool isVolatile = I.isVolatile();
2887 unsigned Alignment = I.getAlignment();
2888
2889 SmallVector<MVT, 4> ValueVTs;
2890 SmallVector<uint64_t, 4> Offsets;
2891 ComputeValueVTs(TLI, Ty, ValueVTs, &Offsets);
2892 unsigned NumValues = ValueVTs.size();
2893 if (NumValues == 0)
2894 return;
Misha Brukmanedf128a2005-04-21 22:36:52 +00002895
Dan Gohman475871a2008-07-27 21:46:04 +00002896 SDValue Root;
Dan Gohman8b4588f2008-07-25 00:04:14 +00002897 bool ConstantMemory = false;
Chris Lattnerd3948112005-01-17 22:19:26 +00002898 if (I.isVolatile())
Dan Gohman8b4588f2008-07-25 00:04:14 +00002899 // Serialize volatile loads with other side effects.
Chris Lattnerd3948112005-01-17 22:19:26 +00002900 Root = getRoot();
Dan Gohman8b4588f2008-07-25 00:04:14 +00002901 else if (AA.pointsToConstantMemory(SV)) {
2902 // Do not serialize (non-volatile) loads of constant memory with anything.
2903 Root = DAG.getEntryNode();
2904 ConstantMemory = true;
2905 } else {
Chris Lattnerd3948112005-01-17 22:19:26 +00002906 // Do not serialize non-volatile loads against each other.
2907 Root = DAG.getRoot();
2908 }
Chris Lattner28b5b1c2006-03-15 22:19:46 +00002909
Dan Gohman475871a2008-07-27 21:46:04 +00002910 SmallVector<SDValue, 4> Values(NumValues);
2911 SmallVector<SDValue, 4> Chains(NumValues);
Dan Gohman1d685a42008-06-07 02:02:36 +00002912 MVT PtrVT = Ptr.getValueType();
2913 for (unsigned i = 0; i != NumValues; ++i) {
Dan Gohman475871a2008-07-27 21:46:04 +00002914 SDValue L = DAG.getLoad(ValueVTs[i], Root,
Dan Gohman1d685a42008-06-07 02:02:36 +00002915 DAG.getNode(ISD::ADD, PtrVT, Ptr,
2916 DAG.getConstant(Offsets[i], PtrVT)),
2917 SV, Offsets[i],
2918 isVolatile, Alignment);
2919 Values[i] = L;
2920 Chains[i] = L.getValue(1);
2921 }
Chris Lattner28b5b1c2006-03-15 22:19:46 +00002922
Dan Gohman8b4588f2008-07-25 00:04:14 +00002923 if (!ConstantMemory) {
Dan Gohman475871a2008-07-27 21:46:04 +00002924 SDValue Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
Dan Gohman8b4588f2008-07-25 00:04:14 +00002925 &Chains[0], NumValues);
2926 if (isVolatile)
2927 DAG.setRoot(Chain);
2928 else
2929 PendingLoads.push_back(Chain);
2930 }
Dan Gohman1d685a42008-06-07 02:02:36 +00002931
Duncan Sandsf9516202008-06-30 10:19:09 +00002932 setValue(&I, DAG.getMergeValues(DAG.getVTList(&ValueVTs[0], NumValues),
2933 &Values[0], NumValues));
Chris Lattner1c08c712005-01-07 07:47:53 +00002934}
2935
2936
2937void SelectionDAGLowering::visitStore(StoreInst &I) {
2938 Value *SrcV = I.getOperand(0);
Dan Gohman1d685a42008-06-07 02:02:36 +00002939 Value *PtrV = I.getOperand(1);
Dan Gohman1d685a42008-06-07 02:02:36 +00002940
2941 SmallVector<MVT, 4> ValueVTs;
2942 SmallVector<uint64_t, 4> Offsets;
2943 ComputeValueVTs(TLI, SrcV->getType(), ValueVTs, &Offsets);
2944 unsigned NumValues = ValueVTs.size();
Dan Gohman8a6ccb52008-06-09 15:21:47 +00002945 if (NumValues == 0)
2946 return;
Dan Gohman1d685a42008-06-07 02:02:36 +00002947
Dan Gohman90d33ee2008-07-30 18:36:51 +00002948 // Get the lowered operands. Note that we do this after
2949 // checking if NumResults is zero, because with zero results
2950 // the operands won't have values in the map.
2951 SDValue Src = getValue(SrcV);
2952 SDValue Ptr = getValue(PtrV);
2953
Dan Gohman475871a2008-07-27 21:46:04 +00002954 SDValue Root = getRoot();
2955 SmallVector<SDValue, 4> Chains(NumValues);
Dan Gohman1d685a42008-06-07 02:02:36 +00002956 MVT PtrVT = Ptr.getValueType();
2957 bool isVolatile = I.isVolatile();
2958 unsigned Alignment = I.getAlignment();
2959 for (unsigned i = 0; i != NumValues; ++i)
Dan Gohman475871a2008-07-27 21:46:04 +00002960 Chains[i] = DAG.getStore(Root, SDValue(Src.Val, Src.ResNo + i),
Dan Gohman1d685a42008-06-07 02:02:36 +00002961 DAG.getNode(ISD::ADD, PtrVT, Ptr,
2962 DAG.getConstant(Offsets[i], PtrVT)),
2963 PtrV, Offsets[i],
2964 isVolatile, Alignment);
2965
2966 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other, &Chains[0], NumValues));
Chris Lattner1c08c712005-01-07 07:47:53 +00002967}
2968
Chris Lattner0eade312006-03-24 02:22:33 +00002969/// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
2970/// node.
2971void SelectionDAGLowering::visitTargetIntrinsic(CallInst &I,
2972 unsigned Intrinsic) {
Duncan Sandsa3355ff2007-12-03 20:06:50 +00002973 bool HasChain = !I.doesNotAccessMemory();
2974 bool OnlyLoad = HasChain && I.onlyReadsMemory();
2975
Chris Lattner0eade312006-03-24 02:22:33 +00002976 // Build the operand list.
Dan Gohman475871a2008-07-27 21:46:04 +00002977 SmallVector<SDValue, 8> Ops;
Chris Lattnere58a7802006-04-02 03:41:14 +00002978 if (HasChain) { // If this intrinsic has side-effects, chainify it.
2979 if (OnlyLoad) {
2980 // We don't need to serialize loads against other loads.
2981 Ops.push_back(DAG.getRoot());
2982 } else {
2983 Ops.push_back(getRoot());
2984 }
2985 }
Chris Lattner0eade312006-03-24 02:22:33 +00002986
2987 // Add the intrinsic ID as an integer operand.
2988 Ops.push_back(DAG.getConstant(Intrinsic, TLI.getPointerTy()));
2989
2990 // Add all operands of the call to the operand list.
2991 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
Dan Gohman475871a2008-07-27 21:46:04 +00002992 SDValue Op = getValue(I.getOperand(i));
Chris Lattner0eade312006-03-24 02:22:33 +00002993 assert(TLI.isTypeLegal(Op.getValueType()) &&
2994 "Intrinsic uses a non-legal type?");
2995 Ops.push_back(Op);
2996 }
2997
Duncan Sands83ec4b62008-06-06 12:08:01 +00002998 std::vector<MVT> VTs;
Chris Lattner0eade312006-03-24 02:22:33 +00002999 if (I.getType() != Type::VoidTy) {
Duncan Sands83ec4b62008-06-06 12:08:01 +00003000 MVT VT = TLI.getValueType(I.getType());
3001 if (VT.isVector()) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00003002 const VectorType *DestTy = cast<VectorType>(I.getType());
Duncan Sands83ec4b62008-06-06 12:08:01 +00003003 MVT EltVT = TLI.getValueType(DestTy->getElementType());
Chris Lattner0eade312006-03-24 02:22:33 +00003004
Duncan Sands83ec4b62008-06-06 12:08:01 +00003005 VT = MVT::getVectorVT(EltVT, DestTy->getNumElements());
Chris Lattner0eade312006-03-24 02:22:33 +00003006 assert(VT != MVT::Other && "Intrinsic uses a non-legal type?");
3007 }
3008
3009 assert(TLI.isTypeLegal(VT) && "Intrinsic uses a non-legal type?");
3010 VTs.push_back(VT);
3011 }
3012 if (HasChain)
3013 VTs.push_back(MVT::Other);
3014
Duncan Sands83ec4b62008-06-06 12:08:01 +00003015 const MVT *VTList = DAG.getNodeValueTypes(VTs);
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00003016
Chris Lattner0eade312006-03-24 02:22:33 +00003017 // Create the node.
Dan Gohman475871a2008-07-27 21:46:04 +00003018 SDValue Result;
Chris Lattner48b61a72006-03-28 00:40:33 +00003019 if (!HasChain)
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00003020 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VTList, VTs.size(),
3021 &Ops[0], Ops.size());
Chris Lattner48b61a72006-03-28 00:40:33 +00003022 else if (I.getType() != Type::VoidTy)
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00003023 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, VTList, VTs.size(),
3024 &Ops[0], Ops.size());
Chris Lattner48b61a72006-03-28 00:40:33 +00003025 else
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00003026 Result = DAG.getNode(ISD::INTRINSIC_VOID, VTList, VTs.size(),
3027 &Ops[0], Ops.size());
Chris Lattner48b61a72006-03-28 00:40:33 +00003028
Chris Lattnere58a7802006-04-02 03:41:14 +00003029 if (HasChain) {
Dan Gohman475871a2008-07-27 21:46:04 +00003030 SDValue Chain = Result.getValue(Result.Val->getNumValues()-1);
Chris Lattnere58a7802006-04-02 03:41:14 +00003031 if (OnlyLoad)
3032 PendingLoads.push_back(Chain);
3033 else
3034 DAG.setRoot(Chain);
3035 }
Chris Lattner0eade312006-03-24 02:22:33 +00003036 if (I.getType() != Type::VoidTy) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00003037 if (const VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
Duncan Sands83ec4b62008-06-06 12:08:01 +00003038 MVT VT = TLI.getValueType(PTy);
Dan Gohman7f321562007-06-25 16:23:39 +00003039 Result = DAG.getNode(ISD::BIT_CONVERT, VT, Result);
Chris Lattner0eade312006-03-24 02:22:33 +00003040 }
3041 setValue(&I, Result);
3042 }
3043}
3044
Duncan Sandsb4fd45e2007-07-06 09:10:03 +00003045/// ExtractTypeInfo - Returns the type info, possibly bitcast, encoded in V.
Duncan Sandscf26d7c2007-07-04 20:52:51 +00003046static GlobalVariable *ExtractTypeInfo (Value *V) {
Anton Korobeynikov0b12ecf2008-05-07 22:54:15 +00003047 V = V->stripPointerCasts();
Duncan Sandsb4fd45e2007-07-06 09:10:03 +00003048 GlobalVariable *GV = dyn_cast<GlobalVariable>(V);
Anton Korobeynikov4c71dfe2008-02-20 11:10:28 +00003049 assert ((GV || isa<ConstantPointerNull>(V)) &&
Duncan Sandscf26d7c2007-07-04 20:52:51 +00003050 "TypeInfo must be a global variable or NULL");
3051 return GV;
3052}
3053
Duncan Sandsf4070822007-06-15 19:04:19 +00003054/// addCatchInfo - Extract the personality and type infos from an eh.selector
Duncan Sandscf26d7c2007-07-04 20:52:51 +00003055/// call, and add them to the specified machine basic block.
Duncan Sandsf4070822007-06-15 19:04:19 +00003056static void addCatchInfo(CallInst &I, MachineModuleInfo *MMI,
3057 MachineBasicBlock *MBB) {
3058 // Inform the MachineModuleInfo of the personality for this landing pad.
3059 ConstantExpr *CE = cast<ConstantExpr>(I.getOperand(2));
3060 assert(CE->getOpcode() == Instruction::BitCast &&
3061 isa<Function>(CE->getOperand(0)) &&
3062 "Personality should be a function");
3063 MMI->addPersonality(MBB, cast<Function>(CE->getOperand(0)));
3064
3065 // Gather all the type infos for this landing pad and pass them along to
3066 // MachineModuleInfo.
3067 std::vector<GlobalVariable *> TyInfo;
Duncan Sandscf26d7c2007-07-04 20:52:51 +00003068 unsigned N = I.getNumOperands();
3069
3070 for (unsigned i = N - 1; i > 2; --i) {
3071 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(i))) {
3072 unsigned FilterLength = CI->getZExtValue();
Duncan Sands6590b042007-08-27 15:47:50 +00003073 unsigned FirstCatch = i + FilterLength + !FilterLength;
Duncan Sandscf26d7c2007-07-04 20:52:51 +00003074 assert (FirstCatch <= N && "Invalid filter length");
3075
3076 if (FirstCatch < N) {
3077 TyInfo.reserve(N - FirstCatch);
3078 for (unsigned j = FirstCatch; j < N; ++j)
3079 TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
3080 MMI->addCatchTypeInfo(MBB, TyInfo);
3081 TyInfo.clear();
3082 }
3083
Duncan Sands6590b042007-08-27 15:47:50 +00003084 if (!FilterLength) {
3085 // Cleanup.
3086 MMI->addCleanup(MBB);
3087 } else {
3088 // Filter.
3089 TyInfo.reserve(FilterLength - 1);
3090 for (unsigned j = i + 1; j < FirstCatch; ++j)
3091 TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
3092 MMI->addFilterTypeInfo(MBB, TyInfo);
3093 TyInfo.clear();
3094 }
Duncan Sandscf26d7c2007-07-04 20:52:51 +00003095
3096 N = i;
3097 }
Duncan Sandsf4070822007-06-15 19:04:19 +00003098 }
Duncan Sandscf26d7c2007-07-04 20:52:51 +00003099
3100 if (N > 3) {
3101 TyInfo.reserve(N - 3);
3102 for (unsigned j = 3; j < N; ++j)
3103 TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
Duncan Sandsf4070822007-06-15 19:04:19 +00003104 MMI->addCatchTypeInfo(MBB, TyInfo);
Duncan Sandscf26d7c2007-07-04 20:52:51 +00003105 }
Duncan Sandsf4070822007-06-15 19:04:19 +00003106}
3107
Mon P Wang63307c32008-05-05 19:05:59 +00003108
3109/// Inlined utility function to implement binary input atomic intrinsics for
3110// visitIntrinsicCall: I is a call instruction
3111// Op is the associated NodeType for I
3112const char *
3113SelectionDAGLowering::implVisitBinaryAtomic(CallInst& I, ISD::NodeType Op) {
Dan Gohman475871a2008-07-27 21:46:04 +00003114 SDValue Root = getRoot();
3115 SDValue L = DAG.getAtomic(Op, Root,
Mon P Wang63307c32008-05-05 19:05:59 +00003116 getValue(I.getOperand(1)),
Dan Gohmanfd4418f2008-06-25 16:07:49 +00003117 getValue(I.getOperand(2)),
Mon P Wang28873102008-06-25 08:15:39 +00003118 I.getOperand(1));
Mon P Wang63307c32008-05-05 19:05:59 +00003119 setValue(&I, L);
3120 DAG.setRoot(L.getValue(1));
3121 return 0;
3122}
3123
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003124/// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
3125/// we want to emit this as a call to a named external function, return the name
3126/// otherwise lower it and return null.
3127const char *
3128SelectionDAGLowering::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
3129 switch (Intrinsic) {
Chris Lattner0eade312006-03-24 02:22:33 +00003130 default:
3131 // By default, turn this into a target intrinsic node.
3132 visitTargetIntrinsic(I, Intrinsic);
3133 return 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003134 case Intrinsic::vastart: visitVAStart(I); return 0;
3135 case Intrinsic::vaend: visitVAEnd(I); return 0;
3136 case Intrinsic::vacopy: visitVACopy(I); return 0;
Nate Begemanbcc5f362007-01-29 22:58:52 +00003137 case Intrinsic::returnaddress:
3138 setValue(&I, DAG.getNode(ISD::RETURNADDR, TLI.getPointerTy(),
3139 getValue(I.getOperand(1))));
3140 return 0;
3141 case Intrinsic::frameaddress:
3142 setValue(&I, DAG.getNode(ISD::FRAMEADDR, TLI.getPointerTy(),
3143 getValue(I.getOperand(1))));
3144 return 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003145 case Intrinsic::setjmp:
Anton Korobeynikovd27a2582006-12-10 23:12:42 +00003146 return "_setjmp"+!TLI.usesUnderscoreSetJmp();
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003147 break;
3148 case Intrinsic::longjmp:
Anton Korobeynikovd27a2582006-12-10 23:12:42 +00003149 return "_longjmp"+!TLI.usesUnderscoreLongJmp();
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003150 break;
Chris Lattner03dd4652006-03-03 00:00:25 +00003151 case Intrinsic::memcpy_i32:
Dan Gohman707e0182008-04-12 04:36:06 +00003152 case Intrinsic::memcpy_i64: {
Dan Gohman475871a2008-07-27 21:46:04 +00003153 SDValue Op1 = getValue(I.getOperand(1));
3154 SDValue Op2 = getValue(I.getOperand(2));
3155 SDValue Op3 = getValue(I.getOperand(3));
Dan Gohman707e0182008-04-12 04:36:06 +00003156 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
3157 DAG.setRoot(DAG.getMemcpy(getRoot(), Op1, Op2, Op3, Align, false,
3158 I.getOperand(1), 0, I.getOperand(2), 0));
Chris Lattner03dd4652006-03-03 00:00:25 +00003159 return 0;
Dan Gohman707e0182008-04-12 04:36:06 +00003160 }
Chris Lattner03dd4652006-03-03 00:00:25 +00003161 case Intrinsic::memset_i32:
Dan Gohman707e0182008-04-12 04:36:06 +00003162 case Intrinsic::memset_i64: {
Dan Gohman475871a2008-07-27 21:46:04 +00003163 SDValue Op1 = getValue(I.getOperand(1));
3164 SDValue Op2 = getValue(I.getOperand(2));
3165 SDValue Op3 = getValue(I.getOperand(3));
Dan Gohman707e0182008-04-12 04:36:06 +00003166 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
3167 DAG.setRoot(DAG.getMemset(getRoot(), Op1, Op2, Op3, Align,
3168 I.getOperand(1), 0));
Chris Lattner03dd4652006-03-03 00:00:25 +00003169 return 0;
Dan Gohman707e0182008-04-12 04:36:06 +00003170 }
Chris Lattner03dd4652006-03-03 00:00:25 +00003171 case Intrinsic::memmove_i32:
Dan Gohman707e0182008-04-12 04:36:06 +00003172 case Intrinsic::memmove_i64: {
Dan Gohman475871a2008-07-27 21:46:04 +00003173 SDValue Op1 = getValue(I.getOperand(1));
3174 SDValue Op2 = getValue(I.getOperand(2));
3175 SDValue Op3 = getValue(I.getOperand(3));
Dan Gohman707e0182008-04-12 04:36:06 +00003176 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
3177
3178 // If the source and destination are known to not be aliases, we can
3179 // lower memmove as memcpy.
3180 uint64_t Size = -1ULL;
3181 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op3))
3182 Size = C->getValue();
3183 if (AA.alias(I.getOperand(1), Size, I.getOperand(2), Size) ==
3184 AliasAnalysis::NoAlias) {
3185 DAG.setRoot(DAG.getMemcpy(getRoot(), Op1, Op2, Op3, Align, false,
3186 I.getOperand(1), 0, I.getOperand(2), 0));
3187 return 0;
3188 }
3189
3190 DAG.setRoot(DAG.getMemmove(getRoot(), Op1, Op2, Op3, Align,
3191 I.getOperand(1), 0, I.getOperand(2), 0));
Chris Lattner03dd4652006-03-03 00:00:25 +00003192 return 0;
Dan Gohman707e0182008-04-12 04:36:06 +00003193 }
Chris Lattner86cb6432005-12-13 17:40:33 +00003194 case Intrinsic::dbg_stoppoint: {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00003195 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskey43970fe2006-03-23 18:06:46 +00003196 DbgStopPointInst &SPI = cast<DbgStopPointInst>(I);
Jim Laskey44c3b9f2007-01-26 21:22:28 +00003197 if (MMI && SPI.getContext() && MMI->Verify(SPI.getContext())) {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00003198 DebugInfoDesc *DD = MMI->getDescFor(SPI.getContext());
Jim Laskeyce72b172006-02-11 01:01:30 +00003199 assert(DD && "Not a debug information descriptor");
Dan Gohman7f460202008-06-30 20:59:49 +00003200 DAG.setRoot(DAG.getDbgStopPoint(getRoot(),
3201 SPI.getLine(),
3202 SPI.getColumn(),
3203 cast<CompileUnitDesc>(DD)));
Chris Lattner86cb6432005-12-13 17:40:33 +00003204 }
Jim Laskey43970fe2006-03-23 18:06:46 +00003205
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +00003206 return 0;
Chris Lattner36ce6912005-11-29 06:21:05 +00003207 }
Jim Laskey43970fe2006-03-23 18:06:46 +00003208 case Intrinsic::dbg_region_start: {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00003209 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskey43970fe2006-03-23 18:06:46 +00003210 DbgRegionStartInst &RSI = cast<DbgRegionStartInst>(I);
Jim Laskey44c3b9f2007-01-26 21:22:28 +00003211 if (MMI && RSI.getContext() && MMI->Verify(RSI.getContext())) {
3212 unsigned LabelID = MMI->RecordRegionStart(RSI.getContext());
Dan Gohman44066042008-07-01 00:05:16 +00003213 DAG.setRoot(DAG.getLabel(ISD::DBG_LABEL, getRoot(), LabelID));
Jim Laskey43970fe2006-03-23 18:06:46 +00003214 }
3215
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +00003216 return 0;
Jim Laskey43970fe2006-03-23 18:06:46 +00003217 }
3218 case Intrinsic::dbg_region_end: {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00003219 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskey43970fe2006-03-23 18:06:46 +00003220 DbgRegionEndInst &REI = cast<DbgRegionEndInst>(I);
Jim Laskey44c3b9f2007-01-26 21:22:28 +00003221 if (MMI && REI.getContext() && MMI->Verify(REI.getContext())) {
3222 unsigned LabelID = MMI->RecordRegionEnd(REI.getContext());
Dan Gohman44066042008-07-01 00:05:16 +00003223 DAG.setRoot(DAG.getLabel(ISD::DBG_LABEL, getRoot(), LabelID));
Jim Laskey43970fe2006-03-23 18:06:46 +00003224 }
3225
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +00003226 return 0;
Jim Laskey43970fe2006-03-23 18:06:46 +00003227 }
3228 case Intrinsic::dbg_func_start: {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00003229 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Evan Cheng1b08bbc2008-02-01 09:10:45 +00003230 if (!MMI) return 0;
Jim Laskey43970fe2006-03-23 18:06:46 +00003231 DbgFuncStartInst &FSI = cast<DbgFuncStartInst>(I);
Evan Cheng1b08bbc2008-02-01 09:10:45 +00003232 Value *SP = FSI.getSubprogram();
3233 if (SP && MMI->Verify(SP)) {
3234 // llvm.dbg.func.start implicitly defines a dbg_stoppoint which is
3235 // what (most?) gdb expects.
3236 DebugInfoDesc *DD = MMI->getDescFor(SP);
3237 assert(DD && "Not a debug information descriptor");
3238 SubprogramDesc *Subprogram = cast<SubprogramDesc>(DD);
3239 const CompileUnitDesc *CompileUnit = Subprogram->getFile();
Dan Gohman99fe47b2008-06-30 22:21:03 +00003240 unsigned SrcFile = MMI->RecordSource(CompileUnit);
Evan Cheng1b08bbc2008-02-01 09:10:45 +00003241 // Record the source line but does create a label. It will be emitted
3242 // at asm emission time.
3243 MMI->RecordSourceLine(Subprogram->getLine(), 0, SrcFile);
Jim Laskey43970fe2006-03-23 18:06:46 +00003244 }
3245
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +00003246 return 0;
Jim Laskey43970fe2006-03-23 18:06:46 +00003247 }
3248 case Intrinsic::dbg_declare: {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00003249 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskey43970fe2006-03-23 18:06:46 +00003250 DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
Evan Chenga844bde2008-02-02 04:07:54 +00003251 Value *Variable = DI.getVariable();
3252 if (MMI && Variable && MMI->Verify(Variable))
3253 DAG.setRoot(DAG.getNode(ISD::DECLARE, MVT::Other, getRoot(),
3254 getValue(DI.getAddress()), getValue(Variable)));
Jim Laskey43970fe2006-03-23 18:06:46 +00003255 return 0;
3256 }
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003257
Jim Laskeyb180aa12007-02-21 22:53:45 +00003258 case Intrinsic::eh_exception: {
Dale Johannesen1532f3d2008-04-02 00:25:04 +00003259 if (!CurMBB->isLandingPad()) {
3260 // FIXME: Mark exception register as live in. Hack for PR1508.
3261 unsigned Reg = TLI.getExceptionAddressRegister();
3262 if (Reg) CurMBB->addLiveIn(Reg);
Jim Laskey735b6f82007-02-22 15:38:06 +00003263 }
Dale Johannesen1532f3d2008-04-02 00:25:04 +00003264 // Insert the EXCEPTIONADDR instruction.
3265 SDVTList VTs = DAG.getVTList(TLI.getPointerTy(), MVT::Other);
Dan Gohman475871a2008-07-27 21:46:04 +00003266 SDValue Ops[1];
Dale Johannesen1532f3d2008-04-02 00:25:04 +00003267 Ops[0] = DAG.getRoot();
Dan Gohman475871a2008-07-27 21:46:04 +00003268 SDValue Op = DAG.getNode(ISD::EXCEPTIONADDR, VTs, Ops, 1);
Dale Johannesen1532f3d2008-04-02 00:25:04 +00003269 setValue(&I, Op);
3270 DAG.setRoot(Op.getValue(1));
Jim Laskeyb180aa12007-02-21 22:53:45 +00003271 return 0;
3272 }
3273
Anton Korobeynikov8806c7b2007-09-07 11:39:35 +00003274 case Intrinsic::eh_selector_i32:
3275 case Intrinsic::eh_selector_i64: {
Jim Laskeyb180aa12007-02-21 22:53:45 +00003276 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Duncan Sands83ec4b62008-06-06 12:08:01 +00003277 MVT VT = (Intrinsic == Intrinsic::eh_selector_i32 ?
Anton Korobeynikov8806c7b2007-09-07 11:39:35 +00003278 MVT::i32 : MVT::i64);
3279
Dale Johannesen1532f3d2008-04-02 00:25:04 +00003280 if (MMI) {
Duncan Sandsf4070822007-06-15 19:04:19 +00003281 if (CurMBB->isLandingPad())
3282 addCatchInfo(I, MMI, CurMBB);
Evan Chenge47c3332007-06-27 18:45:32 +00003283 else {
Duncan Sandsf4070822007-06-15 19:04:19 +00003284#ifndef NDEBUG
Duncan Sandsf4070822007-06-15 19:04:19 +00003285 FuncInfo.CatchInfoLost.insert(&I);
3286#endif
Duncan Sands90291952007-07-06 09:18:59 +00003287 // FIXME: Mark exception selector register as live in. Hack for PR1508.
3288 unsigned Reg = TLI.getExceptionSelectorRegister();
3289 if (Reg) CurMBB->addLiveIn(Reg);
Evan Chenge47c3332007-06-27 18:45:32 +00003290 }
Jim Laskey735b6f82007-02-22 15:38:06 +00003291
3292 // Insert the EHSELECTION instruction.
Anton Korobeynikov8806c7b2007-09-07 11:39:35 +00003293 SDVTList VTs = DAG.getVTList(VT, MVT::Other);
Dan Gohman475871a2008-07-27 21:46:04 +00003294 SDValue Ops[2];
Jim Laskey735b6f82007-02-22 15:38:06 +00003295 Ops[0] = getValue(I.getOperand(1));
3296 Ops[1] = getRoot();
Dan Gohman475871a2008-07-27 21:46:04 +00003297 SDValue Op = DAG.getNode(ISD::EHSELECTION, VTs, Ops, 2);
Jim Laskey735b6f82007-02-22 15:38:06 +00003298 setValue(&I, Op);
3299 DAG.setRoot(Op.getValue(1));
Jim Laskey7a1de982007-02-24 09:45:44 +00003300 } else {
Anton Korobeynikov8806c7b2007-09-07 11:39:35 +00003301 setValue(&I, DAG.getConstant(0, VT));
Jim Laskey735b6f82007-02-22 15:38:06 +00003302 }
Jim Laskeyb180aa12007-02-21 22:53:45 +00003303
3304 return 0;
3305 }
Anton Korobeynikov8806c7b2007-09-07 11:39:35 +00003306
3307 case Intrinsic::eh_typeid_for_i32:
3308 case Intrinsic::eh_typeid_for_i64: {
Jim Laskeyb180aa12007-02-21 22:53:45 +00003309 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Duncan Sands83ec4b62008-06-06 12:08:01 +00003310 MVT VT = (Intrinsic == Intrinsic::eh_typeid_for_i32 ?
Anton Korobeynikov8806c7b2007-09-07 11:39:35 +00003311 MVT::i32 : MVT::i64);
Jim Laskeyb180aa12007-02-21 22:53:45 +00003312
Jim Laskey735b6f82007-02-22 15:38:06 +00003313 if (MMI) {
3314 // Find the type id for the given typeinfo.
Duncan Sandscf26d7c2007-07-04 20:52:51 +00003315 GlobalVariable *GV = ExtractTypeInfo(I.getOperand(1));
Duncan Sands3b346362007-05-04 17:12:26 +00003316
Jim Laskey735b6f82007-02-22 15:38:06 +00003317 unsigned TypeID = MMI->getTypeIDFor(GV);
Anton Korobeynikov8806c7b2007-09-07 11:39:35 +00003318 setValue(&I, DAG.getConstant(TypeID, VT));
Jim Laskey7a1de982007-02-24 09:45:44 +00003319 } else {
Duncan Sandsf664e412007-07-06 14:46:23 +00003320 // Return something different to eh_selector.
Anton Korobeynikov8806c7b2007-09-07 11:39:35 +00003321 setValue(&I, DAG.getConstant(1, VT));
Jim Laskey735b6f82007-02-22 15:38:06 +00003322 }
Jim Laskeyb180aa12007-02-21 22:53:45 +00003323
3324 return 0;
3325 }
3326
Anton Korobeynikov2365f512007-07-14 14:06:15 +00003327 case Intrinsic::eh_return: {
3328 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3329
Dale Johannesen1532f3d2008-04-02 00:25:04 +00003330 if (MMI) {
Anton Korobeynikov2365f512007-07-14 14:06:15 +00003331 MMI->setCallsEHReturn(true);
3332 DAG.setRoot(DAG.getNode(ISD::EH_RETURN,
3333 MVT::Other,
Dan Gohman86e1ebf2008-03-27 19:56:19 +00003334 getControlRoot(),
Anton Korobeynikov2365f512007-07-14 14:06:15 +00003335 getValue(I.getOperand(1)),
3336 getValue(I.getOperand(2))));
3337 } else {
3338 setValue(&I, DAG.getConstant(0, TLI.getPointerTy()));
3339 }
3340
3341 return 0;
3342 }
3343
3344 case Intrinsic::eh_unwind_init: {
3345 if (MachineModuleInfo *MMI = DAG.getMachineModuleInfo()) {
3346 MMI->setCallsUnwindInit(true);
3347 }
3348
3349 return 0;
3350 }
3351
3352 case Intrinsic::eh_dwarf_cfa: {
Duncan Sands83ec4b62008-06-06 12:08:01 +00003353 MVT VT = getValue(I.getOperand(1)).getValueType();
Dan Gohman475871a2008-07-27 21:46:04 +00003354 SDValue CfaArg;
Duncan Sands8e4eb092008-06-08 20:54:56 +00003355 if (VT.bitsGT(TLI.getPointerTy()))
Dale Johannesen1532f3d2008-04-02 00:25:04 +00003356 CfaArg = DAG.getNode(ISD::TRUNCATE,
3357 TLI.getPointerTy(), getValue(I.getOperand(1)));
3358 else
3359 CfaArg = DAG.getNode(ISD::SIGN_EXTEND,
3360 TLI.getPointerTy(), getValue(I.getOperand(1)));
Anton Korobeynikov2365f512007-07-14 14:06:15 +00003361
Dan Gohman475871a2008-07-27 21:46:04 +00003362 SDValue Offset = DAG.getNode(ISD::ADD,
Dale Johannesen1532f3d2008-04-02 00:25:04 +00003363 TLI.getPointerTy(),
3364 DAG.getNode(ISD::FRAME_TO_ARGS_OFFSET,
3365 TLI.getPointerTy()),
3366 CfaArg);
3367 setValue(&I, DAG.getNode(ISD::ADD,
3368 TLI.getPointerTy(),
3369 DAG.getNode(ISD::FRAMEADDR,
3370 TLI.getPointerTy(),
3371 DAG.getConstant(0,
3372 TLI.getPointerTy())),
3373 Offset));
Anton Korobeynikov2365f512007-07-14 14:06:15 +00003374 return 0;
3375 }
3376
Dale Johannesen9ab7fb32007-10-02 17:43:59 +00003377 case Intrinsic::sqrt:
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003378 setValue(&I, DAG.getNode(ISD::FSQRT,
3379 getValue(I.getOperand(1)).getValueType(),
3380 getValue(I.getOperand(1))));
3381 return 0;
Dale Johannesen9ab7fb32007-10-02 17:43:59 +00003382 case Intrinsic::powi:
Chris Lattner6ddf8ed2006-09-09 06:03:30 +00003383 setValue(&I, DAG.getNode(ISD::FPOWI,
3384 getValue(I.getOperand(1)).getValueType(),
3385 getValue(I.getOperand(1)),
3386 getValue(I.getOperand(2))));
3387 return 0;
Dan Gohmanac9385a2007-10-12 00:01:22 +00003388 case Intrinsic::sin:
3389 setValue(&I, DAG.getNode(ISD::FSIN,
3390 getValue(I.getOperand(1)).getValueType(),
3391 getValue(I.getOperand(1))));
3392 return 0;
3393 case Intrinsic::cos:
3394 setValue(&I, DAG.getNode(ISD::FCOS,
3395 getValue(I.getOperand(1)).getValueType(),
3396 getValue(I.getOperand(1))));
3397 return 0;
3398 case Intrinsic::pow:
3399 setValue(&I, DAG.getNode(ISD::FPOW,
3400 getValue(I.getOperand(1)).getValueType(),
3401 getValue(I.getOperand(1)),
3402 getValue(I.getOperand(2))));
3403 return 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003404 case Intrinsic::pcmarker: {
Dan Gohman475871a2008-07-27 21:46:04 +00003405 SDValue Tmp = getValue(I.getOperand(1));
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003406 DAG.setRoot(DAG.getNode(ISD::PCMARKER, MVT::Other, getRoot(), Tmp));
3407 return 0;
3408 }
Andrew Lenharth8b91c772005-11-11 22:48:54 +00003409 case Intrinsic::readcyclecounter: {
Dan Gohman475871a2008-07-27 21:46:04 +00003410 SDValue Op = getRoot();
3411 SDValue Tmp = DAG.getNode(ISD::READCYCLECOUNTER,
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00003412 DAG.getNodeValueTypes(MVT::i64, MVT::Other), 2,
3413 &Op, 1);
Andrew Lenharth8b91c772005-11-11 22:48:54 +00003414 setValue(&I, Tmp);
3415 DAG.setRoot(Tmp.getValue(1));
Andrew Lenharth51b8d542005-11-11 16:47:30 +00003416 return 0;
Andrew Lenharth8b91c772005-11-11 22:48:54 +00003417 }
Chris Lattnerc6eb6d72007-04-10 03:20:39 +00003418 case Intrinsic::part_select: {
Reid Spencer3f108cb2007-04-05 01:20:18 +00003419 // Currently not implemented: just abort
Reid Spencerf75b8742007-04-12 02:48:46 +00003420 assert(0 && "part_select intrinsic not implemented");
3421 abort();
3422 }
3423 case Intrinsic::part_set: {
3424 // Currently not implemented: just abort
3425 assert(0 && "part_set intrinsic not implemented");
Reid Spencer3f108cb2007-04-05 01:20:18 +00003426 abort();
Reid Spenceraddd11d2007-04-04 23:48:25 +00003427 }
Reid Spencera4f9c4d2007-04-01 07:34:11 +00003428 case Intrinsic::bswap:
Nate Begemand88fc032006-01-14 03:14:10 +00003429 setValue(&I, DAG.getNode(ISD::BSWAP,
3430 getValue(I.getOperand(1)).getValueType(),
3431 getValue(I.getOperand(1))));
3432 return 0;
Reid Spencera4f9c4d2007-04-01 07:34:11 +00003433 case Intrinsic::cttz: {
Dan Gohman475871a2008-07-27 21:46:04 +00003434 SDValue Arg = getValue(I.getOperand(1));
Duncan Sands83ec4b62008-06-06 12:08:01 +00003435 MVT Ty = Arg.getValueType();
Dan Gohman475871a2008-07-27 21:46:04 +00003436 SDValue result = DAG.getNode(ISD::CTTZ, Ty, Arg);
Reid Spencera4f9c4d2007-04-01 07:34:11 +00003437 setValue(&I, result);
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003438 return 0;
Reid Spencera4f9c4d2007-04-01 07:34:11 +00003439 }
3440 case Intrinsic::ctlz: {
Dan Gohman475871a2008-07-27 21:46:04 +00003441 SDValue Arg = getValue(I.getOperand(1));
Duncan Sands83ec4b62008-06-06 12:08:01 +00003442 MVT Ty = Arg.getValueType();
Dan Gohman475871a2008-07-27 21:46:04 +00003443 SDValue result = DAG.getNode(ISD::CTLZ, Ty, Arg);
Reid Spencera4f9c4d2007-04-01 07:34:11 +00003444 setValue(&I, result);
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003445 return 0;
Reid Spencera4f9c4d2007-04-01 07:34:11 +00003446 }
3447 case Intrinsic::ctpop: {
Dan Gohman475871a2008-07-27 21:46:04 +00003448 SDValue Arg = getValue(I.getOperand(1));
Duncan Sands83ec4b62008-06-06 12:08:01 +00003449 MVT Ty = Arg.getValueType();
Dan Gohman475871a2008-07-27 21:46:04 +00003450 SDValue result = DAG.getNode(ISD::CTPOP, Ty, Arg);
Reid Spencera4f9c4d2007-04-01 07:34:11 +00003451 setValue(&I, result);
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003452 return 0;
Reid Spencera4f9c4d2007-04-01 07:34:11 +00003453 }
Chris Lattner140d53c2006-01-13 02:50:02 +00003454 case Intrinsic::stacksave: {
Dan Gohman475871a2008-07-27 21:46:04 +00003455 SDValue Op = getRoot();
3456 SDValue Tmp = DAG.getNode(ISD::STACKSAVE,
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00003457 DAG.getNodeValueTypes(TLI.getPointerTy(), MVT::Other), 2, &Op, 1);
Chris Lattner140d53c2006-01-13 02:50:02 +00003458 setValue(&I, Tmp);
3459 DAG.setRoot(Tmp.getValue(1));
3460 return 0;
3461 }
Chris Lattner39a17dd2006-01-23 05:22:07 +00003462 case Intrinsic::stackrestore: {
Dan Gohman475871a2008-07-27 21:46:04 +00003463 SDValue Tmp = getValue(I.getOperand(1));
Chris Lattner39a17dd2006-01-23 05:22:07 +00003464 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, MVT::Other, getRoot(), Tmp));
Chris Lattner140d53c2006-01-13 02:50:02 +00003465 return 0;
Chris Lattner39a17dd2006-01-23 05:22:07 +00003466 }
Tanya Lattner24e5aad2007-06-15 22:26:58 +00003467 case Intrinsic::var_annotation:
3468 // Discard annotate attributes
3469 return 0;
Duncan Sands36397f52007-07-27 12:58:54 +00003470
Duncan Sands36397f52007-07-27 12:58:54 +00003471 case Intrinsic::init_trampoline: {
Anton Korobeynikov0b12ecf2008-05-07 22:54:15 +00003472 const Function *F = cast<Function>(I.getOperand(2)->stripPointerCasts());
Duncan Sands36397f52007-07-27 12:58:54 +00003473
Dan Gohman475871a2008-07-27 21:46:04 +00003474 SDValue Ops[6];
Duncan Sands36397f52007-07-27 12:58:54 +00003475 Ops[0] = getRoot();
3476 Ops[1] = getValue(I.getOperand(1));
3477 Ops[2] = getValue(I.getOperand(2));
3478 Ops[3] = getValue(I.getOperand(3));
3479 Ops[4] = DAG.getSrcValue(I.getOperand(1));
3480 Ops[5] = DAG.getSrcValue(F);
3481
Dan Gohman475871a2008-07-27 21:46:04 +00003482 SDValue Tmp = DAG.getNode(ISD::TRAMPOLINE,
Duncan Sandsf7331b32007-09-11 14:10:23 +00003483 DAG.getNodeValueTypes(TLI.getPointerTy(),
3484 MVT::Other), 2,
3485 Ops, 6);
3486
3487 setValue(&I, Tmp);
3488 DAG.setRoot(Tmp.getValue(1));
Duncan Sands36397f52007-07-27 12:58:54 +00003489 return 0;
3490 }
Gordon Henriksence224772008-01-07 01:30:38 +00003491
3492 case Intrinsic::gcroot:
Gordon Henriksen5eca0752008-08-17 18:44:35 +00003493 if (GFI) {
Gordon Henriksence224772008-01-07 01:30:38 +00003494 Value *Alloca = I.getOperand(1);
3495 Constant *TypeMap = cast<Constant>(I.getOperand(2));
3496
3497 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).Val);
Gordon Henriksen5eca0752008-08-17 18:44:35 +00003498 GFI->addStackRoot(FI->getIndex(), TypeMap);
Gordon Henriksence224772008-01-07 01:30:38 +00003499 }
3500 return 0;
3501
3502 case Intrinsic::gcread:
3503 case Intrinsic::gcwrite:
Gordon Henriksen5eca0752008-08-17 18:44:35 +00003504 assert(0 && "GC failed to lower gcread/gcwrite intrinsics!");
Gordon Henriksence224772008-01-07 01:30:38 +00003505 return 0;
3506
Anton Korobeynikov917c2a62007-11-15 23:25:33 +00003507 case Intrinsic::flt_rounds: {
Dan Gohman1a024862008-01-31 00:41:03 +00003508 setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, MVT::i32));
Anton Korobeynikov917c2a62007-11-15 23:25:33 +00003509 return 0;
3510 }
Anton Korobeynikov66fac792008-01-15 07:02:33 +00003511
3512 case Intrinsic::trap: {
3513 DAG.setRoot(DAG.getNode(ISD::TRAP, MVT::Other, getRoot()));
3514 return 0;
3515 }
Evan Cheng27b7db52008-03-08 00:58:38 +00003516 case Intrinsic::prefetch: {
Dan Gohman475871a2008-07-27 21:46:04 +00003517 SDValue Ops[4];
Evan Cheng27b7db52008-03-08 00:58:38 +00003518 Ops[0] = getRoot();
3519 Ops[1] = getValue(I.getOperand(1));
3520 Ops[2] = getValue(I.getOperand(2));
3521 Ops[3] = getValue(I.getOperand(3));
3522 DAG.setRoot(DAG.getNode(ISD::PREFETCH, MVT::Other, &Ops[0], 4));
3523 return 0;
3524 }
3525
Andrew Lenharth22c5c1b2008-02-16 01:24:58 +00003526 case Intrinsic::memory_barrier: {
Dan Gohman475871a2008-07-27 21:46:04 +00003527 SDValue Ops[6];
Andrew Lenharth22c5c1b2008-02-16 01:24:58 +00003528 Ops[0] = getRoot();
3529 for (int x = 1; x < 6; ++x)
3530 Ops[x] = getValue(I.getOperand(x));
3531
3532 DAG.setRoot(DAG.getNode(ISD::MEMBARRIER, MVT::Other, &Ops[0], 6));
3533 return 0;
3534 }
Mon P Wang28873102008-06-25 08:15:39 +00003535 case Intrinsic::atomic_cmp_swap: {
Dan Gohman475871a2008-07-27 21:46:04 +00003536 SDValue Root = getRoot();
3537 SDValue L = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, Root,
Andrew Lenharthab0b9492008-02-21 06:45:13 +00003538 getValue(I.getOperand(1)),
3539 getValue(I.getOperand(2)),
Dan Gohmanfd4418f2008-06-25 16:07:49 +00003540 getValue(I.getOperand(3)),
Mon P Wang28873102008-06-25 08:15:39 +00003541 I.getOperand(1));
Andrew Lenharthab0b9492008-02-21 06:45:13 +00003542 setValue(&I, L);
3543 DAG.setRoot(L.getValue(1));
3544 return 0;
3545 }
Mon P Wang28873102008-06-25 08:15:39 +00003546 case Intrinsic::atomic_load_add:
3547 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_ADD);
3548 case Intrinsic::atomic_load_sub:
3549 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_SUB);
Mon P Wang63307c32008-05-05 19:05:59 +00003550 case Intrinsic::atomic_load_and:
3551 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_AND);
3552 case Intrinsic::atomic_load_or:
3553 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_OR);
3554 case Intrinsic::atomic_load_xor:
3555 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_XOR);
Andrew Lenharth507a58a2008-06-14 05:48:15 +00003556 case Intrinsic::atomic_load_nand:
3557 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_NAND);
Mon P Wang63307c32008-05-05 19:05:59 +00003558 case Intrinsic::atomic_load_min:
3559 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MIN);
3560 case Intrinsic::atomic_load_max:
3561 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MAX);
3562 case Intrinsic::atomic_load_umin:
3563 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMIN);
3564 case Intrinsic::atomic_load_umax:
3565 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMAX);
3566 case Intrinsic::atomic_swap:
3567 return implVisitBinaryAtomic(I, ISD::ATOMIC_SWAP);
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003568 }
3569}
3570
3571
Dan Gohman475871a2008-07-27 21:46:04 +00003572void SelectionDAGLowering::LowerCallTo(CallSite CS, SDValue Callee,
Jim Laskey1da20a72007-02-23 21:45:01 +00003573 bool IsTailCall,
Anton Korobeynikov070280e2007-05-23 11:08:31 +00003574 MachineBasicBlock *LandingPad) {
Duncan Sands6f74b482007-12-19 09:48:52 +00003575 const PointerType *PT = cast<PointerType>(CS.getCalledValue()->getType());
Jim Laskey735b6f82007-02-22 15:38:06 +00003576 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
Anton Korobeynikov070280e2007-05-23 11:08:31 +00003577 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3578 unsigned BeginLabel = 0, EndLabel = 0;
Duncan Sands6f74b482007-12-19 09:48:52 +00003579
Jim Laskey735b6f82007-02-22 15:38:06 +00003580 TargetLowering::ArgListTy Args;
3581 TargetLowering::ArgListEntry Entry;
Duncan Sands6f74b482007-12-19 09:48:52 +00003582 Args.reserve(CS.arg_size());
3583 for (CallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
3584 i != e; ++i) {
Dan Gohman475871a2008-07-27 21:46:04 +00003585 SDValue ArgNode = getValue(*i);
Duncan Sands6f74b482007-12-19 09:48:52 +00003586 Entry.Node = ArgNode; Entry.Ty = (*i)->getType();
Duncan Sands4fee7032007-05-07 20:49:28 +00003587
Duncan Sands6f74b482007-12-19 09:48:52 +00003588 unsigned attrInd = i - CS.arg_begin() + 1;
3589 Entry.isSExt = CS.paramHasAttr(attrInd, ParamAttr::SExt);
3590 Entry.isZExt = CS.paramHasAttr(attrInd, ParamAttr::ZExt);
3591 Entry.isInReg = CS.paramHasAttr(attrInd, ParamAttr::InReg);
3592 Entry.isSRet = CS.paramHasAttr(attrInd, ParamAttr::StructRet);
3593 Entry.isNest = CS.paramHasAttr(attrInd, ParamAttr::Nest);
3594 Entry.isByVal = CS.paramHasAttr(attrInd, ParamAttr::ByVal);
Dale Johannesen08e78b12008-02-22 17:49:45 +00003595 Entry.Alignment = CS.getParamAlignment(attrInd);
Jim Laskey735b6f82007-02-22 15:38:06 +00003596 Args.push_back(Entry);
3597 }
3598
Dale Johannesen1532f3d2008-04-02 00:25:04 +00003599 if (LandingPad && MMI) {
Anton Korobeynikov070280e2007-05-23 11:08:31 +00003600 // Insert a label before the invoke call to mark the try range. This can be
3601 // used to detect deletion of the invoke via the MachineModuleInfo.
3602 BeginLabel = MMI->NextLabelID();
Dale Johannesena4091d32008-04-04 23:48:31 +00003603 // Both PendingLoads and PendingExports must be flushed here;
3604 // this call might not return.
3605 (void)getRoot();
Dan Gohman44066042008-07-01 00:05:16 +00003606 DAG.setRoot(DAG.getLabel(ISD::EH_LABEL, getControlRoot(), BeginLabel));
Anton Korobeynikov070280e2007-05-23 11:08:31 +00003607 }
Duncan Sands6f74b482007-12-19 09:48:52 +00003608
Dan Gohman475871a2008-07-27 21:46:04 +00003609 std::pair<SDValue,SDValue> Result =
Duncan Sands6f74b482007-12-19 09:48:52 +00003610 TLI.LowerCallTo(getRoot(), CS.getType(),
3611 CS.paramHasAttr(0, ParamAttr::SExt),
Duncan Sands00fee652008-02-14 17:28:50 +00003612 CS.paramHasAttr(0, ParamAttr::ZExt),
Duncan Sands6f74b482007-12-19 09:48:52 +00003613 FTy->isVarArg(), CS.getCallingConv(), IsTailCall,
Jim Laskey735b6f82007-02-22 15:38:06 +00003614 Callee, Args, DAG);
Duncan Sands6f74b482007-12-19 09:48:52 +00003615 if (CS.getType() != Type::VoidTy)
3616 setValue(CS.getInstruction(), Result.first);
Jim Laskey735b6f82007-02-22 15:38:06 +00003617 DAG.setRoot(Result.second);
Anton Korobeynikov070280e2007-05-23 11:08:31 +00003618
Dale Johannesen1532f3d2008-04-02 00:25:04 +00003619 if (LandingPad && MMI) {
Anton Korobeynikov070280e2007-05-23 11:08:31 +00003620 // Insert a label at the end of the invoke call to mark the try range. This
3621 // can be used to detect deletion of the invoke via the MachineModuleInfo.
3622 EndLabel = MMI->NextLabelID();
Dan Gohman44066042008-07-01 00:05:16 +00003623 DAG.setRoot(DAG.getLabel(ISD::EH_LABEL, getRoot(), EndLabel));
Anton Korobeynikov070280e2007-05-23 11:08:31 +00003624
Duncan Sands6f74b482007-12-19 09:48:52 +00003625 // Inform MachineModuleInfo of range.
Anton Korobeynikov070280e2007-05-23 11:08:31 +00003626 MMI->addInvoke(LandingPad, BeginLabel, EndLabel);
3627 }
Jim Laskey735b6f82007-02-22 15:38:06 +00003628}
3629
3630
Chris Lattner1c08c712005-01-07 07:47:53 +00003631void SelectionDAGLowering::visitCall(CallInst &I) {
Chris Lattner64e14b12005-01-08 22:48:57 +00003632 const char *RenameFn = 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003633 if (Function *F = I.getCalledFunction()) {
Chris Lattner87b51bc2007-09-10 21:15:22 +00003634 if (F->isDeclaration()) {
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003635 if (unsigned IID = F->getIntrinsicID()) {
3636 RenameFn = visitIntrinsicCall(I, IID);
3637 if (!RenameFn)
3638 return;
Chris Lattner87b51bc2007-09-10 21:15:22 +00003639 }
3640 }
3641
3642 // Check for well-known libc/libm calls. If the function is internal, it
3643 // can't be a library call.
3644 unsigned NameLen = F->getNameLen();
3645 if (!F->hasInternalLinkage() && NameLen) {
3646 const char *NameStr = F->getNameStart();
3647 if (NameStr[0] == 'c' &&
3648 ((NameLen == 8 && !strcmp(NameStr, "copysign")) ||
3649 (NameLen == 9 && !strcmp(NameStr, "copysignf")))) {
3650 if (I.getNumOperands() == 3 && // Basic sanity checks.
3651 I.getOperand(1)->getType()->isFloatingPoint() &&
3652 I.getType() == I.getOperand(1)->getType() &&
3653 I.getType() == I.getOperand(2)->getType()) {
Dan Gohman475871a2008-07-27 21:46:04 +00003654 SDValue LHS = getValue(I.getOperand(1));
3655 SDValue RHS = getValue(I.getOperand(2));
Chris Lattner87b51bc2007-09-10 21:15:22 +00003656 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, LHS.getValueType(),
3657 LHS, RHS));
3658 return;
3659 }
3660 } else if (NameStr[0] == 'f' &&
3661 ((NameLen == 4 && !strcmp(NameStr, "fabs")) ||
Dale Johannesen2f429012007-09-26 21:10:55 +00003662 (NameLen == 5 && !strcmp(NameStr, "fabsf")) ||
3663 (NameLen == 5 && !strcmp(NameStr, "fabsl")))) {
Chris Lattner87b51bc2007-09-10 21:15:22 +00003664 if (I.getNumOperands() == 2 && // Basic sanity checks.
3665 I.getOperand(1)->getType()->isFloatingPoint() &&
3666 I.getType() == I.getOperand(1)->getType()) {
Dan Gohman475871a2008-07-27 21:46:04 +00003667 SDValue Tmp = getValue(I.getOperand(1));
Chris Lattner87b51bc2007-09-10 21:15:22 +00003668 setValue(&I, DAG.getNode(ISD::FABS, Tmp.getValueType(), Tmp));
3669 return;
3670 }
3671 } else if (NameStr[0] == 's' &&
3672 ((NameLen == 3 && !strcmp(NameStr, "sin")) ||
Dale Johannesen2f429012007-09-26 21:10:55 +00003673 (NameLen == 4 && !strcmp(NameStr, "sinf")) ||
3674 (NameLen == 4 && !strcmp(NameStr, "sinl")))) {
Chris Lattner87b51bc2007-09-10 21:15:22 +00003675 if (I.getNumOperands() == 2 && // Basic sanity checks.
3676 I.getOperand(1)->getType()->isFloatingPoint() &&
3677 I.getType() == I.getOperand(1)->getType()) {
Dan Gohman475871a2008-07-27 21:46:04 +00003678 SDValue Tmp = getValue(I.getOperand(1));
Chris Lattner87b51bc2007-09-10 21:15:22 +00003679 setValue(&I, DAG.getNode(ISD::FSIN, Tmp.getValueType(), Tmp));
3680 return;
3681 }
3682 } else if (NameStr[0] == 'c' &&
3683 ((NameLen == 3 && !strcmp(NameStr, "cos")) ||
Dale Johannesen2f429012007-09-26 21:10:55 +00003684 (NameLen == 4 && !strcmp(NameStr, "cosf")) ||
3685 (NameLen == 4 && !strcmp(NameStr, "cosl")))) {
Chris Lattner87b51bc2007-09-10 21:15:22 +00003686 if (I.getNumOperands() == 2 && // Basic sanity checks.
3687 I.getOperand(1)->getType()->isFloatingPoint() &&
3688 I.getType() == I.getOperand(1)->getType()) {
Dan Gohman475871a2008-07-27 21:46:04 +00003689 SDValue Tmp = getValue(I.getOperand(1));
Chris Lattner87b51bc2007-09-10 21:15:22 +00003690 setValue(&I, DAG.getNode(ISD::FCOS, Tmp.getValueType(), Tmp));
3691 return;
Chris Lattnerf76e7dc2005-04-30 04:43:14 +00003692 }
Chris Lattner1ca85d52005-05-14 13:56:55 +00003693 }
Chris Lattner87b51bc2007-09-10 21:15:22 +00003694 }
Chris Lattnerce7518c2006-01-26 22:24:51 +00003695 } else if (isa<InlineAsm>(I.getOperand(0))) {
Duncan Sandsfd7b3262007-12-17 18:08:19 +00003696 visitInlineAsm(&I);
Chris Lattnerce7518c2006-01-26 22:24:51 +00003697 return;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003698 }
Misha Brukmanedf128a2005-04-21 22:36:52 +00003699
Dan Gohman475871a2008-07-27 21:46:04 +00003700 SDValue Callee;
Chris Lattner64e14b12005-01-08 22:48:57 +00003701 if (!RenameFn)
3702 Callee = getValue(I.getOperand(0));
3703 else
3704 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
Anton Korobeynikov070280e2007-05-23 11:08:31 +00003705
Duncan Sands6f74b482007-12-19 09:48:52 +00003706 LowerCallTo(&I, Callee, I.isTailCall());
Chris Lattner1c08c712005-01-07 07:47:53 +00003707}
3708
Jim Laskey735b6f82007-02-22 15:38:06 +00003709
Dan Gohmanb6f5b002007-06-28 23:29:44 +00003710/// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
3711/// this value and returns the result as a ValueVT value. This uses
3712/// Chain/Flag as the input and updates them for the output Chain/Flag.
3713/// If the Flag pointer is NULL, no flag is used.
Dan Gohman475871a2008-07-27 21:46:04 +00003714SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
3715 SDValue &Chain,
3716 SDValue *Flag) const {
Dan Gohman23ce5022008-04-25 18:27:55 +00003717 // Assemble the legal parts into the final values.
Dan Gohman475871a2008-07-27 21:46:04 +00003718 SmallVector<SDValue, 4> Values(ValueVTs.size());
3719 SmallVector<SDValue, 8> Parts;
Chris Lattner6833b062008-04-28 07:16:35 +00003720 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
Dan Gohman23ce5022008-04-25 18:27:55 +00003721 // Copy the legal parts from the registers.
Duncan Sands83ec4b62008-06-06 12:08:01 +00003722 MVT ValueVT = ValueVTs[Value];
Dan Gohman23ce5022008-04-25 18:27:55 +00003723 unsigned NumRegs = TLI->getNumRegisters(ValueVT);
Duncan Sands83ec4b62008-06-06 12:08:01 +00003724 MVT RegisterVT = RegVTs[Value];
Dan Gohman23ce5022008-04-25 18:27:55 +00003725
Chris Lattner6833b062008-04-28 07:16:35 +00003726 Parts.resize(NumRegs);
Dan Gohman23ce5022008-04-25 18:27:55 +00003727 for (unsigned i = 0; i != NumRegs; ++i) {
Dan Gohman475871a2008-07-27 21:46:04 +00003728 SDValue P;
Chris Lattner6833b062008-04-28 07:16:35 +00003729 if (Flag == 0)
3730 P = DAG.getCopyFromReg(Chain, Regs[Part+i], RegisterVT);
3731 else {
3732 P = DAG.getCopyFromReg(Chain, Regs[Part+i], RegisterVT, *Flag);
Dan Gohman23ce5022008-04-25 18:27:55 +00003733 *Flag = P.getValue(2);
Chris Lattner6833b062008-04-28 07:16:35 +00003734 }
3735 Chain = P.getValue(1);
Chris Lattneread0d882008-06-17 06:09:18 +00003736
3737 // If the source register was virtual and if we know something about it,
3738 // add an assert node.
3739 if (TargetRegisterInfo::isVirtualRegister(Regs[Part+i]) &&
3740 RegisterVT.isInteger() && !RegisterVT.isVector()) {
3741 unsigned SlotNo = Regs[Part+i]-TargetRegisterInfo::FirstVirtualRegister;
3742 FunctionLoweringInfo &FLI = DAG.getFunctionLoweringInfo();
3743 if (FLI.LiveOutRegInfo.size() > SlotNo) {
3744 FunctionLoweringInfo::LiveOutInfo &LOI = FLI.LiveOutRegInfo[SlotNo];
3745
3746 unsigned RegSize = RegisterVT.getSizeInBits();
3747 unsigned NumSignBits = LOI.NumSignBits;
3748 unsigned NumZeroBits = LOI.KnownZero.countLeadingOnes();
3749
3750 // FIXME: We capture more information than the dag can represent. For
3751 // now, just use the tightest assertzext/assertsext possible.
3752 bool isSExt = true;
3753 MVT FromVT(MVT::Other);
3754 if (NumSignBits == RegSize)
3755 isSExt = true, FromVT = MVT::i1; // ASSERT SEXT 1
3756 else if (NumZeroBits >= RegSize-1)
3757 isSExt = false, FromVT = MVT::i1; // ASSERT ZEXT 1
3758 else if (NumSignBits > RegSize-8)
3759 isSExt = true, FromVT = MVT::i8; // ASSERT SEXT 8
3760 else if (NumZeroBits >= RegSize-9)
3761 isSExt = false, FromVT = MVT::i8; // ASSERT ZEXT 8
3762 else if (NumSignBits > RegSize-16)
3763 isSExt = true, FromVT = MVT::i16; // ASSERT SEXT 16
3764 else if (NumZeroBits >= RegSize-17)
3765 isSExt = false, FromVT = MVT::i16; // ASSERT ZEXT 16
3766 else if (NumSignBits > RegSize-32)
3767 isSExt = true, FromVT = MVT::i32; // ASSERT SEXT 32
3768 else if (NumZeroBits >= RegSize-33)
3769 isSExt = false, FromVT = MVT::i32; // ASSERT ZEXT 32
3770
3771 if (FromVT != MVT::Other) {
3772 P = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext,
3773 RegisterVT, P, DAG.getValueType(FromVT));
3774
3775 }
3776 }
3777 }
3778
Dan Gohman23ce5022008-04-25 18:27:55 +00003779 Parts[Part+i] = P;
3780 }
Chris Lattner5df99b32007-03-25 05:00:54 +00003781
Dan Gohman23ce5022008-04-25 18:27:55 +00003782 Values[Value] = getCopyFromParts(DAG, &Parts[Part], NumRegs, RegisterVT,
3783 ValueVT);
3784 Part += NumRegs;
3785 }
Duncan Sands4bdcb612008-07-02 17:40:58 +00003786
Duncan Sandsf9516202008-06-30 10:19:09 +00003787 return DAG.getMergeValues(DAG.getVTList(&ValueVTs[0], ValueVTs.size()),
3788 &Values[0], ValueVTs.size());
Chris Lattner864635a2006-02-22 22:37:12 +00003789}
3790
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00003791/// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
3792/// specified value into the registers specified by this object. This uses
3793/// Chain/Flag as the input and updates them for the output Chain/Flag.
Dan Gohmanb6f5b002007-06-28 23:29:44 +00003794/// If the Flag pointer is NULL, no flag is used.
Dan Gohman475871a2008-07-27 21:46:04 +00003795void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG,
3796 SDValue &Chain, SDValue *Flag) const {
Dan Gohmanb6f5b002007-06-28 23:29:44 +00003797 // Get the list of the values's legal parts.
Dan Gohman23ce5022008-04-25 18:27:55 +00003798 unsigned NumRegs = Regs.size();
Dan Gohman475871a2008-07-27 21:46:04 +00003799 SmallVector<SDValue, 8> Parts(NumRegs);
Chris Lattner6833b062008-04-28 07:16:35 +00003800 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
Duncan Sands83ec4b62008-06-06 12:08:01 +00003801 MVT ValueVT = ValueVTs[Value];
Dan Gohman23ce5022008-04-25 18:27:55 +00003802 unsigned NumParts = TLI->getNumRegisters(ValueVT);
Duncan Sands83ec4b62008-06-06 12:08:01 +00003803 MVT RegisterVT = RegVTs[Value];
Dan Gohman23ce5022008-04-25 18:27:55 +00003804
3805 getCopyToParts(DAG, Val.getValue(Val.ResNo + Value),
3806 &Parts[Part], NumParts, RegisterVT);
3807 Part += NumParts;
3808 }
Dan Gohmanb6f5b002007-06-28 23:29:44 +00003809
3810 // Copy the parts into the registers.
Dan Gohman475871a2008-07-27 21:46:04 +00003811 SmallVector<SDValue, 8> Chains(NumRegs);
Dan Gohman23ce5022008-04-25 18:27:55 +00003812 for (unsigned i = 0; i != NumRegs; ++i) {
Dan Gohman475871a2008-07-27 21:46:04 +00003813 SDValue Part;
Chris Lattner6833b062008-04-28 07:16:35 +00003814 if (Flag == 0)
3815 Part = DAG.getCopyToReg(Chain, Regs[i], Parts[i]);
3816 else {
3817 Part = DAG.getCopyToReg(Chain, Regs[i], Parts[i], *Flag);
Dan Gohmanb6f5b002007-06-28 23:29:44 +00003818 *Flag = Part.getValue(1);
Chris Lattner6833b062008-04-28 07:16:35 +00003819 }
3820 Chains[i] = Part.getValue(0);
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00003821 }
Chris Lattner6833b062008-04-28 07:16:35 +00003822
Evan Cheng33bf38a2008-04-28 22:07:13 +00003823 if (NumRegs == 1 || Flag)
3824 // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is
3825 // flagged to it. That is the CopyToReg nodes and the user are considered
3826 // a single scheduling unit. If we create a TokenFactor and return it as
3827 // chain, then the TokenFactor is both a predecessor (operand) of the
3828 // user as well as a successor (the TF operands are flagged to the user).
3829 // c1, f1 = CopyToReg
3830 // c2, f2 = CopyToReg
3831 // c3 = TokenFactor c1, c2
3832 // ...
3833 // = op c3, ..., f2
3834 Chain = Chains[NumRegs-1];
Chris Lattner6833b062008-04-28 07:16:35 +00003835 else
3836 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other, &Chains[0], NumRegs);
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00003837}
Chris Lattner864635a2006-02-22 22:37:12 +00003838
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00003839/// AddInlineAsmOperands - Add this value to the specified inlineasm node
3840/// operand list. This adds the code marker and includes the number of
3841/// values added into it.
3842void RegsForValue::AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
Dan Gohman475871a2008-07-27 21:46:04 +00003843 std::vector<SDValue> &Ops) const {
Duncan Sands83ec4b62008-06-06 12:08:01 +00003844 MVT IntPtrTy = DAG.getTargetLoweringInfo().getPointerTy();
Chris Lattner4b993b12007-04-09 00:33:58 +00003845 Ops.push_back(DAG.getTargetConstant(Code | (Regs.size() << 3), IntPtrTy));
Chris Lattner6833b062008-04-28 07:16:35 +00003846 for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
3847 unsigned NumRegs = TLI->getNumRegisters(ValueVTs[Value]);
Duncan Sands83ec4b62008-06-06 12:08:01 +00003848 MVT RegisterVT = RegVTs[Value];
Chris Lattner6833b062008-04-28 07:16:35 +00003849 for (unsigned i = 0; i != NumRegs; ++i)
3850 Ops.push_back(DAG.getRegister(Regs[Reg++], RegisterVT));
Dan Gohman23ce5022008-04-25 18:27:55 +00003851 }
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00003852}
Chris Lattner864635a2006-02-22 22:37:12 +00003853
3854/// isAllocatableRegister - If the specified register is safe to allocate,
3855/// i.e. it isn't a stack pointer or some other special register, return the
3856/// register class for the register. Otherwise, return null.
3857static const TargetRegisterClass *
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00003858isAllocatableRegister(unsigned Reg, MachineFunction &MF,
Dan Gohman6f0d0242008-02-10 18:45:23 +00003859 const TargetLowering &TLI,
3860 const TargetRegisterInfo *TRI) {
Duncan Sands83ec4b62008-06-06 12:08:01 +00003861 MVT FoundVT = MVT::Other;
Chris Lattnerf8814cf2006-04-02 00:24:45 +00003862 const TargetRegisterClass *FoundRC = 0;
Dan Gohman6f0d0242008-02-10 18:45:23 +00003863 for (TargetRegisterInfo::regclass_iterator RCI = TRI->regclass_begin(),
3864 E = TRI->regclass_end(); RCI != E; ++RCI) {
Duncan Sands83ec4b62008-06-06 12:08:01 +00003865 MVT ThisVT = MVT::Other;
Chris Lattnerf8814cf2006-04-02 00:24:45 +00003866
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00003867 const TargetRegisterClass *RC = *RCI;
3868 // If none of the the value types for this register class are valid, we
3869 // can't use it. For example, 64-bit reg classes on 32-bit targets.
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00003870 for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
3871 I != E; ++I) {
3872 if (TLI.isTypeLegal(*I)) {
Chris Lattnerf8814cf2006-04-02 00:24:45 +00003873 // If we have already found this register in a different register class,
3874 // choose the one with the largest VT specified. For example, on
3875 // PowerPC, we favor f64 register classes over f32.
Duncan Sands8e4eb092008-06-08 20:54:56 +00003876 if (FoundVT == MVT::Other || FoundVT.bitsLT(*I)) {
Chris Lattnerf8814cf2006-04-02 00:24:45 +00003877 ThisVT = *I;
3878 break;
3879 }
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00003880 }
3881 }
3882
Chris Lattnerf8814cf2006-04-02 00:24:45 +00003883 if (ThisVT == MVT::Other) continue;
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00003884
Chris Lattner864635a2006-02-22 22:37:12 +00003885 // NOTE: This isn't ideal. In particular, this might allocate the
3886 // frame pointer in functions that need it (due to them not being taken
3887 // out of allocation, because a variable sized allocation hasn't been seen
3888 // yet). This is a slight code pessimization, but should still work.
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00003889 for (TargetRegisterClass::iterator I = RC->allocation_order_begin(MF),
3890 E = RC->allocation_order_end(MF); I != E; ++I)
Chris Lattnerf8814cf2006-04-02 00:24:45 +00003891 if (*I == Reg) {
3892 // We found a matching register class. Keep looking at others in case
3893 // we find one with larger registers that this physreg is also in.
3894 FoundRC = RC;
3895 FoundVT = ThisVT;
3896 break;
3897 }
Chris Lattner4e4b5762006-02-01 18:59:47 +00003898 }
Chris Lattnerf8814cf2006-04-02 00:24:45 +00003899 return FoundRC;
Chris Lattner864635a2006-02-22 22:37:12 +00003900}
3901
Chris Lattner4e4b5762006-02-01 18:59:47 +00003902
Chris Lattner0c583402007-04-28 20:49:53 +00003903namespace {
3904/// AsmOperandInfo - This contains information for each constraint that we are
3905/// lowering.
Evan Cheng5c807602008-02-26 02:33:44 +00003906struct SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo {
3907 /// CallOperand - If this is the result output operand or a clobber
3908 /// this is null, otherwise it is the incoming operand to the CallInst.
3909 /// This gets modified as the asm is processed.
Dan Gohman475871a2008-07-27 21:46:04 +00003910 SDValue CallOperand;
Evan Cheng5c807602008-02-26 02:33:44 +00003911
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003912 /// AssignedRegs - If this is a register or register class operand, this
3913 /// contains the set of register corresponding to the operand.
3914 RegsForValue AssignedRegs;
3915
Dan Gohman23ce5022008-04-25 18:27:55 +00003916 explicit SDISelAsmOperandInfo(const InlineAsm::ConstraintInfo &info)
Evan Cheng5c807602008-02-26 02:33:44 +00003917 : TargetLowering::AsmOperandInfo(info), CallOperand(0,0) {
Chris Lattner0c583402007-04-28 20:49:53 +00003918 }
Chris Lattner3ff90dc2007-04-30 17:16:27 +00003919
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003920 /// MarkAllocatedRegs - Once AssignedRegs is set, mark the assigned registers
3921 /// busy in OutputRegs/InputRegs.
3922 void MarkAllocatedRegs(bool isOutReg, bool isInReg,
3923 std::set<unsigned> &OutputRegs,
Chris Lattner7cbeb242008-02-21 04:55:52 +00003924 std::set<unsigned> &InputRegs,
3925 const TargetRegisterInfo &TRI) const {
3926 if (isOutReg) {
3927 for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i)
3928 MarkRegAndAliases(AssignedRegs.Regs[i], OutputRegs, TRI);
3929 }
3930 if (isInReg) {
3931 for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i)
3932 MarkRegAndAliases(AssignedRegs.Regs[i], InputRegs, TRI);
3933 }
3934 }
3935
3936private:
3937 /// MarkRegAndAliases - Mark the specified register and all aliases in the
3938 /// specified set.
3939 static void MarkRegAndAliases(unsigned Reg, std::set<unsigned> &Regs,
3940 const TargetRegisterInfo &TRI) {
3941 assert(TargetRegisterInfo::isPhysicalRegister(Reg) && "Isn't a physreg");
3942 Regs.insert(Reg);
3943 if (const unsigned *Aliases = TRI.getAliasSet(Reg))
3944 for (; *Aliases; ++Aliases)
3945 Regs.insert(*Aliases);
3946 }
Chris Lattner0c583402007-04-28 20:49:53 +00003947};
3948} // end anon namespace.
Chris Lattner864635a2006-02-22 22:37:12 +00003949
Chris Lattner3ff90dc2007-04-30 17:16:27 +00003950
Chris Lattner0fe71e92008-02-21 19:43:13 +00003951/// GetRegistersForValue - Assign registers (virtual or physical) for the
3952/// specified operand. We prefer to assign virtual registers, to allow the
3953/// register allocator handle the assignment process. However, if the asm uses
3954/// features that we can't model on machineinstrs, we have SDISel do the
3955/// allocation. This produces generally horrible, but correct, code.
3956///
3957/// OpInfo describes the operand.
3958/// HasEarlyClobber is true if there are any early clobber constraints (=&r)
3959/// or any explicitly clobbered registers.
3960/// Input and OutputRegs are the set of already allocated physical registers.
3961///
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003962void SelectionDAGLowering::
Evan Cheng5c807602008-02-26 02:33:44 +00003963GetRegistersForValue(SDISelAsmOperandInfo &OpInfo, bool HasEarlyClobber,
Chris Lattnerbf996f12007-04-30 17:29:31 +00003964 std::set<unsigned> &OutputRegs,
3965 std::set<unsigned> &InputRegs) {
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003966 // Compute whether this value requires an input register, an output register,
3967 // or both.
3968 bool isOutReg = false;
3969 bool isInReg = false;
3970 switch (OpInfo.Type) {
3971 case InlineAsm::isOutput:
3972 isOutReg = true;
3973
3974 // If this is an early-clobber output, or if there is an input
3975 // constraint that matches this, we need to reserve the input register
3976 // so no other inputs allocate to it.
3977 isInReg = OpInfo.isEarlyClobber || OpInfo.hasMatchingInput;
3978 break;
3979 case InlineAsm::isInput:
3980 isInReg = true;
3981 isOutReg = false;
3982 break;
3983 case InlineAsm::isClobber:
3984 isOutReg = true;
3985 isInReg = true;
3986 break;
3987 }
3988
3989
3990 MachineFunction &MF = DAG.getMachineFunction();
Chris Lattnerb606dba2008-04-28 06:44:42 +00003991 SmallVector<unsigned, 4> Regs;
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003992
3993 // If this is a constraint for a single physreg, or a constraint for a
3994 // register class, find it.
3995 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
3996 TLI.getRegForInlineAsmConstraint(OpInfo.ConstraintCode,
3997 OpInfo.ConstraintVT);
Chris Lattnerbf996f12007-04-30 17:29:31 +00003998
3999 unsigned NumRegs = 1;
4000 if (OpInfo.ConstraintVT != MVT::Other)
Dan Gohmanb9f10192007-06-21 14:42:22 +00004001 NumRegs = TLI.getNumRegisters(OpInfo.ConstraintVT);
Duncan Sands83ec4b62008-06-06 12:08:01 +00004002 MVT RegVT;
4003 MVT ValueVT = OpInfo.ConstraintVT;
Chris Lattnerbf996f12007-04-30 17:29:31 +00004004
Chris Lattnerbf996f12007-04-30 17:29:31 +00004005
4006 // If this is a constraint for a specific physical register, like {r17},
4007 // assign it now.
4008 if (PhysReg.first) {
4009 if (OpInfo.ConstraintVT == MVT::Other)
4010 ValueVT = *PhysReg.second->vt_begin();
4011
4012 // Get the actual register value type. This is important, because the user
4013 // may have asked for (e.g.) the AX register in i32 type. We need to
4014 // remember that AX is actually i16 to get the right extension.
4015 RegVT = *PhysReg.second->vt_begin();
4016
4017 // This is a explicit reference to a physical register.
4018 Regs.push_back(PhysReg.first);
4019
4020 // If this is an expanded reference, add the rest of the regs to Regs.
4021 if (NumRegs != 1) {
4022 TargetRegisterClass::iterator I = PhysReg.second->begin();
Chris Lattnerbf996f12007-04-30 17:29:31 +00004023 for (; *I != PhysReg.first; ++I)
Evan Cheng50871242008-05-14 20:07:51 +00004024 assert(I != PhysReg.second->end() && "Didn't find reg!");
Chris Lattnerbf996f12007-04-30 17:29:31 +00004025
4026 // Already added the first reg.
4027 --NumRegs; ++I;
4028 for (; NumRegs; --NumRegs, ++I) {
Evan Cheng50871242008-05-14 20:07:51 +00004029 assert(I != PhysReg.second->end() && "Ran out of registers to allocate!");
Chris Lattnerbf996f12007-04-30 17:29:31 +00004030 Regs.push_back(*I);
4031 }
4032 }
Dan Gohman23ce5022008-04-25 18:27:55 +00004033 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, RegVT, ValueVT);
Chris Lattner7cbeb242008-02-21 04:55:52 +00004034 const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
4035 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TRI);
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004036 return;
Chris Lattnerbf996f12007-04-30 17:29:31 +00004037 }
4038
4039 // Otherwise, if this was a reference to an LLVM register class, create vregs
4040 // for this reference.
4041 std::vector<unsigned> RegClassRegs;
Chris Lattnerc2c28fc2007-06-15 19:11:01 +00004042 const TargetRegisterClass *RC = PhysReg.second;
4043 if (RC) {
Chris Lattnerbf996f12007-04-30 17:29:31 +00004044 // If this is an early clobber or tied register, our regalloc doesn't know
4045 // how to maintain the constraint. If it isn't, go ahead and create vreg
4046 // and let the regalloc do the right thing.
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004047 if (!OpInfo.hasMatchingInput && !OpInfo.isEarlyClobber &&
4048 // If there is some other early clobber and this is an input register,
4049 // then we are forced to pre-allocate the input reg so it doesn't
4050 // conflict with the earlyclobber.
4051 !(OpInfo.Type == InlineAsm::isInput && HasEarlyClobber)) {
Chris Lattnerbf996f12007-04-30 17:29:31 +00004052 RegVT = *PhysReg.second->vt_begin();
4053
4054 if (OpInfo.ConstraintVT == MVT::Other)
4055 ValueVT = RegVT;
4056
4057 // Create the appropriate number of virtual registers.
Chris Lattner84bc5422007-12-31 04:13:23 +00004058 MachineRegisterInfo &RegInfo = MF.getRegInfo();
Chris Lattnerbf996f12007-04-30 17:29:31 +00004059 for (; NumRegs; --NumRegs)
Chris Lattner84bc5422007-12-31 04:13:23 +00004060 Regs.push_back(RegInfo.createVirtualRegister(PhysReg.second));
Chris Lattnerbf996f12007-04-30 17:29:31 +00004061
Dan Gohman23ce5022008-04-25 18:27:55 +00004062 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, RegVT, ValueVT);
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004063 return;
Chris Lattnerbf996f12007-04-30 17:29:31 +00004064 }
4065
4066 // Otherwise, we can't allocate it. Let the code below figure out how to
4067 // maintain these constraints.
4068 RegClassRegs.assign(PhysReg.second->begin(), PhysReg.second->end());
4069
4070 } else {
4071 // This is a reference to a register class that doesn't directly correspond
4072 // to an LLVM register class. Allocate NumRegs consecutive, available,
4073 // registers from the class.
4074 RegClassRegs = TLI.getRegClassForInlineAsmConstraint(OpInfo.ConstraintCode,
4075 OpInfo.ConstraintVT);
4076 }
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004077
Dan Gohman6f0d0242008-02-10 18:45:23 +00004078 const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
Chris Lattnerbf996f12007-04-30 17:29:31 +00004079 unsigned NumAllocated = 0;
4080 for (unsigned i = 0, e = RegClassRegs.size(); i != e; ++i) {
4081 unsigned Reg = RegClassRegs[i];
4082 // See if this register is available.
4083 if ((isOutReg && OutputRegs.count(Reg)) || // Already used.
4084 (isInReg && InputRegs.count(Reg))) { // Already used.
4085 // Make sure we find consecutive registers.
4086 NumAllocated = 0;
4087 continue;
4088 }
4089
4090 // Check to see if this register is allocatable (i.e. don't give out the
4091 // stack pointer).
Chris Lattnerc2c28fc2007-06-15 19:11:01 +00004092 if (RC == 0) {
Dan Gohman6f0d0242008-02-10 18:45:23 +00004093 RC = isAllocatableRegister(Reg, MF, TLI, TRI);
Chris Lattnerc2c28fc2007-06-15 19:11:01 +00004094 if (!RC) { // Couldn't allocate this register.
4095 // Reset NumAllocated to make sure we return consecutive registers.
4096 NumAllocated = 0;
4097 continue;
4098 }
Chris Lattnerbf996f12007-04-30 17:29:31 +00004099 }
4100
4101 // Okay, this register is good, we can use it.
4102 ++NumAllocated;
4103
4104 // If we allocated enough consecutive registers, succeed.
4105 if (NumAllocated == NumRegs) {
4106 unsigned RegStart = (i-NumAllocated)+1;
4107 unsigned RegEnd = i+1;
4108 // Mark all of the allocated registers used.
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004109 for (unsigned i = RegStart; i != RegEnd; ++i)
4110 Regs.push_back(RegClassRegs[i]);
Chris Lattnerbf996f12007-04-30 17:29:31 +00004111
Dan Gohman23ce5022008-04-25 18:27:55 +00004112 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, *RC->vt_begin(),
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004113 OpInfo.ConstraintVT);
Chris Lattner7cbeb242008-02-21 04:55:52 +00004114 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TRI);
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004115 return;
Chris Lattnerbf996f12007-04-30 17:29:31 +00004116 }
4117 }
4118
4119 // Otherwise, we couldn't allocate enough registers for this.
Chris Lattnerbf996f12007-04-30 17:29:31 +00004120}
4121
4122
Chris Lattnerce7518c2006-01-26 22:24:51 +00004123/// visitInlineAsm - Handle a call to an InlineAsm object.
4124///
Duncan Sandsfd7b3262007-12-17 18:08:19 +00004125void SelectionDAGLowering::visitInlineAsm(CallSite CS) {
4126 InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
Chris Lattnerce7518c2006-01-26 22:24:51 +00004127
Chris Lattner0c583402007-04-28 20:49:53 +00004128 /// ConstraintOperands - Information about all of the constraints.
Evan Cheng5c807602008-02-26 02:33:44 +00004129 std::vector<SDISelAsmOperandInfo> ConstraintOperands;
Chris Lattnerce7518c2006-01-26 22:24:51 +00004130
Dan Gohman475871a2008-07-27 21:46:04 +00004131 SDValue Chain = getRoot();
4132 SDValue Flag;
Chris Lattnerce7518c2006-01-26 22:24:51 +00004133
Chris Lattner4e4b5762006-02-01 18:59:47 +00004134 std::set<unsigned> OutputRegs, InputRegs;
Chris Lattner1efa40f2006-02-22 00:56:39 +00004135
Chris Lattner0c583402007-04-28 20:49:53 +00004136 // Do a prepass over the constraints, canonicalizing them, and building up the
4137 // ConstraintOperands list.
4138 std::vector<InlineAsm::ConstraintInfo>
4139 ConstraintInfos = IA->ParseConstraints();
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004140
4141 // SawEarlyClobber - Keep track of whether we saw an earlyclobber output
4142 // constraint. If so, we can't let the register allocator allocate any input
4143 // registers, because it will not know to avoid the earlyclobbered output reg.
4144 bool SawEarlyClobber = false;
4145
Duncan Sandsfd7b3262007-12-17 18:08:19 +00004146 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst.
Chris Lattneracf8b012008-04-27 23:44:28 +00004147 unsigned ResNo = 0; // ResNo - The result number of the next output.
Chris Lattner0c583402007-04-28 20:49:53 +00004148 for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) {
Evan Cheng5c807602008-02-26 02:33:44 +00004149 ConstraintOperands.push_back(SDISelAsmOperandInfo(ConstraintInfos[i]));
4150 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
Chris Lattner0c583402007-04-28 20:49:53 +00004151
Duncan Sands83ec4b62008-06-06 12:08:01 +00004152 MVT OpVT = MVT::Other;
Chris Lattner0c583402007-04-28 20:49:53 +00004153
4154 // Compute the value type for each operand.
4155 switch (OpInfo.Type) {
Chris Lattner1efa40f2006-02-22 00:56:39 +00004156 case InlineAsm::isOutput:
Chris Lattneracf8b012008-04-27 23:44:28 +00004157 // Indirect outputs just consume an argument.
4158 if (OpInfo.isIndirect) {
Duncan Sandsfd7b3262007-12-17 18:08:19 +00004159 OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
Chris Lattneracf8b012008-04-27 23:44:28 +00004160 break;
Chris Lattner1efa40f2006-02-22 00:56:39 +00004161 }
Chris Lattneracf8b012008-04-27 23:44:28 +00004162 // The return value of the call is this value. As such, there is no
4163 // corresponding argument.
4164 assert(CS.getType() != Type::VoidTy && "Bad inline asm!");
4165 if (const StructType *STy = dyn_cast<StructType>(CS.getType())) {
4166 OpVT = TLI.getValueType(STy->getElementType(ResNo));
4167 } else {
4168 assert(ResNo == 0 && "Asm only has one result!");
4169 OpVT = TLI.getValueType(CS.getType());
4170 }
4171 ++ResNo;
Chris Lattner1efa40f2006-02-22 00:56:39 +00004172 break;
4173 case InlineAsm::isInput:
Duncan Sandsfd7b3262007-12-17 18:08:19 +00004174 OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
Chris Lattner1efa40f2006-02-22 00:56:39 +00004175 break;
4176 case InlineAsm::isClobber:
Chris Lattner0c583402007-04-28 20:49:53 +00004177 // Nothing to do.
Chris Lattner1efa40f2006-02-22 00:56:39 +00004178 break;
4179 }
Chris Lattner1efa40f2006-02-22 00:56:39 +00004180
Chris Lattner0c583402007-04-28 20:49:53 +00004181 // If this is an input or an indirect output, process the call argument.
Dale Johanneseneb57ea72007-11-05 21:20:28 +00004182 // BasicBlocks are labels, currently appearing only in asm's.
Chris Lattner0c583402007-04-28 20:49:53 +00004183 if (OpInfo.CallOperandVal) {
Chris Lattner507ffd22008-04-27 00:16:18 +00004184 if (BasicBlock *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal))
4185 OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
Dale Johanneseneb57ea72007-11-05 21:20:28 +00004186 else {
4187 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
4188 const Type *OpTy = OpInfo.CallOperandVal->getType();
4189 // If this is an indirect operand, the operand is a pointer to the
4190 // accessed type.
4191 if (OpInfo.isIndirect)
4192 OpTy = cast<PointerType>(OpTy)->getElementType();
4193
Dan Gohman4fa2a3f2008-05-23 00:34:04 +00004194 // If OpTy is not a single value, it may be a struct/union that we
Dale Johanneseneb57ea72007-11-05 21:20:28 +00004195 // can tile with integers.
Dan Gohman4fa2a3f2008-05-23 00:34:04 +00004196 if (!OpTy->isSingleValueType() && OpTy->isSized()) {
Dale Johanneseneb57ea72007-11-05 21:20:28 +00004197 unsigned BitSize = TD->getTypeSizeInBits(OpTy);
4198 switch (BitSize) {
4199 default: break;
4200 case 1:
4201 case 8:
4202 case 16:
4203 case 32:
4204 case 64:
4205 OpTy = IntegerType::get(BitSize);
4206 break;
4207 }
Chris Lattner6995cf62007-04-29 18:58:03 +00004208 }
Dale Johanneseneb57ea72007-11-05 21:20:28 +00004209
4210 OpVT = TLI.getValueType(OpTy, true);
Chris Lattner0c583402007-04-28 20:49:53 +00004211 }
4212 }
4213
4214 OpInfo.ConstraintVT = OpVT;
Chris Lattner2a600be2007-04-28 21:01:43 +00004215
Chris Lattner3ff90dc2007-04-30 17:16:27 +00004216 // Compute the constraint code and ConstraintType to use.
Chris Lattner5a096902008-04-27 00:37:18 +00004217 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
Chris Lattner0c583402007-04-28 20:49:53 +00004218
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004219 // Keep track of whether we see an earlyclobber.
4220 SawEarlyClobber |= OpInfo.isEarlyClobber;
Chris Lattner09e4b7e2007-04-28 21:12:06 +00004221
Chris Lattner0fe71e92008-02-21 19:43:13 +00004222 // If we see a clobber of a register, it is an early clobber.
Chris Lattner69e6a8d2008-02-21 20:54:31 +00004223 if (!SawEarlyClobber &&
4224 OpInfo.Type == InlineAsm::isClobber &&
4225 OpInfo.ConstraintType == TargetLowering::C_Register) {
4226 // Note that we want to ignore things that we don't trick here, like
4227 // dirflag, fpsr, flags, etc.
4228 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
4229 TLI.getRegForInlineAsmConstraint(OpInfo.ConstraintCode,
4230 OpInfo.ConstraintVT);
4231 if (PhysReg.first || PhysReg.second) {
4232 // This is a register we know of.
4233 SawEarlyClobber = true;
4234 }
4235 }
Chris Lattner0fe71e92008-02-21 19:43:13 +00004236
Chris Lattner09e4b7e2007-04-28 21:12:06 +00004237 // If this is a memory input, and if the operand is not indirect, do what we
4238 // need to to provide an address for the memory input.
4239 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
4240 !OpInfo.isIndirect) {
4241 assert(OpInfo.Type == InlineAsm::isInput &&
4242 "Can only indirectify direct input operands!");
4243
4244 // Memory operands really want the address of the value. If we don't have
4245 // an indirect input, put it in the constpool if we can, otherwise spill
4246 // it to a stack slot.
4247
4248 // If the operand is a float, integer, or vector constant, spill to a
4249 // constant pool entry to get its address.
4250 Value *OpVal = OpInfo.CallOperandVal;
4251 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
4252 isa<ConstantVector>(OpVal)) {
4253 OpInfo.CallOperand = DAG.getConstantPool(cast<Constant>(OpVal),
4254 TLI.getPointerTy());
4255 } else {
4256 // Otherwise, create a stack slot and emit a store to it before the
4257 // asm.
4258 const Type *Ty = OpVal->getType();
Duncan Sands514ab342007-11-01 20:53:16 +00004259 uint64_t TySize = TLI.getTargetData()->getABITypeSize(Ty);
Chris Lattner09e4b7e2007-04-28 21:12:06 +00004260 unsigned Align = TLI.getTargetData()->getPrefTypeAlignment(Ty);
4261 MachineFunction &MF = DAG.getMachineFunction();
4262 int SSFI = MF.getFrameInfo()->CreateStackObject(TySize, Align);
Dan Gohman475871a2008-07-27 21:46:04 +00004263 SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getPointerTy());
Chris Lattner09e4b7e2007-04-28 21:12:06 +00004264 Chain = DAG.getStore(Chain, OpInfo.CallOperand, StackSlot, NULL, 0);
4265 OpInfo.CallOperand = StackSlot;
4266 }
4267
4268 // There is no longer a Value* corresponding to this operand.
4269 OpInfo.CallOperandVal = 0;
4270 // It is now an indirect operand.
4271 OpInfo.isIndirect = true;
4272 }
4273
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004274 // If this constraint is for a specific register, allocate it before
4275 // anything else.
4276 if (OpInfo.ConstraintType == TargetLowering::C_Register)
4277 GetRegistersForValue(OpInfo, SawEarlyClobber, OutputRegs, InputRegs);
Chris Lattner0c583402007-04-28 20:49:53 +00004278 }
Chris Lattner0c583402007-04-28 20:49:53 +00004279 ConstraintInfos.clear();
4280
4281
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004282 // Second pass - Loop over all of the operands, assigning virtual or physregs
4283 // to registerclass operands.
4284 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
Evan Cheng5c807602008-02-26 02:33:44 +00004285 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004286
4287 // C_Register operands have already been allocated, Other/Memory don't need
4288 // to be.
4289 if (OpInfo.ConstraintType == TargetLowering::C_RegisterClass)
4290 GetRegistersForValue(OpInfo, SawEarlyClobber, OutputRegs, InputRegs);
4291 }
4292
Chris Lattner0c583402007-04-28 20:49:53 +00004293 // AsmNodeOperands - The operands for the ISD::INLINEASM node.
Dan Gohman475871a2008-07-27 21:46:04 +00004294 std::vector<SDValue> AsmNodeOperands;
4295 AsmNodeOperands.push_back(SDValue()); // reserve space for input chain
Chris Lattner0c583402007-04-28 20:49:53 +00004296 AsmNodeOperands.push_back(
4297 DAG.getTargetExternalSymbol(IA->getAsmString().c_str(), MVT::Other));
4298
Chris Lattner2cc2f662006-02-01 01:28:23 +00004299
Chris Lattner0f0b7d42006-02-21 23:12:12 +00004300 // Loop over all of the inputs, copying the operand values into the
4301 // appropriate registers and processing the output regs.
Chris Lattner864635a2006-02-22 22:37:12 +00004302 RegsForValue RetValRegs;
Chris Lattner41f62592008-04-29 04:29:54 +00004303
Chris Lattner0c583402007-04-28 20:49:53 +00004304 // IndirectStoresToEmit - The set of stores to emit after the inline asm node.
4305 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
4306
4307 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
Evan Cheng5c807602008-02-26 02:33:44 +00004308 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
Chris Lattner1efa40f2006-02-22 00:56:39 +00004309
Chris Lattner0c583402007-04-28 20:49:53 +00004310 switch (OpInfo.Type) {
Chris Lattner2cc2f662006-02-01 01:28:23 +00004311 case InlineAsm::isOutput: {
Chris Lattnerc83994e2007-04-28 21:03:16 +00004312 if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass &&
4313 OpInfo.ConstraintType != TargetLowering::C_Register) {
Chris Lattnerf2f3cd52007-04-28 06:08:13 +00004314 // Memory output, or 'other' output (e.g. 'X' constraint).
Chris Lattner09e4b7e2007-04-28 21:12:06 +00004315 assert(OpInfo.isIndirect && "Memory output must be indirect operand");
Chris Lattner22873462006-02-27 23:45:39 +00004316
Chris Lattner22873462006-02-27 23:45:39 +00004317 // Add information to the INLINEASM node to know about this output.
4318 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
Chris Lattnerc90233b2007-05-15 01:33:58 +00004319 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
4320 TLI.getPointerTy()));
Chris Lattner09e4b7e2007-04-28 21:12:06 +00004321 AsmNodeOperands.push_back(OpInfo.CallOperand);
Chris Lattner22873462006-02-27 23:45:39 +00004322 break;
4323 }
4324
Chris Lattner2a600be2007-04-28 21:01:43 +00004325 // Otherwise, this is a register or register class output.
Chris Lattner22873462006-02-27 23:45:39 +00004326
Chris Lattner864635a2006-02-22 22:37:12 +00004327 // Copy the output from the appropriate register. Find a register that
Chris Lattner1efa40f2006-02-22 00:56:39 +00004328 // we can use.
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004329 if (OpInfo.AssignedRegs.Regs.empty()) {
Duncan Sandsa47c6c32008-06-17 03:24:13 +00004330 cerr << "Couldn't allocate output reg for constraint '"
Chris Lattner0c583402007-04-28 20:49:53 +00004331 << OpInfo.ConstraintCode << "'!\n";
Chris Lattnerd03f1582006-10-31 07:33:13 +00004332 exit(1);
4333 }
Chris Lattner1efa40f2006-02-22 00:56:39 +00004334
Chris Lattner41f62592008-04-29 04:29:54 +00004335 // If this is an indirect operand, store through the pointer after the
4336 // asm.
4337 if (OpInfo.isIndirect) {
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004338 IndirectStoresToEmit.push_back(std::make_pair(OpInfo.AssignedRegs,
Chris Lattner0c583402007-04-28 20:49:53 +00004339 OpInfo.CallOperandVal));
Chris Lattner41f62592008-04-29 04:29:54 +00004340 } else {
4341 // This is the result value of the call.
4342 assert(CS.getType() != Type::VoidTy && "Bad inline asm!");
4343 // Concatenate this output onto the outputs list.
4344 RetValRegs.append(OpInfo.AssignedRegs);
Chris Lattner2cc2f662006-02-01 01:28:23 +00004345 }
Chris Lattner6656dd12006-01-31 02:03:41 +00004346
4347 // Add information to the INLINEASM node to know that this register is
4348 // set.
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004349 OpInfo.AssignedRegs.AddInlineAsmOperands(2 /*REGDEF*/, DAG,
4350 AsmNodeOperands);
Chris Lattner6656dd12006-01-31 02:03:41 +00004351 break;
4352 }
4353 case InlineAsm::isInput: {
Dan Gohman475871a2008-07-27 21:46:04 +00004354 SDValue InOperandVal = OpInfo.CallOperand;
Chris Lattner3d81fee2006-02-04 02:16:44 +00004355
Chris Lattner0c583402007-04-28 20:49:53 +00004356 if (isdigit(OpInfo.ConstraintCode[0])) { // Matching constraint?
Chris Lattner2223aea2006-02-02 00:25:23 +00004357 // If this is required to match an output register we have already set,
4358 // just use its register.
Chris Lattner0c583402007-04-28 20:49:53 +00004359 unsigned OperandNo = atoi(OpInfo.ConstraintCode.c_str());
Chris Lattner3d81fee2006-02-04 02:16:44 +00004360
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00004361 // Scan until we find the definition we already emitted of this operand.
4362 // When we find it, create a RegsForValue operand.
4363 unsigned CurOp = 2; // The first operand.
4364 for (; OperandNo; --OperandNo) {
4365 // Advance to the next operand.
4366 unsigned NumOps =
4367 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
Chris Lattnera15cf702006-07-20 19:02:21 +00004368 assert(((NumOps & 7) == 2 /*REGDEF*/ ||
4369 (NumOps & 7) == 4 /*MEM*/) &&
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00004370 "Skipped past definitions?");
4371 CurOp += (NumOps>>3)+1;
4372 }
4373
4374 unsigned NumOps =
4375 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
Chris Lattner527fae12007-02-01 01:21:12 +00004376 if ((NumOps & 7) == 2 /*REGDEF*/) {
4377 // Add NumOps>>3 registers to MatchedRegs.
4378 RegsForValue MatchedRegs;
Dan Gohman23ce5022008-04-25 18:27:55 +00004379 MatchedRegs.TLI = &TLI;
Dan Gohman1fa850b2008-05-02 00:03:54 +00004380 MatchedRegs.ValueVTs.push_back(InOperandVal.getValueType());
4381 MatchedRegs.RegVTs.push_back(AsmNodeOperands[CurOp+1].getValueType());
Chris Lattner527fae12007-02-01 01:21:12 +00004382 for (unsigned i = 0, e = NumOps>>3; i != e; ++i) {
4383 unsigned Reg =
4384 cast<RegisterSDNode>(AsmNodeOperands[++CurOp])->getReg();
4385 MatchedRegs.Regs.push_back(Reg);
4386 }
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00004387
Chris Lattner527fae12007-02-01 01:21:12 +00004388 // Use the produced MatchedRegs object to
Dan Gohmanb6f5b002007-06-28 23:29:44 +00004389 MatchedRegs.getCopyToRegs(InOperandVal, DAG, Chain, &Flag);
Chris Lattner527fae12007-02-01 01:21:12 +00004390 MatchedRegs.AddInlineAsmOperands(1 /*REGUSE*/, DAG, AsmNodeOperands);
4391 break;
4392 } else {
4393 assert((NumOps & 7) == 4/*MEM*/ && "Unknown matching constraint!");
Chris Lattnerf9853bc2008-02-21 05:27:19 +00004394 assert((NumOps >> 3) == 1 && "Unexpected number of operands");
4395 // Add information to the INLINEASM node to know about this input.
4396 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
4397 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
4398 TLI.getPointerTy()));
4399 AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
4400 break;
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00004401 }
Chris Lattner2223aea2006-02-02 00:25:23 +00004402 }
Chris Lattner87bc3bd2006-02-24 01:11:24 +00004403
Chris Lattner2a600be2007-04-28 21:01:43 +00004404 if (OpInfo.ConstraintType == TargetLowering::C_Other) {
Chris Lattner0c583402007-04-28 20:49:53 +00004405 assert(!OpInfo.isIndirect &&
Chris Lattner44b2c502007-04-28 06:42:38 +00004406 "Don't know how to handle indirect other inputs yet!");
4407
Dan Gohman475871a2008-07-27 21:46:04 +00004408 std::vector<SDValue> Ops;
Chris Lattner48884cd2007-08-25 00:47:38 +00004409 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode[0],
4410 Ops, DAG);
4411 if (Ops.empty()) {
Bill Wendling832171c2006-12-07 20:04:42 +00004412 cerr << "Invalid operand for inline asm constraint '"
Chris Lattner0c583402007-04-28 20:49:53 +00004413 << OpInfo.ConstraintCode << "'!\n";
Chris Lattner53069fb2006-10-31 19:41:18 +00004414 exit(1);
4415 }
Chris Lattner87bc3bd2006-02-24 01:11:24 +00004416
4417 // Add information to the INLINEASM node to know about this input.
Chris Lattner48884cd2007-08-25 00:47:38 +00004418 unsigned ResOpType = 3 /*IMM*/ | (Ops.size() << 3);
Chris Lattnerc90233b2007-05-15 01:33:58 +00004419 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
4420 TLI.getPointerTy()));
Chris Lattner48884cd2007-08-25 00:47:38 +00004421 AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end());
Chris Lattner87bc3bd2006-02-24 01:11:24 +00004422 break;
Chris Lattner2a600be2007-04-28 21:01:43 +00004423 } else if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
Chris Lattner09e4b7e2007-04-28 21:12:06 +00004424 assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
Chris Lattner44b2c502007-04-28 06:42:38 +00004425 assert(InOperandVal.getValueType() == TLI.getPointerTy() &&
4426 "Memory operands expect pointer values");
4427
Chris Lattner87bc3bd2006-02-24 01:11:24 +00004428 // Add information to the INLINEASM node to know about this input.
4429 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
Chris Lattnerc90233b2007-05-15 01:33:58 +00004430 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
4431 TLI.getPointerTy()));
Chris Lattner87bc3bd2006-02-24 01:11:24 +00004432 AsmNodeOperands.push_back(InOperandVal);
4433 break;
4434 }
4435
Chris Lattner2a600be2007-04-28 21:01:43 +00004436 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
4437 OpInfo.ConstraintType == TargetLowering::C_Register) &&
4438 "Unknown constraint type!");
Chris Lattner0c583402007-04-28 20:49:53 +00004439 assert(!OpInfo.isIndirect &&
Chris Lattner44b2c502007-04-28 06:42:38 +00004440 "Don't know how to handle indirect register inputs yet!");
Chris Lattner87bc3bd2006-02-24 01:11:24 +00004441
4442 // Copy the input into the appropriate registers.
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004443 assert(!OpInfo.AssignedRegs.Regs.empty() &&
4444 "Couldn't allocate input reg!");
Chris Lattner87bc3bd2006-02-24 01:11:24 +00004445
Dan Gohmanb6f5b002007-06-28 23:29:44 +00004446 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, Chain, &Flag);
Chris Lattner87bc3bd2006-02-24 01:11:24 +00004447
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004448 OpInfo.AssignedRegs.AddInlineAsmOperands(1/*REGUSE*/, DAG,
4449 AsmNodeOperands);
Chris Lattner6656dd12006-01-31 02:03:41 +00004450 break;
4451 }
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00004452 case InlineAsm::isClobber: {
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00004453 // Add the clobbered value to the operand list, so that the register
4454 // allocator is aware that the physreg got clobbered.
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004455 if (!OpInfo.AssignedRegs.Regs.empty())
4456 OpInfo.AssignedRegs.AddInlineAsmOperands(2/*REGDEF*/, DAG,
4457 AsmNodeOperands);
Chris Lattner6656dd12006-01-31 02:03:41 +00004458 break;
4459 }
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00004460 }
Chris Lattner6656dd12006-01-31 02:03:41 +00004461 }
Chris Lattnerce7518c2006-01-26 22:24:51 +00004462
4463 // Finish up input operands.
4464 AsmNodeOperands[0] = Chain;
4465 if (Flag.Val) AsmNodeOperands.push_back(Flag);
4466
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00004467 Chain = DAG.getNode(ISD::INLINEASM,
4468 DAG.getNodeValueTypes(MVT::Other, MVT::Flag), 2,
Chris Lattnerbd564bf2006-08-08 02:23:42 +00004469 &AsmNodeOperands[0], AsmNodeOperands.size());
Chris Lattnerce7518c2006-01-26 22:24:51 +00004470 Flag = Chain.getValue(1);
4471
Chris Lattner6656dd12006-01-31 02:03:41 +00004472 // If this asm returns a register value, copy the result from that register
4473 // and set it as the value of the call.
Chris Lattner3a508c92007-04-12 06:00:20 +00004474 if (!RetValRegs.Regs.empty()) {
Dan Gohman475871a2008-07-27 21:46:04 +00004475 SDValue Val = RetValRegs.getCopyFromRegs(DAG, Chain, &Flag);
Chris Lattner3fb29682008-04-29 04:48:56 +00004476
4477 // If any of the results of the inline asm is a vector, it may have the
4478 // wrong width/num elts. This can happen for register classes that can
4479 // contain multiple different value types. The preg or vreg allocated may
4480 // not have the same VT as was expected. Convert it to the right type with
Dan Gohman7f321562007-06-25 16:23:39 +00004481 // bit_convert.
Chris Lattner3fb29682008-04-29 04:48:56 +00004482 if (const StructType *ResSTy = dyn_cast<StructType>(CS.getType())) {
4483 for (unsigned i = 0, e = ResSTy->getNumElements(); i != e; ++i) {
Duncan Sands83ec4b62008-06-06 12:08:01 +00004484 if (Val.Val->getValueType(i).isVector())
Chris Lattner3fb29682008-04-29 04:48:56 +00004485 Val = DAG.getNode(ISD::BIT_CONVERT,
4486 TLI.getValueType(ResSTy->getElementType(i)), Val);
4487 }
4488 } else {
Duncan Sands83ec4b62008-06-06 12:08:01 +00004489 if (Val.getValueType().isVector())
Chris Lattner3fb29682008-04-29 04:48:56 +00004490 Val = DAG.getNode(ISD::BIT_CONVERT, TLI.getValueType(CS.getType()),
4491 Val);
Chris Lattner3a508c92007-04-12 06:00:20 +00004492 }
Chris Lattner3fb29682008-04-29 04:48:56 +00004493
Duncan Sandsfd7b3262007-12-17 18:08:19 +00004494 setValue(CS.getInstruction(), Val);
Chris Lattner3a508c92007-04-12 06:00:20 +00004495 }
Chris Lattnerce7518c2006-01-26 22:24:51 +00004496
Dan Gohman475871a2008-07-27 21:46:04 +00004497 std::vector<std::pair<SDValue, Value*> > StoresToEmit;
Chris Lattner6656dd12006-01-31 02:03:41 +00004498
4499 // Process indirect outputs, first output all of the flagged copies out of
4500 // physregs.
4501 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
Chris Lattner864635a2006-02-22 22:37:12 +00004502 RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
Chris Lattner6656dd12006-01-31 02:03:41 +00004503 Value *Ptr = IndirectStoresToEmit[i].second;
Dan Gohman475871a2008-07-27 21:46:04 +00004504 SDValue OutVal = OutRegs.getCopyFromRegs(DAG, Chain, &Flag);
Chris Lattner864635a2006-02-22 22:37:12 +00004505 StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
Chris Lattner6656dd12006-01-31 02:03:41 +00004506 }
4507
4508 // Emit the non-flagged stores from the physregs.
Dan Gohman475871a2008-07-27 21:46:04 +00004509 SmallVector<SDValue, 8> OutChains;
Chris Lattner6656dd12006-01-31 02:03:41 +00004510 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i)
Chris Lattner0c583402007-04-28 20:49:53 +00004511 OutChains.push_back(DAG.getStore(Chain, StoresToEmit[i].first,
Chris Lattner6656dd12006-01-31 02:03:41 +00004512 getValue(StoresToEmit[i].second),
Evan Cheng8b2794a2006-10-13 21:14:26 +00004513 StoresToEmit[i].second, 0));
Chris Lattner6656dd12006-01-31 02:03:41 +00004514 if (!OutChains.empty())
Chris Lattnerbd564bf2006-08-08 02:23:42 +00004515 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
4516 &OutChains[0], OutChains.size());
Chris Lattnerce7518c2006-01-26 22:24:51 +00004517 DAG.setRoot(Chain);
4518}
4519
4520
Chris Lattner1c08c712005-01-07 07:47:53 +00004521void SelectionDAGLowering::visitMalloc(MallocInst &I) {
Dan Gohman475871a2008-07-27 21:46:04 +00004522 SDValue Src = getValue(I.getOperand(0));
Chris Lattner1c08c712005-01-07 07:47:53 +00004523
Duncan Sands83ec4b62008-06-06 12:08:01 +00004524 MVT IntPtr = TLI.getPointerTy();
Chris Lattner68cd65e2005-01-22 23:04:37 +00004525
Duncan Sands8e4eb092008-06-08 20:54:56 +00004526 if (IntPtr.bitsLT(Src.getValueType()))
Chris Lattner68cd65e2005-01-22 23:04:37 +00004527 Src = DAG.getNode(ISD::TRUNCATE, IntPtr, Src);
Duncan Sands8e4eb092008-06-08 20:54:56 +00004528 else if (IntPtr.bitsGT(Src.getValueType()))
Chris Lattner68cd65e2005-01-22 23:04:37 +00004529 Src = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, Src);
Chris Lattner1c08c712005-01-07 07:47:53 +00004530
4531 // Scale the source by the type size.
Duncan Sands514ab342007-11-01 20:53:16 +00004532 uint64_t ElementSize = TD->getABITypeSize(I.getType()->getElementType());
Chris Lattner1c08c712005-01-07 07:47:53 +00004533 Src = DAG.getNode(ISD::MUL, Src.getValueType(),
Chris Lattner0bd48932008-01-17 07:00:52 +00004534 Src, DAG.getIntPtrConstant(ElementSize));
Chris Lattner1c08c712005-01-07 07:47:53 +00004535
Reid Spencer47857812006-12-31 05:55:36 +00004536 TargetLowering::ArgListTy Args;
4537 TargetLowering::ArgListEntry Entry;
4538 Entry.Node = Src;
4539 Entry.Ty = TLI.getTargetData()->getIntPtrType();
Reid Spencer47857812006-12-31 05:55:36 +00004540 Args.push_back(Entry);
Chris Lattnercf5734d2005-01-08 19:26:18 +00004541
Dan Gohman475871a2008-07-27 21:46:04 +00004542 std::pair<SDValue,SDValue> Result =
Duncan Sands00fee652008-02-14 17:28:50 +00004543 TLI.LowerCallTo(getRoot(), I.getType(), false, false, false, CallingConv::C,
4544 true, DAG.getExternalSymbol("malloc", IntPtr), Args, DAG);
Chris Lattnercf5734d2005-01-08 19:26:18 +00004545 setValue(&I, Result.first); // Pointers always fit in registers
4546 DAG.setRoot(Result.second);
Chris Lattner1c08c712005-01-07 07:47:53 +00004547}
4548
4549void SelectionDAGLowering::visitFree(FreeInst &I) {
Reid Spencer47857812006-12-31 05:55:36 +00004550 TargetLowering::ArgListTy Args;
4551 TargetLowering::ArgListEntry Entry;
4552 Entry.Node = getValue(I.getOperand(0));
4553 Entry.Ty = TLI.getTargetData()->getIntPtrType();
Reid Spencer47857812006-12-31 05:55:36 +00004554 Args.push_back(Entry);
Duncan Sands83ec4b62008-06-06 12:08:01 +00004555 MVT IntPtr = TLI.getPointerTy();
Dan Gohman475871a2008-07-27 21:46:04 +00004556 std::pair<SDValue,SDValue> Result =
Duncan Sands00fee652008-02-14 17:28:50 +00004557 TLI.LowerCallTo(getRoot(), Type::VoidTy, false, false, false,
4558 CallingConv::C, true,
Chris Lattnercf5734d2005-01-08 19:26:18 +00004559 DAG.getExternalSymbol("free", IntPtr), Args, DAG);
4560 DAG.setRoot(Result.second);
Chris Lattner1c08c712005-01-07 07:47:53 +00004561}
4562
Evan Chengff9b3732008-01-30 18:18:23 +00004563// EmitInstrWithCustomInserter - This method should be implemented by targets
4564// that mark instructions with the 'usesCustomDAGSchedInserter' flag. These
Chris Lattner025c39b2005-08-26 20:54:47 +00004565// instructions are special in various ways, which require special support to
4566// insert. The specified MachineInstr is created but not inserted into any
4567// basic blocks, and the scheduler passes ownership of it to this method.
Evan Chengff9b3732008-01-30 18:18:23 +00004568MachineBasicBlock *TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
Chris Lattner025c39b2005-08-26 20:54:47 +00004569 MachineBasicBlock *MBB) {
Bill Wendling832171c2006-12-07 20:04:42 +00004570 cerr << "If a target marks an instruction with "
4571 << "'usesCustomDAGSchedInserter', it must implement "
Evan Chengff9b3732008-01-30 18:18:23 +00004572 << "TargetLowering::EmitInstrWithCustomInserter!\n";
Chris Lattner025c39b2005-08-26 20:54:47 +00004573 abort();
4574 return 0;
4575}
4576
Chris Lattner39ae3622005-01-09 00:00:49 +00004577void SelectionDAGLowering::visitVAStart(CallInst &I) {
Nate Begemanacc398c2006-01-25 18:21:52 +00004578 DAG.setRoot(DAG.getNode(ISD::VASTART, MVT::Other, getRoot(),
4579 getValue(I.getOperand(1)),
4580 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner39ae3622005-01-09 00:00:49 +00004581}
4582
4583void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
Dan Gohman475871a2008-07-27 21:46:04 +00004584 SDValue V = DAG.getVAArg(TLI.getValueType(I.getType()), getRoot(),
Nate Begemanacc398c2006-01-25 18:21:52 +00004585 getValue(I.getOperand(0)),
4586 DAG.getSrcValue(I.getOperand(0)));
4587 setValue(&I, V);
4588 DAG.setRoot(V.getValue(1));
Chris Lattner1c08c712005-01-07 07:47:53 +00004589}
4590
4591void SelectionDAGLowering::visitVAEnd(CallInst &I) {
Nate Begemanacc398c2006-01-25 18:21:52 +00004592 DAG.setRoot(DAG.getNode(ISD::VAEND, MVT::Other, getRoot(),
4593 getValue(I.getOperand(1)),
4594 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner1c08c712005-01-07 07:47:53 +00004595}
4596
4597void SelectionDAGLowering::visitVACopy(CallInst &I) {
Nate Begemanacc398c2006-01-25 18:21:52 +00004598 DAG.setRoot(DAG.getNode(ISD::VACOPY, MVT::Other, getRoot(),
4599 getValue(I.getOperand(1)),
4600 getValue(I.getOperand(2)),
4601 DAG.getSrcValue(I.getOperand(1)),
4602 DAG.getSrcValue(I.getOperand(2))));
Chris Lattner1c08c712005-01-07 07:47:53 +00004603}
4604
Chris Lattnerfdfded52006-04-12 16:20:43 +00004605/// TargetLowering::LowerArguments - This is the default LowerArguments
4606/// implementation, which just inserts a FORMAL_ARGUMENTS node. FIXME: When all
Chris Lattnerf4ec8172006-05-16 22:53:20 +00004607/// targets are migrated to using FORMAL_ARGUMENTS, this hook should be
4608/// integrated into SDISel.
Dan Gohmana44b6742008-06-30 20:31:15 +00004609void TargetLowering::LowerArguments(Function &F, SelectionDAG &DAG,
Dan Gohman475871a2008-07-27 21:46:04 +00004610 SmallVectorImpl<SDValue> &ArgValues) {
Chris Lattnerfdfded52006-04-12 16:20:43 +00004611 // Add CC# and isVararg as operands to the FORMAL_ARGUMENTS node.
Dan Gohman475871a2008-07-27 21:46:04 +00004612 SmallVector<SDValue, 3+16> Ops;
Chris Lattner8c0c10c2006-05-16 06:45:34 +00004613 Ops.push_back(DAG.getRoot());
Chris Lattnerfdfded52006-04-12 16:20:43 +00004614 Ops.push_back(DAG.getConstant(F.getCallingConv(), getPointerTy()));
4615 Ops.push_back(DAG.getConstant(F.isVarArg(), getPointerTy()));
4616
4617 // Add one result value for each formal argument.
Dan Gohmana44b6742008-06-30 20:31:15 +00004618 SmallVector<MVT, 16> RetVals;
Anton Korobeynikov6aa279d2007-01-28 18:01:49 +00004619 unsigned j = 1;
Anton Korobeynikovac2b2cf2007-01-28 16:04:40 +00004620 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end();
4621 I != E; ++I, ++j) {
Dan Gohmanf5025cf2008-06-09 21:19:23 +00004622 SmallVector<MVT, 4> ValueVTs;
4623 ComputeValueVTs(*this, I->getType(), ValueVTs);
4624 for (unsigned Value = 0, NumValues = ValueVTs.size();
4625 Value != NumValues; ++Value) {
4626 MVT VT = ValueVTs[Value];
4627 const Type *ArgTy = VT.getTypeForMVT();
4628 ISD::ArgFlagsTy Flags;
4629 unsigned OriginalAlignment =
4630 getTargetData()->getABITypeAlignment(ArgTy);
Lauro Ramos Venancio7aa47b62007-02-13 13:50:08 +00004631
Dan Gohmanf5025cf2008-06-09 21:19:23 +00004632 if (F.paramHasAttr(j, ParamAttr::ZExt))
4633 Flags.setZExt();
4634 if (F.paramHasAttr(j, ParamAttr::SExt))
4635 Flags.setSExt();
4636 if (F.paramHasAttr(j, ParamAttr::InReg))
4637 Flags.setInReg();
4638 if (F.paramHasAttr(j, ParamAttr::StructRet))
4639 Flags.setSRet();
4640 if (F.paramHasAttr(j, ParamAttr::ByVal)) {
4641 Flags.setByVal();
4642 const PointerType *Ty = cast<PointerType>(I->getType());
4643 const Type *ElementTy = Ty->getElementType();
4644 unsigned FrameAlign = getByValTypeAlignment(ElementTy);
4645 unsigned FrameSize = getTargetData()->getABITypeSize(ElementTy);
4646 // For ByVal, alignment should be passed from FE. BE will guess if
4647 // this info is not there but there are cases it cannot get right.
4648 if (F.getParamAlignment(j))
4649 FrameAlign = F.getParamAlignment(j);
4650 Flags.setByValAlign(FrameAlign);
4651 Flags.setByValSize(FrameSize);
4652 }
4653 if (F.paramHasAttr(j, ParamAttr::Nest))
4654 Flags.setNest();
4655 Flags.setOrigAlign(OriginalAlignment);
Duncan Sandsb988bac2008-02-11 20:58:28 +00004656
Dan Gohmanf5025cf2008-06-09 21:19:23 +00004657 MVT RegisterVT = getRegisterType(VT);
4658 unsigned NumRegs = getNumRegisters(VT);
4659 for (unsigned i = 0; i != NumRegs; ++i) {
4660 RetVals.push_back(RegisterVT);
4661 ISD::ArgFlagsTy MyFlags = Flags;
4662 if (NumRegs > 1 && i == 0)
4663 MyFlags.setSplit();
4664 // if it isn't first piece, alignment must be 1
4665 else if (i > 0)
4666 MyFlags.setOrigAlign(1);
4667 Ops.push_back(DAG.getArgFlags(MyFlags));
4668 }
Dan Gohmanb6f5b002007-06-28 23:29:44 +00004669 }
Chris Lattnerfdfded52006-04-12 16:20:43 +00004670 }
Evan Cheng3b0d2862006-04-25 23:03:35 +00004671
Chris Lattner8c0c10c2006-05-16 06:45:34 +00004672 RetVals.push_back(MVT::Other);
Chris Lattnerfdfded52006-04-12 16:20:43 +00004673
4674 // Create the node.
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00004675 SDNode *Result = DAG.getNode(ISD::FORMAL_ARGUMENTS,
Chris Lattner86ca3ca2008-02-13 07:39:09 +00004676 DAG.getVTList(&RetVals[0], RetVals.size()),
Chris Lattnerbd564bf2006-08-08 02:23:42 +00004677 &Ops[0], Ops.size()).Val;
Chris Lattner86ca3ca2008-02-13 07:39:09 +00004678
4679 // Prelower FORMAL_ARGUMENTS. This isn't required for functionality, but
4680 // allows exposing the loads that may be part of the argument access to the
4681 // first DAGCombiner pass.
Dan Gohman475871a2008-07-27 21:46:04 +00004682 SDValue TmpRes = LowerOperation(SDValue(Result, 0), DAG);
Chris Lattner86ca3ca2008-02-13 07:39:09 +00004683
4684 // The number of results should match up, except that the lowered one may have
4685 // an extra flag result.
4686 assert((Result->getNumValues() == TmpRes.Val->getNumValues() ||
4687 (Result->getNumValues()+1 == TmpRes.Val->getNumValues() &&
4688 TmpRes.getValue(Result->getNumValues()).getValueType() == MVT::Flag))
4689 && "Lowering produced unexpected number of results!");
Dan Gohman2dbc1672008-07-21 21:04:07 +00004690
4691 // The FORMAL_ARGUMENTS node itself is likely no longer needed.
4692 if (Result != TmpRes.Val && Result->use_empty()) {
4693 HandleSDNode Dummy(DAG.getRoot());
4694 DAG.RemoveDeadNode(Result);
4695 }
4696
Chris Lattner86ca3ca2008-02-13 07:39:09 +00004697 Result = TmpRes.Val;
4698
Dan Gohman27a70be2007-07-02 16:18:06 +00004699 unsigned NumArgRegs = Result->getNumValues() - 1;
Dan Gohman475871a2008-07-27 21:46:04 +00004700 DAG.setRoot(SDValue(Result, NumArgRegs));
Chris Lattnerfdfded52006-04-12 16:20:43 +00004701
4702 // Set up the return result vector.
Chris Lattnerfdfded52006-04-12 16:20:43 +00004703 unsigned i = 0;
Reid Spencer47857812006-12-31 05:55:36 +00004704 unsigned Idx = 1;
4705 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E;
4706 ++I, ++Idx) {
Dan Gohmanf5025cf2008-06-09 21:19:23 +00004707 SmallVector<MVT, 4> ValueVTs;
4708 ComputeValueVTs(*this, I->getType(), ValueVTs);
4709 for (unsigned Value = 0, NumValues = ValueVTs.size();
4710 Value != NumValues; ++Value) {
4711 MVT VT = ValueVTs[Value];
4712 MVT PartVT = getRegisterType(VT);
Duncan Sandsb988bac2008-02-11 20:58:28 +00004713
Dan Gohmanf5025cf2008-06-09 21:19:23 +00004714 unsigned NumParts = getNumRegisters(VT);
Dan Gohman475871a2008-07-27 21:46:04 +00004715 SmallVector<SDValue, 4> Parts(NumParts);
Dan Gohmanf5025cf2008-06-09 21:19:23 +00004716 for (unsigned j = 0; j != NumParts; ++j)
Dan Gohman475871a2008-07-27 21:46:04 +00004717 Parts[j] = SDValue(Result, i++);
Duncan Sandsb988bac2008-02-11 20:58:28 +00004718
Dan Gohmanf5025cf2008-06-09 21:19:23 +00004719 ISD::NodeType AssertOp = ISD::DELETED_NODE;
4720 if (F.paramHasAttr(Idx, ParamAttr::SExt))
4721 AssertOp = ISD::AssertSext;
4722 else if (F.paramHasAttr(Idx, ParamAttr::ZExt))
4723 AssertOp = ISD::AssertZext;
Duncan Sandsb988bac2008-02-11 20:58:28 +00004724
Dan Gohmana44b6742008-06-30 20:31:15 +00004725 ArgValues.push_back(getCopyFromParts(DAG, &Parts[0], NumParts, PartVT, VT,
4726 AssertOp));
Dan Gohmanf5025cf2008-06-09 21:19:23 +00004727 }
Chris Lattnerfdfded52006-04-12 16:20:43 +00004728 }
Dan Gohman27a70be2007-07-02 16:18:06 +00004729 assert(i == NumArgRegs && "Argument register count mismatch!");
Chris Lattnerfdfded52006-04-12 16:20:43 +00004730}
4731
Chris Lattnerf4ec8172006-05-16 22:53:20 +00004732
4733/// TargetLowering::LowerCallTo - This is the default LowerCallTo
4734/// implementation, which just inserts an ISD::CALL node, which is later custom
4735/// lowered by the target to something concrete. FIXME: When all targets are
4736/// migrated to using ISD::CALL, this hook should be integrated into SDISel.
Dan Gohman475871a2008-07-27 21:46:04 +00004737std::pair<SDValue, SDValue>
4738TargetLowering::LowerCallTo(SDValue Chain, const Type *RetTy,
Duncan Sands00fee652008-02-14 17:28:50 +00004739 bool RetSExt, bool RetZExt, bool isVarArg,
4740 unsigned CallingConv, bool isTailCall,
Dan Gohman475871a2008-07-27 21:46:04 +00004741 SDValue Callee,
Chris Lattnerf4ec8172006-05-16 22:53:20 +00004742 ArgListTy &Args, SelectionDAG &DAG) {
Dan Gohman475871a2008-07-27 21:46:04 +00004743 SmallVector<SDValue, 32> Ops;
Chris Lattnerf4ec8172006-05-16 22:53:20 +00004744 Ops.push_back(Chain); // Op#0 - Chain
4745 Ops.push_back(DAG.getConstant(CallingConv, getPointerTy())); // Op#1 - CC
4746 Ops.push_back(DAG.getConstant(isVarArg, getPointerTy())); // Op#2 - VarArg
4747 Ops.push_back(DAG.getConstant(isTailCall, getPointerTy())); // Op#3 - Tail
4748 Ops.push_back(Callee);
4749
4750 // Handle all of the outgoing arguments.
4751 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
Dan Gohmanf5025cf2008-06-09 21:19:23 +00004752 SmallVector<MVT, 4> ValueVTs;
4753 ComputeValueVTs(*this, Args[i].Ty, ValueVTs);
4754 for (unsigned Value = 0, NumValues = ValueVTs.size();
4755 Value != NumValues; ++Value) {
4756 MVT VT = ValueVTs[Value];
4757 const Type *ArgTy = VT.getTypeForMVT();
Dan Gohman475871a2008-07-27 21:46:04 +00004758 SDValue Op = SDValue(Args[i].Node.Val, Args[i].Node.ResNo + Value);
Dan Gohmanf5025cf2008-06-09 21:19:23 +00004759 ISD::ArgFlagsTy Flags;
4760 unsigned OriginalAlignment =
4761 getTargetData()->getABITypeAlignment(ArgTy);
Duncan Sands276dcbd2008-03-21 09:14:45 +00004762
Dan Gohmanf5025cf2008-06-09 21:19:23 +00004763 if (Args[i].isZExt)
4764 Flags.setZExt();
4765 if (Args[i].isSExt)
4766 Flags.setSExt();
4767 if (Args[i].isInReg)
4768 Flags.setInReg();
4769 if (Args[i].isSRet)
4770 Flags.setSRet();
4771 if (Args[i].isByVal) {
4772 Flags.setByVal();
4773 const PointerType *Ty = cast<PointerType>(Args[i].Ty);
4774 const Type *ElementTy = Ty->getElementType();
4775 unsigned FrameAlign = getByValTypeAlignment(ElementTy);
4776 unsigned FrameSize = getTargetData()->getABITypeSize(ElementTy);
4777 // For ByVal, alignment should come from FE. BE will guess if this
4778 // info is not there but there are cases it cannot get right.
4779 if (Args[i].Alignment)
4780 FrameAlign = Args[i].Alignment;
4781 Flags.setByValAlign(FrameAlign);
4782 Flags.setByValSize(FrameSize);
4783 }
4784 if (Args[i].isNest)
4785 Flags.setNest();
4786 Flags.setOrigAlign(OriginalAlignment);
Dan Gohman27a70be2007-07-02 16:18:06 +00004787
Dan Gohmanf5025cf2008-06-09 21:19:23 +00004788 MVT PartVT = getRegisterType(VT);
4789 unsigned NumParts = getNumRegisters(VT);
Dan Gohman475871a2008-07-27 21:46:04 +00004790 SmallVector<SDValue, 4> Parts(NumParts);
Dan Gohmanf5025cf2008-06-09 21:19:23 +00004791 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
Duncan Sandsb988bac2008-02-11 20:58:28 +00004792
Dan Gohmanf5025cf2008-06-09 21:19:23 +00004793 if (Args[i].isSExt)
4794 ExtendKind = ISD::SIGN_EXTEND;
4795 else if (Args[i].isZExt)
4796 ExtendKind = ISD::ZERO_EXTEND;
Duncan Sandsb988bac2008-02-11 20:58:28 +00004797
Dan Gohmanf5025cf2008-06-09 21:19:23 +00004798 getCopyToParts(DAG, Op, &Parts[0], NumParts, PartVT, ExtendKind);
Duncan Sandsb988bac2008-02-11 20:58:28 +00004799
Dan Gohmanf5025cf2008-06-09 21:19:23 +00004800 for (unsigned i = 0; i != NumParts; ++i) {
4801 // if it isn't first piece, alignment must be 1
4802 ISD::ArgFlagsTy MyFlags = Flags;
4803 if (NumParts > 1 && i == 0)
4804 MyFlags.setSplit();
4805 else if (i != 0)
4806 MyFlags.setOrigAlign(1);
Duncan Sandsb988bac2008-02-11 20:58:28 +00004807
Dan Gohmanf5025cf2008-06-09 21:19:23 +00004808 Ops.push_back(Parts[i]);
4809 Ops.push_back(DAG.getArgFlags(MyFlags));
4810 }
Dan Gohman27a70be2007-07-02 16:18:06 +00004811 }
Chris Lattnerf4ec8172006-05-16 22:53:20 +00004812 }
4813
Dan Gohmanef5d1942008-03-11 21:11:25 +00004814 // Figure out the result value types. We start by making a list of
Dan Gohman23ce5022008-04-25 18:27:55 +00004815 // the potentially illegal return value types.
Duncan Sands83ec4b62008-06-06 12:08:01 +00004816 SmallVector<MVT, 4> LoweredRetTys;
4817 SmallVector<MVT, 4> RetTys;
Dan Gohman23ce5022008-04-25 18:27:55 +00004818 ComputeValueVTs(*this, RetTy, RetTys);
Dan Gohmanef5d1942008-03-11 21:11:25 +00004819
Dan Gohman23ce5022008-04-25 18:27:55 +00004820 // Then we translate that to a list of legal types.
4821 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
Duncan Sands83ec4b62008-06-06 12:08:01 +00004822 MVT VT = RetTys[I];
4823 MVT RegisterVT = getRegisterType(VT);
Dan Gohmanef5d1942008-03-11 21:11:25 +00004824 unsigned NumRegs = getNumRegisters(VT);
4825 for (unsigned i = 0; i != NumRegs; ++i)
4826 LoweredRetTys.push_back(RegisterVT);
4827 }
Chris Lattnerf4ec8172006-05-16 22:53:20 +00004828
Dan Gohmanef5d1942008-03-11 21:11:25 +00004829 LoweredRetTys.push_back(MVT::Other); // Always has a chain.
Chris Lattnerf4ec8172006-05-16 22:53:20 +00004830
Dan Gohmanb6f5b002007-06-28 23:29:44 +00004831 // Create the CALL node.
Dan Gohman475871a2008-07-27 21:46:04 +00004832 SDValue Res = DAG.getNode(ISD::CALL,
Dan Gohmanef5d1942008-03-11 21:11:25 +00004833 DAG.getVTList(&LoweredRetTys[0],
4834 LoweredRetTys.size()),
Chris Lattnerbe384162006-08-16 22:57:46 +00004835 &Ops[0], Ops.size());
Dan Gohmanef5d1942008-03-11 21:11:25 +00004836 Chain = Res.getValue(LoweredRetTys.size() - 1);
Dan Gohmanb6f5b002007-06-28 23:29:44 +00004837
4838 // Gather up the call result into a single value.
4839 if (RetTy != Type::VoidTy) {
Duncan Sands00fee652008-02-14 17:28:50 +00004840 ISD::NodeType AssertOp = ISD::DELETED_NODE;
4841
4842 if (RetSExt)
4843 AssertOp = ISD::AssertSext;
4844 else if (RetZExt)
Dan Gohmanb6f5b002007-06-28 23:29:44 +00004845 AssertOp = ISD::AssertZext;
Duncan Sands00fee652008-02-14 17:28:50 +00004846
Dan Gohman475871a2008-07-27 21:46:04 +00004847 SmallVector<SDValue, 4> ReturnValues;
Dan Gohmanef5d1942008-03-11 21:11:25 +00004848 unsigned RegNo = 0;
Dan Gohman23ce5022008-04-25 18:27:55 +00004849 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
Duncan Sands83ec4b62008-06-06 12:08:01 +00004850 MVT VT = RetTys[I];
4851 MVT RegisterVT = getRegisterType(VT);
Dan Gohmanef5d1942008-03-11 21:11:25 +00004852 unsigned NumRegs = getNumRegisters(VT);
4853 unsigned RegNoEnd = NumRegs + RegNo;
Dan Gohman475871a2008-07-27 21:46:04 +00004854 SmallVector<SDValue, 4> Results;
Dan Gohmanef5d1942008-03-11 21:11:25 +00004855 for (; RegNo != RegNoEnd; ++RegNo)
4856 Results.push_back(Res.getValue(RegNo));
Dan Gohman475871a2008-07-27 21:46:04 +00004857 SDValue ReturnValue =
Dan Gohmanef5d1942008-03-11 21:11:25 +00004858 getCopyFromParts(DAG, &Results[0], NumRegs, RegisterVT, VT,
4859 AssertOp);
4860 ReturnValues.push_back(ReturnValue);
4861 }
Duncan Sandsf9516202008-06-30 10:19:09 +00004862 Res = DAG.getMergeValues(DAG.getVTList(&RetTys[0], RetTys.size()),
4863 &ReturnValues[0], ReturnValues.size());
Chris Lattnerf4ec8172006-05-16 22:53:20 +00004864 }
Dan Gohmanb6f5b002007-06-28 23:29:44 +00004865
4866 return std::make_pair(Res, Chain);
Chris Lattnerf4ec8172006-05-16 22:53:20 +00004867}
4868
Dan Gohman475871a2008-07-27 21:46:04 +00004869SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) {
Chris Lattner171453a2005-01-16 07:28:41 +00004870 assert(0 && "LowerOperation not implemented for this target!");
4871 abort();
Dan Gohman475871a2008-07-27 21:46:04 +00004872 return SDValue();
Chris Lattner171453a2005-01-16 07:28:41 +00004873}
4874
Nate Begeman0aed7842006-01-28 03:14:31 +00004875
Chris Lattner7041ee32005-01-11 05:56:49 +00004876//===----------------------------------------------------------------------===//
4877// SelectionDAGISel code
4878//===----------------------------------------------------------------------===//
Chris Lattner1c08c712005-01-07 07:47:53 +00004879
Duncan Sands83ec4b62008-06-06 12:08:01 +00004880unsigned SelectionDAGISel::MakeReg(MVT VT) {
Chris Lattner84bc5422007-12-31 04:13:23 +00004881 return RegInfo->createVirtualRegister(TLI.getRegClassFor(VT));
Chris Lattner1c08c712005-01-07 07:47:53 +00004882}
4883
Chris Lattner495a0b52005-08-17 06:37:43 +00004884void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const {
Jim Laskeyc7c3f112006-10-16 20:52:31 +00004885 AU.addRequired<AliasAnalysis>();
Gordon Henriksen5eca0752008-08-17 18:44:35 +00004886 AU.addRequired<GCModuleInfo>();
Chris Lattnerc8d288f2007-03-31 04:18:03 +00004887 AU.setPreservesAll();
Chris Lattner495a0b52005-08-17 06:37:43 +00004888}
Chris Lattner1c08c712005-01-07 07:47:53 +00004889
Chris Lattner1c08c712005-01-07 07:47:53 +00004890bool SelectionDAGISel::runOnFunction(Function &Fn) {
Dan Gohman5f43f922007-08-27 16:26:13 +00004891 // Get alias analysis for load/store combining.
4892 AA = &getAnalysis<AliasAnalysis>();
4893
Chris Lattner1c08c712005-01-07 07:47:53 +00004894 MachineFunction &MF = MachineFunction::construct(&Fn, TLI.getTargetMachine());
Gordon Henriksen5eca0752008-08-17 18:44:35 +00004895 if (MF.getFunction()->hasGC())
4896 GFI = &getAnalysis<GCModuleInfo>().getFunctionInfo(*MF.getFunction());
Gordon Henriksence224772008-01-07 01:30:38 +00004897 else
Gordon Henriksen5eca0752008-08-17 18:44:35 +00004898 GFI = 0;
Chris Lattner84bc5422007-12-31 04:13:23 +00004899 RegInfo = &MF.getRegInfo();
Bill Wendling832171c2006-12-07 20:04:42 +00004900 DOUT << "\n\n\n=== " << Fn.getName() << "\n";
Chris Lattner1c08c712005-01-07 07:47:53 +00004901
4902 FunctionLoweringInfo FuncInfo(TLI, Fn, MF);
4903
Dale Johannesen1532f3d2008-04-02 00:25:04 +00004904 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
4905 if (InvokeInst *Invoke = dyn_cast<InvokeInst>(I->getTerminator()))
4906 // Mark landing pad.
4907 FuncInfo.MBBMap[Invoke->getSuccessor(1)]->setIsLandingPad();
Duncan Sands9fac0b52007-06-06 10:05:18 +00004908
Dan Gohman0e5f1302008-07-07 23:02:41 +00004909 SelectAllBasicBlocks(Fn, MF, FuncInfo);
Misha Brukmanedf128a2005-04-21 22:36:52 +00004910
Evan Chengad2070c2007-02-10 02:43:39 +00004911 // Add function live-ins to entry block live-in set.
4912 BasicBlock *EntryBB = &Fn.getEntryBlock();
4913 BB = FuncInfo.MBBMap[EntryBB];
Chris Lattner84bc5422007-12-31 04:13:23 +00004914 if (!RegInfo->livein_empty())
4915 for (MachineRegisterInfo::livein_iterator I = RegInfo->livein_begin(),
4916 E = RegInfo->livein_end(); I != E; ++I)
Evan Chengad2070c2007-02-10 02:43:39 +00004917 BB->addLiveIn(I->first);
4918
Duncan Sandsf4070822007-06-15 19:04:19 +00004919#ifndef NDEBUG
4920 assert(FuncInfo.CatchInfoFound.size() == FuncInfo.CatchInfoLost.size() &&
4921 "Not all catch info was assigned to a landing pad!");
4922#endif
4923
Chris Lattner1c08c712005-01-07 07:47:53 +00004924 return true;
4925}
4926
Chris Lattner6833b062008-04-28 07:16:35 +00004927void SelectionDAGLowering::CopyValueToVirtualRegister(Value *V, unsigned Reg) {
Dan Gohman475871a2008-07-27 21:46:04 +00004928 SDValue Op = getValue(V);
Chris Lattner18c2f132005-01-13 20:50:02 +00004929 assert((Op.getOpcode() != ISD::CopyFromReg ||
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00004930 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
Chris Lattner18c2f132005-01-13 20:50:02 +00004931 "Copy from a reg to the same reg!");
Dan Gohman86e1ebf2008-03-27 19:56:19 +00004932 assert(!TargetRegisterInfo::isPhysicalRegister(Reg) && "Is a physreg");
Dan Gohmanb6f5b002007-06-28 23:29:44 +00004933
Dan Gohman23ce5022008-04-25 18:27:55 +00004934 RegsForValue RFV(TLI, Reg, V->getType());
Dan Gohman475871a2008-07-27 21:46:04 +00004935 SDValue Chain = DAG.getEntryNode();
Dan Gohman23ce5022008-04-25 18:27:55 +00004936 RFV.getCopyToRegs(Op, DAG, Chain, 0);
4937 PendingExports.push_back(Chain);
Chris Lattner1c08c712005-01-07 07:47:53 +00004938}
4939
Chris Lattner068a81e2005-01-17 17:15:02 +00004940void SelectionDAGISel::
Dan Gohman86e1ebf2008-03-27 19:56:19 +00004941LowerArguments(BasicBlock *LLVMBB, SelectionDAGLowering &SDL) {
Chris Lattner068a81e2005-01-17 17:15:02 +00004942 // If this is the entry block, emit arguments.
Evan Cheng15699fc2007-02-10 01:08:18 +00004943 Function &F = *LLVMBB->getParent();
Chris Lattner0afa8e32005-01-17 17:55:19 +00004944 FunctionLoweringInfo &FuncInfo = SDL.FuncInfo;
Dan Gohman475871a2008-07-27 21:46:04 +00004945 SDValue OldRoot = SDL.DAG.getRoot();
4946 SmallVector<SDValue, 16> Args;
Dan Gohmana44b6742008-06-30 20:31:15 +00004947 TLI.LowerArguments(F, SDL.DAG, Args);
Chris Lattner068a81e2005-01-17 17:15:02 +00004948
Chris Lattnerbf209482005-10-30 19:42:35 +00004949 unsigned a = 0;
4950 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
Dan Gohmanf5025cf2008-06-09 21:19:23 +00004951 AI != E; ++AI) {
4952 SmallVector<MVT, 4> ValueVTs;
4953 ComputeValueVTs(TLI, AI->getType(), ValueVTs);
4954 unsigned NumValues = ValueVTs.size();
Chris Lattnerbf209482005-10-30 19:42:35 +00004955 if (!AI->use_empty()) {
Duncan Sands4bdcb612008-07-02 17:40:58 +00004956 SDL.setValue(AI, SDL.DAG.getMergeValues(&Args[a], NumValues));
Chris Lattnerbf209482005-10-30 19:42:35 +00004957 // If this argument is live outside of the entry block, insert a copy from
4958 // whereever we got it to the vreg that other BB's will reference it as.
Chris Lattner251db182007-02-25 18:40:32 +00004959 DenseMap<const Value*, unsigned>::iterator VMI=FuncInfo.ValueMap.find(AI);
4960 if (VMI != FuncInfo.ValueMap.end()) {
Dan Gohman86e1ebf2008-03-27 19:56:19 +00004961 SDL.CopyValueToVirtualRegister(AI, VMI->second);
Chris Lattnerbf209482005-10-30 19:42:35 +00004962 }
Chris Lattner0afa8e32005-01-17 17:55:19 +00004963 }
Dan Gohmanf5025cf2008-06-09 21:19:23 +00004964 a += NumValues;
4965 }
Chris Lattnerbf209482005-10-30 19:42:35 +00004966
Chris Lattnerbf209482005-10-30 19:42:35 +00004967 // Finally, if the target has anything special to do, allow it to do so.
Chris Lattner96645412006-05-16 06:10:58 +00004968 // FIXME: this should insert code into the DAG!
Chris Lattnerbf209482005-10-30 19:42:35 +00004969 EmitFunctionEntryCode(F, SDL.DAG.getMachineFunction());
Chris Lattner068a81e2005-01-17 17:15:02 +00004970}
4971
Duncan Sandsf4070822007-06-15 19:04:19 +00004972static void copyCatchInfo(BasicBlock *SrcBB, BasicBlock *DestBB,
4973 MachineModuleInfo *MMI, FunctionLoweringInfo &FLI) {
Duncan Sandsf4070822007-06-15 19:04:19 +00004974 for (BasicBlock::iterator I = SrcBB->begin(), E = --SrcBB->end(); I != E; ++I)
Duncan Sandscf26d7c2007-07-04 20:52:51 +00004975 if (isSelector(I)) {
Duncan Sandsf4070822007-06-15 19:04:19 +00004976 // Apply the catch info to DestBB.
4977 addCatchInfo(cast<CallInst>(*I), MMI, FLI.MBBMap[DestBB]);
4978#ifndef NDEBUG
Duncan Sands560a7372007-11-15 09:54:37 +00004979 if (!FLI.MBBMap[SrcBB]->isLandingPad())
4980 FLI.CatchInfoFound.insert(I);
Duncan Sandsf4070822007-06-15 19:04:19 +00004981#endif
4982 }
4983}
4984
Arnold Schwaighofer30e62c02008-04-30 09:16:33 +00004985/// IsFixedFrameObjectWithPosOffset - Check if object is a fixed frame object and
4986/// whether object offset >= 0.
4987static bool
Dan Gohman475871a2008-07-27 21:46:04 +00004988IsFixedFrameObjectWithPosOffset(MachineFrameInfo * MFI, SDValue Op) {
Arnold Schwaighofer30e62c02008-04-30 09:16:33 +00004989 if (!isa<FrameIndexSDNode>(Op)) return false;
4990
4991 FrameIndexSDNode * FrameIdxNode = dyn_cast<FrameIndexSDNode>(Op);
4992 int FrameIdx = FrameIdxNode->getIndex();
4993 return MFI->isFixedObjectIndex(FrameIdx) &&
4994 MFI->getObjectOffset(FrameIdx) >= 0;
4995}
4996
4997/// IsPossiblyOverwrittenArgumentOfTailCall - Check if the operand could
4998/// possibly be overwritten when lowering the outgoing arguments in a tail
4999/// call. Currently the implementation of this call is very conservative and
5000/// assumes all arguments sourcing from FORMAL_ARGUMENTS or a CopyFromReg with
5001/// virtual registers would be overwritten by direct lowering.
Dan Gohman475871a2008-07-27 21:46:04 +00005002static bool IsPossiblyOverwrittenArgumentOfTailCall(SDValue Op,
Arnold Schwaighofer30e62c02008-04-30 09:16:33 +00005003 MachineFrameInfo * MFI) {
5004 RegisterSDNode * OpReg = NULL;
5005 if (Op.getOpcode() == ISD::FORMAL_ARGUMENTS ||
5006 (Op.getOpcode()== ISD::CopyFromReg &&
5007 (OpReg = dyn_cast<RegisterSDNode>(Op.getOperand(1))) &&
5008 (OpReg->getReg() >= TargetRegisterInfo::FirstVirtualRegister)) ||
5009 (Op.getOpcode() == ISD::LOAD &&
5010 IsFixedFrameObjectWithPosOffset(MFI, Op.getOperand(1))) ||
5011 (Op.getOpcode() == ISD::MERGE_VALUES &&
5012 Op.getOperand(Op.ResNo).getOpcode() == ISD::LOAD &&
5013 IsFixedFrameObjectWithPosOffset(MFI, Op.getOperand(Op.ResNo).
5014 getOperand(1))))
5015 return true;
5016 return false;
5017}
5018
Arnold Schwaighoferc85e1712007-10-11 19:40:01 +00005019/// CheckDAGForTailCallsAndFixThem - This Function looks for CALL nodes in the
Arnold Schwaighofer48abc5c2007-10-12 21:30:57 +00005020/// DAG and fixes their tailcall attribute operand.
Arnold Schwaighoferc85e1712007-10-11 19:40:01 +00005021static void CheckDAGForTailCallsAndFixThem(SelectionDAG &DAG,
5022 TargetLowering& TLI) {
5023 SDNode * Ret = NULL;
Dan Gohman475871a2008-07-27 21:46:04 +00005024 SDValue Terminator = DAG.getRoot();
Arnold Schwaighoferc85e1712007-10-11 19:40:01 +00005025
5026 // Find RET node.
5027 if (Terminator.getOpcode() == ISD::RET) {
5028 Ret = Terminator.Val;
5029 }
5030
5031 // Fix tail call attribute of CALL nodes.
5032 for (SelectionDAG::allnodes_iterator BE = DAG.allnodes_begin(),
Dan Gohman0e5f1302008-07-07 23:02:41 +00005033 BI = DAG.allnodes_end(); BI != BE; ) {
5034 --BI;
Arnold Schwaighoferc85e1712007-10-11 19:40:01 +00005035 if (BI->getOpcode() == ISD::CALL) {
Dan Gohman475871a2008-07-27 21:46:04 +00005036 SDValue OpRet(Ret, 0);
5037 SDValue OpCall(BI, 0);
Arnold Schwaighoferc85e1712007-10-11 19:40:01 +00005038 bool isMarkedTailCall =
5039 cast<ConstantSDNode>(OpCall.getOperand(3))->getValue() != 0;
5040 // If CALL node has tail call attribute set to true and the call is not
5041 // eligible (no RET or the target rejects) the attribute is fixed to
Arnold Schwaighofer48abc5c2007-10-12 21:30:57 +00005042 // false. The TargetLowering::IsEligibleForTailCallOptimization function
Arnold Schwaighoferc85e1712007-10-11 19:40:01 +00005043 // must correctly identify tail call optimizable calls.
Arnold Schwaighofer30e62c02008-04-30 09:16:33 +00005044 if (!isMarkedTailCall) continue;
5045 if (Ret==NULL ||
5046 !TLI.IsEligibleForTailCallOptimization(OpCall, OpRet, DAG)) {
5047 // Not eligible. Mark CALL node as non tail call.
Dan Gohman475871a2008-07-27 21:46:04 +00005048 SmallVector<SDValue, 32> Ops;
Arnold Schwaighoferc85e1712007-10-11 19:40:01 +00005049 unsigned idx=0;
Arnold Schwaighofer30e62c02008-04-30 09:16:33 +00005050 for(SDNode::op_iterator I =OpCall.Val->op_begin(),
5051 E = OpCall.Val->op_end(); I != E; I++, idx++) {
Arnold Schwaighoferc85e1712007-10-11 19:40:01 +00005052 if (idx!=3)
5053 Ops.push_back(*I);
Arnold Schwaighofer30e62c02008-04-30 09:16:33 +00005054 else
Arnold Schwaighoferc85e1712007-10-11 19:40:01 +00005055 Ops.push_back(DAG.getConstant(false, TLI.getPointerTy()));
5056 }
5057 DAG.UpdateNodeOperands(OpCall, Ops.begin(), Ops.size());
Arnold Schwaighofer30e62c02008-04-30 09:16:33 +00005058 } else {
5059 // Look for tail call clobbered arguments. Emit a series of
5060 // copyto/copyfrom virtual register nodes to protect them.
Dan Gohman475871a2008-07-27 21:46:04 +00005061 SmallVector<SDValue, 32> Ops;
5062 SDValue Chain = OpCall.getOperand(0), InFlag;
Arnold Schwaighofer30e62c02008-04-30 09:16:33 +00005063 unsigned idx=0;
5064 for(SDNode::op_iterator I = OpCall.Val->op_begin(),
5065 E = OpCall.Val->op_end(); I != E; I++, idx++) {
Dan Gohman475871a2008-07-27 21:46:04 +00005066 SDValue Arg = *I;
Arnold Schwaighofer30e62c02008-04-30 09:16:33 +00005067 if (idx > 4 && (idx % 2)) {
5068 bool isByVal = cast<ARG_FLAGSSDNode>(OpCall.getOperand(idx+1))->
5069 getArgFlags().isByVal();
5070 MachineFunction &MF = DAG.getMachineFunction();
5071 MachineFrameInfo *MFI = MF.getFrameInfo();
5072 if (!isByVal &&
5073 IsPossiblyOverwrittenArgumentOfTailCall(Arg, MFI)) {
Duncan Sands83ec4b62008-06-06 12:08:01 +00005074 MVT VT = Arg.getValueType();
Arnold Schwaighofer30e62c02008-04-30 09:16:33 +00005075 unsigned VReg = MF.getRegInfo().
5076 createVirtualRegister(TLI.getRegClassFor(VT));
5077 Chain = DAG.getCopyToReg(Chain, VReg, Arg, InFlag);
5078 InFlag = Chain.getValue(1);
5079 Arg = DAG.getCopyFromReg(Chain, VReg, VT, InFlag);
5080 Chain = Arg.getValue(1);
5081 InFlag = Arg.getValue(2);
5082 }
5083 }
5084 Ops.push_back(Arg);
5085 }
5086 // Link in chain of CopyTo/CopyFromReg.
5087 Ops[0] = Chain;
5088 DAG.UpdateNodeOperands(OpCall, Ops.begin(), Ops.size());
Arnold Schwaighoferc85e1712007-10-11 19:40:01 +00005089 }
5090 }
5091 }
5092}
5093
Chris Lattner1c08c712005-01-07 07:47:53 +00005094void SelectionDAGISel::BuildSelectionDAG(SelectionDAG &DAG, BasicBlock *LLVMBB,
5095 std::vector<std::pair<MachineInstr*, unsigned> > &PHINodesToUpdate,
Nate Begemanf15485a2006-03-27 01:32:24 +00005096 FunctionLoweringInfo &FuncInfo) {
Gordon Henriksen5eca0752008-08-17 18:44:35 +00005097 SelectionDAGLowering SDL(DAG, TLI, *AA, FuncInfo, GFI);
Dan Gohman78eca172008-08-19 22:33:34 +00005098 BB = FuncInfo.MBBMap[LLVMBB];
5099
5100 // Before doing SelectionDAG ISel, see if FastISel has been requested.
5101 // FastISel doesn't currently support entry blocks, because that
5102 // requires special handling for arguments. And it doesn't support EH
5103 // landing pads, which also require special handling.
5104 // For now, also exclude blocks with terminators that aren't
5105 // unconditional branches.
5106 if (EnableFastISel &&
5107 LLVMBB != &LLVMBB->getParent()->getEntryBlock() &&
5108 !BB->isLandingPad() &&
5109 isa<BranchInst>(LLVMBB->getTerminator()) &&
5110 cast<BranchInst>(LLVMBB->getTerminator())->isUnconditional()) {
5111 if (FastISel *F = TLI.createFastISel(BB, &FuncInfo.MF,
5112 TLI.getTargetMachine().getInstrInfo())) {
5113 BasicBlock::iterator I =
5114 F->SelectInstructions(LLVMBB->begin(), LLVMBB->end(), FuncInfo.ValueMap);
5115 if (I == LLVMBB->end())
5116 // The "fast" selector selected the entire block, so we're done.
5117 return;
5118
5119 // The "fast" selector couldn't handle something and bailed.
5120 // For the temporary purpose of debugging, just abort.
5121 I->dump();
5122 assert(0 && "FastISel didn't select the entire block");
5123 abort();
5124 }
5125 }
Chris Lattnerddb870b2005-01-13 17:59:43 +00005126
Chris Lattnerbf209482005-10-30 19:42:35 +00005127 // Lower any arguments needed in this block if this is the entry block.
Dan Gohmanecb7a772007-03-22 16:38:57 +00005128 if (LLVMBB == &LLVMBB->getParent()->getEntryBlock())
Dan Gohman86e1ebf2008-03-27 19:56:19 +00005129 LowerArguments(LLVMBB, SDL);
Chris Lattner1c08c712005-01-07 07:47:53 +00005130
Chris Lattner1c08c712005-01-07 07:47:53 +00005131 SDL.setCurrentBasicBlock(BB);
5132
Duncan Sandsf4070822007-06-15 19:04:19 +00005133 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Duncan Sands9fac0b52007-06-06 10:05:18 +00005134
Dale Johannesen1532f3d2008-04-02 00:25:04 +00005135 if (MMI && BB->isLandingPad()) {
Duncan Sandsf4070822007-06-15 19:04:19 +00005136 // Add a label to mark the beginning of the landing pad. Deletion of the
5137 // landing pad can thus be detected via the MachineModuleInfo.
5138 unsigned LabelID = MMI->addLandingPad(BB);
Dan Gohman44066042008-07-01 00:05:16 +00005139 DAG.setRoot(DAG.getLabel(ISD::EH_LABEL, DAG.getEntryNode(), LabelID));
Duncan Sandsf4070822007-06-15 19:04:19 +00005140
Evan Chenge47c3332007-06-27 18:45:32 +00005141 // Mark exception register as live in.
5142 unsigned Reg = TLI.getExceptionAddressRegister();
5143 if (Reg) BB->addLiveIn(Reg);
5144
5145 // Mark exception selector register as live in.
5146 Reg = TLI.getExceptionSelectorRegister();
5147 if (Reg) BB->addLiveIn(Reg);
5148
Duncan Sandsf4070822007-06-15 19:04:19 +00005149 // FIXME: Hack around an exception handling flaw (PR1508): the personality
5150 // function and list of typeids logically belong to the invoke (or, if you
5151 // like, the basic block containing the invoke), and need to be associated
5152 // with it in the dwarf exception handling tables. Currently however the
Duncan Sandscf26d7c2007-07-04 20:52:51 +00005153 // information is provided by an intrinsic (eh.selector) that can be moved
5154 // to unexpected places by the optimizers: if the unwind edge is critical,
5155 // then breaking it can result in the intrinsics being in the successor of
5156 // the landing pad, not the landing pad itself. This results in exceptions
5157 // not being caught because no typeids are associated with the invoke.
5158 // This may not be the only way things can go wrong, but it is the only way
5159 // we try to work around for the moment.
Duncan Sandsf4070822007-06-15 19:04:19 +00005160 BranchInst *Br = dyn_cast<BranchInst>(LLVMBB->getTerminator());
5161
5162 if (Br && Br->isUnconditional()) { // Critical edge?
5163 BasicBlock::iterator I, E;
5164 for (I = LLVMBB->begin(), E = --LLVMBB->end(); I != E; ++I)
Duncan Sandscf26d7c2007-07-04 20:52:51 +00005165 if (isSelector(I))
Duncan Sandsf4070822007-06-15 19:04:19 +00005166 break;
5167
5168 if (I == E)
5169 // No catch info found - try to extract some from the successor.
5170 copyCatchInfo(Br->getSuccessor(0), LLVMBB, MMI, FuncInfo);
Duncan Sands9fac0b52007-06-06 10:05:18 +00005171 }
5172 }
5173
Chris Lattner1c08c712005-01-07 07:47:53 +00005174 // Lower all of the non-terminator instructions.
5175 for (BasicBlock::iterator I = LLVMBB->begin(), E = --LLVMBB->end();
5176 I != E; ++I)
5177 SDL.visit(*I);
Duncan Sandsf19f6bb2007-06-13 05:51:31 +00005178
Chris Lattner1c08c712005-01-07 07:47:53 +00005179 // Ensure that all instructions which are used outside of their defining
Duncan Sandsf19f6bb2007-06-13 05:51:31 +00005180 // blocks are available as virtual registers. Invoke is handled elsewhere.
Chris Lattner1c08c712005-01-07 07:47:53 +00005181 for (BasicBlock::iterator I = LLVMBB->begin(), E = LLVMBB->end(); I != E;++I)
Duncan Sandsf19f6bb2007-06-13 05:51:31 +00005182 if (!I->use_empty() && !isa<PHINode>(I) && !isa<InvokeInst>(I)) {
Chris Lattner9f24ad72007-02-04 01:35:11 +00005183 DenseMap<const Value*, unsigned>::iterator VMI =FuncInfo.ValueMap.find(I);
Chris Lattner1c08c712005-01-07 07:47:53 +00005184 if (VMI != FuncInfo.ValueMap.end())
Dan Gohman86e1ebf2008-03-27 19:56:19 +00005185 SDL.CopyValueToVirtualRegister(I, VMI->second);
Chris Lattner1c08c712005-01-07 07:47:53 +00005186 }
5187
5188 // Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
5189 // ensure constants are generated when needed. Remember the virtual registers
5190 // that need to be added to the Machine PHI nodes as input. We cannot just
5191 // directly add them, because expansion might result in multiple MBB's for one
5192 // BB. As such, the start of the BB might correspond to a different MBB than
5193 // the end.
Misha Brukmanedf128a2005-04-21 22:36:52 +00005194 //
Chris Lattner8c494ab2006-10-27 23:50:33 +00005195 TerminatorInst *TI = LLVMBB->getTerminator();
Chris Lattner1c08c712005-01-07 07:47:53 +00005196
5197 // Emit constants only once even if used by multiple PHI nodes.
5198 std::map<Constant*, unsigned> ConstantsOut;
Chris Lattnerd5e93c02006-09-07 01:59:34 +00005199
Chris Lattner8c494ab2006-10-27 23:50:33 +00005200 // Vector bool would be better, but vector<bool> is really slow.
5201 std::vector<unsigned char> SuccsHandled;
5202 if (TI->getNumSuccessors())
5203 SuccsHandled.resize(BB->getParent()->getNumBlockIDs());
5204
Dan Gohman532dc2e2007-07-09 20:59:04 +00005205 // Check successor nodes' PHI nodes that expect a constant to be available
5206 // from this block.
Chris Lattner1c08c712005-01-07 07:47:53 +00005207 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
5208 BasicBlock *SuccBB = TI->getSuccessor(succ);
Chris Lattnerd5e93c02006-09-07 01:59:34 +00005209 if (!isa<PHINode>(SuccBB->begin())) continue;
Chris Lattner8c494ab2006-10-27 23:50:33 +00005210 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
Chris Lattnerd5e93c02006-09-07 01:59:34 +00005211
Chris Lattner8c494ab2006-10-27 23:50:33 +00005212 // If this terminator has multiple identical successors (common for
5213 // switches), only handle each succ once.
5214 unsigned SuccMBBNo = SuccMBB->getNumber();
5215 if (SuccsHandled[SuccMBBNo]) continue;
5216 SuccsHandled[SuccMBBNo] = true;
5217
5218 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
Chris Lattner1c08c712005-01-07 07:47:53 +00005219 PHINode *PN;
5220
5221 // At this point we know that there is a 1-1 correspondence between LLVM PHI
5222 // nodes and Machine PHI nodes, but the incoming operands have not been
5223 // emitted yet.
5224 for (BasicBlock::iterator I = SuccBB->begin();
Chris Lattner8c494ab2006-10-27 23:50:33 +00005225 (PN = dyn_cast<PHINode>(I)); ++I) {
5226 // Ignore dead phi's.
5227 if (PN->use_empty()) continue;
5228
5229 unsigned Reg;
5230 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
Chris Lattner3f7927c2006-11-29 01:12:32 +00005231
Chris Lattner8c494ab2006-10-27 23:50:33 +00005232 if (Constant *C = dyn_cast<Constant>(PHIOp)) {
5233 unsigned &RegOut = ConstantsOut[C];
5234 if (RegOut == 0) {
5235 RegOut = FuncInfo.CreateRegForValue(C);
Dan Gohman86e1ebf2008-03-27 19:56:19 +00005236 SDL.CopyValueToVirtualRegister(C, RegOut);
Chris Lattner1c08c712005-01-07 07:47:53 +00005237 }
Chris Lattner8c494ab2006-10-27 23:50:33 +00005238 Reg = RegOut;
5239 } else {
5240 Reg = FuncInfo.ValueMap[PHIOp];
5241 if (Reg == 0) {
5242 assert(isa<AllocaInst>(PHIOp) &&
5243 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
5244 "Didn't codegen value into a register!??");
5245 Reg = FuncInfo.CreateRegForValue(PHIOp);
Dan Gohman86e1ebf2008-03-27 19:56:19 +00005246 SDL.CopyValueToVirtualRegister(PHIOp, Reg);
Chris Lattner7e021512006-03-31 02:12:18 +00005247 }
Chris Lattner1c08c712005-01-07 07:47:53 +00005248 }
Chris Lattner8c494ab2006-10-27 23:50:33 +00005249
5250 // Remember that this register needs to added to the machine PHI node as
5251 // the input for this MBB.
Dan Gohman6f498b02008-08-04 23:42:46 +00005252 SmallVector<MVT, 4> ValueVTs;
5253 ComputeValueVTs(TLI, PN->getType(), ValueVTs);
5254 for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
5255 MVT VT = ValueVTs[vti];
5256 unsigned NumRegisters = TLI.getNumRegisters(VT);
5257 for (unsigned i = 0, e = NumRegisters; i != e; ++i)
5258 PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
5259 Reg += NumRegisters;
5260 }
Chris Lattner8c494ab2006-10-27 23:50:33 +00005261 }
Chris Lattner1c08c712005-01-07 07:47:53 +00005262 }
5263 ConstantsOut.clear();
5264
5265 // Lower the terminator after the copies are emitted.
Duncan Sandsf19f6bb2007-06-13 05:51:31 +00005266 SDL.visit(*LLVMBB->getTerminator());
Chris Lattnera651cf62005-01-17 19:43:36 +00005267
Nate Begemanf15485a2006-03-27 01:32:24 +00005268 // Copy over any CaseBlock records that may now exist due to SwitchInst
Nate Begeman37efe672006-04-22 18:53:45 +00005269 // lowering, as well as any jump table information.
Nate Begemanf15485a2006-03-27 01:32:24 +00005270 SwitchCases.clear();
5271 SwitchCases = SDL.SwitchCases;
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00005272 JTCases.clear();
5273 JTCases = SDL.JTCases;
Anton Korobeynikov4198c582007-04-09 12:31:58 +00005274 BitTestCases.clear();
5275 BitTestCases = SDL.BitTestCases;
5276
Chris Lattnera651cf62005-01-17 19:43:36 +00005277 // Make sure the root of the DAG is up-to-date.
Dan Gohman86e1ebf2008-03-27 19:56:19 +00005278 DAG.setRoot(SDL.getControlRoot());
Arnold Schwaighoferc85e1712007-10-11 19:40:01 +00005279
5280 // Check whether calls in this block are real tail calls. Fix up CALL nodes
5281 // with correct tailcall attribute so that the target can rely on the tailcall
5282 // attribute indicating whether the call is really eligible for tail call
5283 // optimization.
5284 CheckDAGForTailCallsAndFixThem(DAG, TLI);
Chris Lattner1c08c712005-01-07 07:47:53 +00005285}
5286
Chris Lattneread0d882008-06-17 06:09:18 +00005287void SelectionDAGISel::ComputeLiveOutVRegInfo(SelectionDAG &DAG) {
5288 SmallPtrSet<SDNode*, 128> VisitedNodes;
5289 SmallVector<SDNode*, 128> Worklist;
5290
5291 Worklist.push_back(DAG.getRoot().Val);
5292
5293 APInt Mask;
5294 APInt KnownZero;
5295 APInt KnownOne;
5296
5297 while (!Worklist.empty()) {
5298 SDNode *N = Worklist.back();
5299 Worklist.pop_back();
5300
5301 // If we've already seen this node, ignore it.
5302 if (!VisitedNodes.insert(N))
5303 continue;
5304
5305 // Otherwise, add all chain operands to the worklist.
5306 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
5307 if (N->getOperand(i).getValueType() == MVT::Other)
5308 Worklist.push_back(N->getOperand(i).Val);
5309
5310 // If this is a CopyToReg with a vreg dest, process it.
5311 if (N->getOpcode() != ISD::CopyToReg)
5312 continue;
5313
5314 unsigned DestReg = cast<RegisterSDNode>(N->getOperand(1))->getReg();
5315 if (!TargetRegisterInfo::isVirtualRegister(DestReg))
5316 continue;
5317
5318 // Ignore non-scalar or non-integer values.
Dan Gohman475871a2008-07-27 21:46:04 +00005319 SDValue Src = N->getOperand(2);
Chris Lattneread0d882008-06-17 06:09:18 +00005320 MVT SrcVT = Src.getValueType();
5321 if (!SrcVT.isInteger() || SrcVT.isVector())
5322 continue;
5323
5324 unsigned NumSignBits = DAG.ComputeNumSignBits(Src);
5325 Mask = APInt::getAllOnesValue(SrcVT.getSizeInBits());
5326 DAG.ComputeMaskedBits(Src, Mask, KnownZero, KnownOne);
5327
5328 // Only install this information if it tells us something.
5329 if (NumSignBits != 1 || KnownZero != 0 || KnownOne != 0) {
5330 DestReg -= TargetRegisterInfo::FirstVirtualRegister;
5331 FunctionLoweringInfo &FLI = DAG.getFunctionLoweringInfo();
5332 if (DestReg >= FLI.LiveOutRegInfo.size())
5333 FLI.LiveOutRegInfo.resize(DestReg+1);
5334 FunctionLoweringInfo::LiveOutInfo &LOI = FLI.LiveOutRegInfo[DestReg];
5335 LOI.NumSignBits = NumSignBits;
5336 LOI.KnownOne = NumSignBits;
5337 LOI.KnownZero = NumSignBits;
5338 }
5339 }
5340}
5341
Nate Begemanf15485a2006-03-27 01:32:24 +00005342void SelectionDAGISel::CodeGenAndEmitDAG(SelectionDAG &DAG) {
Dan Gohman462dc7f2008-07-21 20:00:07 +00005343 std::string GroupName;
5344 if (TimePassesIsEnabled)
5345 GroupName = "Instruction Selection and Scheduling";
5346 std::string BlockName;
5347 if (ViewDAGCombine1 || ViewLegalizeTypesDAGs || ViewLegalizeDAGs ||
5348 ViewDAGCombine2 || ViewISelDAGs || ViewSchedDAGs || ViewSUnitDAGs)
5349 BlockName = DAG.getMachineFunction().getFunction()->getName() + ':' +
5350 BB->getBasicBlock()->getName();
5351
5352 DOUT << "Initial selection DAG:\n";
Dan Gohman417e11b2007-10-08 15:12:17 +00005353 DEBUG(DAG.dump());
Dan Gohman462dc7f2008-07-21 20:00:07 +00005354
5355 if (ViewDAGCombine1) DAG.viewGraph("dag-combine1 input for " + BlockName);
Dan Gohman417e11b2007-10-08 15:12:17 +00005356
Chris Lattneraf21d552005-10-10 16:47:10 +00005357 // Run the DAG combiner in pre-legalize mode.
Evan Chengebffb662008-07-01 17:59:20 +00005358 if (TimePassesIsEnabled) {
Dan Gohman5e843682008-07-14 18:19:29 +00005359 NamedRegionTimer T("DAG Combining 1", GroupName);
Evan Chengebffb662008-07-01 17:59:20 +00005360 DAG.Combine(false, *AA);
5361 } else {
5362 DAG.Combine(false, *AA);
5363 }
Nate Begeman2300f552005-09-07 00:15:36 +00005364
Dan Gohman417e11b2007-10-08 15:12:17 +00005365 DOUT << "Optimized lowered selection DAG:\n";
Chris Lattner1c08c712005-01-07 07:47:53 +00005366 DEBUG(DAG.dump());
Duncan Sandsf00e74f2008-07-17 17:06:03 +00005367
Chris Lattner1c08c712005-01-07 07:47:53 +00005368 // Second step, hack on the DAG until it only uses operations and types that
5369 // the target supports.
Duncan Sandsf00e74f2008-07-17 17:06:03 +00005370 if (EnableLegalizeTypes) {// Enable this some day.
Dan Gohman462dc7f2008-07-21 20:00:07 +00005371 if (ViewLegalizeTypesDAGs) DAG.viewGraph("legalize-types input for " +
5372 BlockName);
5373
5374 if (TimePassesIsEnabled) {
5375 NamedRegionTimer T("Type Legalization", GroupName);
5376 DAG.LegalizeTypes();
5377 } else {
5378 DAG.LegalizeTypes();
5379 }
5380
5381 DOUT << "Type-legalized selection DAG:\n";
5382 DEBUG(DAG.dump());
5383
Chris Lattner70587ea2008-07-10 23:37:50 +00005384 // TODO: enable a dag combine pass here.
5385 }
Duncan Sandsf00e74f2008-07-17 17:06:03 +00005386
Dan Gohman462dc7f2008-07-21 20:00:07 +00005387 if (ViewLegalizeDAGs) DAG.viewGraph("legalize input for " + BlockName);
5388
Evan Chengebffb662008-07-01 17:59:20 +00005389 if (TimePassesIsEnabled) {
Dan Gohman5e843682008-07-14 18:19:29 +00005390 NamedRegionTimer T("DAG Legalization", GroupName);
Evan Chengebffb662008-07-01 17:59:20 +00005391 DAG.Legalize();
5392 } else {
5393 DAG.Legalize();
5394 }
Nate Begemanf15485a2006-03-27 01:32:24 +00005395
Bill Wendling832171c2006-12-07 20:04:42 +00005396 DOUT << "Legalized selection DAG:\n";
Chris Lattner1c08c712005-01-07 07:47:53 +00005397 DEBUG(DAG.dump());
Nate Begemanf15485a2006-03-27 01:32:24 +00005398
Dan Gohman462dc7f2008-07-21 20:00:07 +00005399 if (ViewDAGCombine2) DAG.viewGraph("dag-combine2 input for " + BlockName);
5400
Chris Lattneraf21d552005-10-10 16:47:10 +00005401 // Run the DAG combiner in post-legalize mode.
Evan Chengebffb662008-07-01 17:59:20 +00005402 if (TimePassesIsEnabled) {
Dan Gohman5e843682008-07-14 18:19:29 +00005403 NamedRegionTimer T("DAG Combining 2", GroupName);
Evan Chengebffb662008-07-01 17:59:20 +00005404 DAG.Combine(true, *AA);
5405 } else {
5406 DAG.Combine(true, *AA);
5407 }
Nate Begeman2300f552005-09-07 00:15:36 +00005408
Dan Gohman417e11b2007-10-08 15:12:17 +00005409 DOUT << "Optimized legalized selection DAG:\n";
5410 DEBUG(DAG.dump());
5411
Dan Gohman462dc7f2008-07-21 20:00:07 +00005412 if (ViewISelDAGs) DAG.viewGraph("isel input for " + BlockName);
Chris Lattneread0d882008-06-17 06:09:18 +00005413
Dan Gohman925a7e82008-08-13 19:47:40 +00005414 if (!Fast && EnableValueProp)
Chris Lattneread0d882008-06-17 06:09:18 +00005415 ComputeLiveOutVRegInfo(DAG);
Evan Cheng552c4a82006-04-28 02:09:19 +00005416
Chris Lattnera33ef482005-03-30 01:10:47 +00005417 // Third, instruction select all of the operations to machine code, adding the
5418 // code to the MachineBasicBlock.
Evan Chengebffb662008-07-01 17:59:20 +00005419 if (TimePassesIsEnabled) {
Dan Gohman5e843682008-07-14 18:19:29 +00005420 NamedRegionTimer T("Instruction Selection", GroupName);
Evan Chengebffb662008-07-01 17:59:20 +00005421 InstructionSelect(DAG);
5422 } else {
5423 InstructionSelect(DAG);
5424 }
Evan Chengdb8d56b2008-06-30 20:45:06 +00005425
Dan Gohman462dc7f2008-07-21 20:00:07 +00005426 DOUT << "Selected selection DAG:\n";
5427 DEBUG(DAG.dump());
5428
5429 if (ViewSchedDAGs) DAG.viewGraph("scheduler input for " + BlockName);
5430
Dan Gohman5e843682008-07-14 18:19:29 +00005431 // Schedule machine code.
5432 ScheduleDAG *Scheduler;
5433 if (TimePassesIsEnabled) {
5434 NamedRegionTimer T("Instruction Scheduling", GroupName);
5435 Scheduler = Schedule(DAG);
5436 } else {
5437 Scheduler = Schedule(DAG);
5438 }
5439
Dan Gohman462dc7f2008-07-21 20:00:07 +00005440 if (ViewSUnitDAGs) Scheduler->viewGraph();
5441
Evan Chengdb8d56b2008-06-30 20:45:06 +00005442 // Emit machine code to BB. This can change 'BB' to the last block being
5443 // inserted into.
Evan Chengebffb662008-07-01 17:59:20 +00005444 if (TimePassesIsEnabled) {
Dan Gohman5e843682008-07-14 18:19:29 +00005445 NamedRegionTimer T("Instruction Creation", GroupName);
5446 BB = Scheduler->EmitSchedule();
Evan Chengebffb662008-07-01 17:59:20 +00005447 } else {
Dan Gohman5e843682008-07-14 18:19:29 +00005448 BB = Scheduler->EmitSchedule();
5449 }
5450
5451 // Free the scheduler state.
5452 if (TimePassesIsEnabled) {
5453 NamedRegionTimer T("Instruction Scheduling Cleanup", GroupName);
5454 delete Scheduler;
5455 } else {
5456 delete Scheduler;
Evan Chengebffb662008-07-01 17:59:20 +00005457 }
Evan Chengdb8d56b2008-06-30 20:45:06 +00005458
5459 // Perform target specific isel post processing.
Evan Chengebffb662008-07-01 17:59:20 +00005460 if (TimePassesIsEnabled) {
Dan Gohman5e843682008-07-14 18:19:29 +00005461 NamedRegionTimer T("Instruction Selection Post Processing", GroupName);
Dan Gohman462dc7f2008-07-21 20:00:07 +00005462 InstructionSelectPostProcessing();
Evan Chengebffb662008-07-01 17:59:20 +00005463 } else {
Dan Gohman462dc7f2008-07-21 20:00:07 +00005464 InstructionSelectPostProcessing();
Evan Chengebffb662008-07-01 17:59:20 +00005465 }
Nate Begemanf15485a2006-03-27 01:32:24 +00005466
Bill Wendling832171c2006-12-07 20:04:42 +00005467 DOUT << "Selected machine code:\n";
Chris Lattner1c08c712005-01-07 07:47:53 +00005468 DEBUG(BB->dump());
Nate Begemanf15485a2006-03-27 01:32:24 +00005469}
Chris Lattner1c08c712005-01-07 07:47:53 +00005470
Dan Gohman0e5f1302008-07-07 23:02:41 +00005471void SelectionDAGISel::SelectAllBasicBlocks(Function &Fn, MachineFunction &MF,
5472 FunctionLoweringInfo &FuncInfo) {
Dan Gohmanfed90b62008-07-28 21:51:04 +00005473 // Define NodeAllocator here so that memory allocation is reused for
Dan Gohman0e5f1302008-07-07 23:02:41 +00005474 // each basic block.
Dan Gohmanfed90b62008-07-28 21:51:04 +00005475 NodeAllocatorType NodeAllocator;
Dan Gohman0e5f1302008-07-07 23:02:41 +00005476
Evan Cheng381cb072008-08-08 07:27:28 +00005477 SimpleBBISel SISel(MF, TLI);
Evan Cheng39fd6e82008-08-07 00:43:25 +00005478 std::vector<std::pair<MachineInstr*, unsigned> > PHINodesToUpdate;
5479 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I) {
5480 BasicBlock *LLVMBB = &*I;
5481 PHINodesToUpdate.clear();
Evan Cheng381cb072008-08-08 07:27:28 +00005482
Dan Gohman925a7e82008-08-13 19:47:40 +00005483 if (!Fast || !SISel.SelectBasicBlock(LLVMBB, FuncInfo.MBBMap[LLVMBB]))
Evan Cheng381cb072008-08-08 07:27:28 +00005484 SelectBasicBlock(LLVMBB, MF, FuncInfo, PHINodesToUpdate, NodeAllocator);
Evan Cheng39fd6e82008-08-07 00:43:25 +00005485 FinishBasicBlock(LLVMBB, MF, FuncInfo, PHINodesToUpdate, NodeAllocator);
5486 }
Dan Gohman0e5f1302008-07-07 23:02:41 +00005487}
5488
Dan Gohmanfed90b62008-07-28 21:51:04 +00005489void
5490SelectionDAGISel::SelectBasicBlock(BasicBlock *LLVMBB, MachineFunction &MF,
5491 FunctionLoweringInfo &FuncInfo,
Evan Cheng39fd6e82008-08-07 00:43:25 +00005492 std::vector<std::pair<MachineInstr*, unsigned> > &PHINodesToUpdate,
Dan Gohmanfed90b62008-07-28 21:51:04 +00005493 NodeAllocatorType &NodeAllocator) {
Evan Cheng39fd6e82008-08-07 00:43:25 +00005494 SelectionDAG DAG(TLI, MF, FuncInfo,
5495 getAnalysisToUpdate<MachineModuleInfo>(),
5496 NodeAllocator);
5497 CurDAG = &DAG;
Nate Begemanf15485a2006-03-27 01:32:24 +00005498
Evan Cheng39fd6e82008-08-07 00:43:25 +00005499 // First step, lower LLVM code to some DAG. This DAG may use operations and
5500 // types that are not supported by the target.
5501 BuildSelectionDAG(DAG, LLVMBB, PHINodesToUpdate, FuncInfo);
Nate Begemanf15485a2006-03-27 01:32:24 +00005502
Evan Cheng39fd6e82008-08-07 00:43:25 +00005503 // Second step, emit the lowered DAG as machine code.
5504 CodeGenAndEmitDAG(DAG);
5505}
Anton Korobeynikov4198c582007-04-09 12:31:58 +00005506
Evan Cheng39fd6e82008-08-07 00:43:25 +00005507void
5508SelectionDAGISel::FinishBasicBlock(BasicBlock *LLVMBB, MachineFunction &MF,
5509 FunctionLoweringInfo &FuncInfo,
5510 std::vector<std::pair<MachineInstr*, unsigned> > &PHINodesToUpdate,
5511 NodeAllocatorType &NodeAllocator) {
Anton Korobeynikov4198c582007-04-09 12:31:58 +00005512 DOUT << "Total amount of phi nodes to update: "
5513 << PHINodesToUpdate.size() << "\n";
5514 DEBUG(for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i)
5515 DOUT << "Node " << i << " : (" << PHINodesToUpdate[i].first
5516 << ", " << PHINodesToUpdate[i].second << ")\n";);
Nate Begemanf15485a2006-03-27 01:32:24 +00005517
Chris Lattnera33ef482005-03-30 01:10:47 +00005518 // Next, now that we know what the last MBB the LLVM BB expanded is, update
Chris Lattner1c08c712005-01-07 07:47:53 +00005519 // PHI nodes in successors.
Anton Korobeynikov4198c582007-04-09 12:31:58 +00005520 if (SwitchCases.empty() && JTCases.empty() && BitTestCases.empty()) {
Nate Begemanf15485a2006-03-27 01:32:24 +00005521 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
5522 MachineInstr *PHI = PHINodesToUpdate[i].first;
5523 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
5524 "This is not a machine PHI node that we are updating!");
Chris Lattner9ce2e9d2007-12-30 00:57:42 +00005525 PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[i].second,
5526 false));
5527 PHI->addOperand(MachineOperand::CreateMBB(BB));
Nate Begemanf15485a2006-03-27 01:32:24 +00005528 }
5529 return;
Chris Lattner1c08c712005-01-07 07:47:53 +00005530 }
Anton Korobeynikov4198c582007-04-09 12:31:58 +00005531
5532 for (unsigned i = 0, e = BitTestCases.size(); i != e; ++i) {
5533 // Lower header first, if it wasn't already lowered
5534 if (!BitTestCases[i].Emitted) {
Chris Lattneread0d882008-06-17 06:09:18 +00005535 SelectionDAG HSDAG(TLI, MF, FuncInfo,
Dan Gohman0e5f1302008-07-07 23:02:41 +00005536 getAnalysisToUpdate<MachineModuleInfo>(),
Dan Gohmanfed90b62008-07-28 21:51:04 +00005537 NodeAllocator);
Anton Korobeynikov4198c582007-04-09 12:31:58 +00005538 CurDAG = &HSDAG;
Gordon Henriksen5eca0752008-08-17 18:44:35 +00005539 SelectionDAGLowering HSDL(HSDAG, TLI, *AA, FuncInfo, GFI);
Anton Korobeynikov4198c582007-04-09 12:31:58 +00005540 // Set the current basic block to the mbb we wish to insert the code into
5541 BB = BitTestCases[i].Parent;
5542 HSDL.setCurrentBasicBlock(BB);
5543 // Emit the code
5544 HSDL.visitBitTestHeader(BitTestCases[i]);
5545 HSDAG.setRoot(HSDL.getRoot());
5546 CodeGenAndEmitDAG(HSDAG);
5547 }
5548
5549 for (unsigned j = 0, ej = BitTestCases[i].Cases.size(); j != ej; ++j) {
Chris Lattneread0d882008-06-17 06:09:18 +00005550 SelectionDAG BSDAG(TLI, MF, FuncInfo,
Dan Gohman0e5f1302008-07-07 23:02:41 +00005551 getAnalysisToUpdate<MachineModuleInfo>(),
Dan Gohmanfed90b62008-07-28 21:51:04 +00005552 NodeAllocator);
Anton Korobeynikov4198c582007-04-09 12:31:58 +00005553 CurDAG = &BSDAG;
Gordon Henriksen5eca0752008-08-17 18:44:35 +00005554 SelectionDAGLowering BSDL(BSDAG, TLI, *AA, FuncInfo, GFI);
Anton Korobeynikov4198c582007-04-09 12:31:58 +00005555 // Set the current basic block to the mbb we wish to insert the code into
5556 BB = BitTestCases[i].Cases[j].ThisBB;
5557 BSDL.setCurrentBasicBlock(BB);
5558 // Emit the code
5559 if (j+1 != ej)
5560 BSDL.visitBitTestCase(BitTestCases[i].Cases[j+1].ThisBB,
5561 BitTestCases[i].Reg,
5562 BitTestCases[i].Cases[j]);
5563 else
5564 BSDL.visitBitTestCase(BitTestCases[i].Default,
5565 BitTestCases[i].Reg,
5566 BitTestCases[i].Cases[j]);
5567
5568
5569 BSDAG.setRoot(BSDL.getRoot());
5570 CodeGenAndEmitDAG(BSDAG);
5571 }
5572
5573 // Update PHI Nodes
5574 for (unsigned pi = 0, pe = PHINodesToUpdate.size(); pi != pe; ++pi) {
5575 MachineInstr *PHI = PHINodesToUpdate[pi].first;
5576 MachineBasicBlock *PHIBB = PHI->getParent();
5577 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
5578 "This is not a machine PHI node that we are updating!");
5579 // This is "default" BB. We have two jumps to it. From "header" BB and
5580 // from last "case" BB.
5581 if (PHIBB == BitTestCases[i].Default) {
Chris Lattner9ce2e9d2007-12-30 00:57:42 +00005582 PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[pi].second,
5583 false));
5584 PHI->addOperand(MachineOperand::CreateMBB(BitTestCases[i].Parent));
5585 PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[pi].second,
5586 false));
5587 PHI->addOperand(MachineOperand::CreateMBB(BitTestCases[i].Cases.
5588 back().ThisBB));
Anton Korobeynikov4198c582007-04-09 12:31:58 +00005589 }
5590 // One of "cases" BB.
5591 for (unsigned j = 0, ej = BitTestCases[i].Cases.size(); j != ej; ++j) {
5592 MachineBasicBlock* cBB = BitTestCases[i].Cases[j].ThisBB;
5593 if (cBB->succ_end() !=
5594 std::find(cBB->succ_begin(),cBB->succ_end(), PHIBB)) {
Chris Lattner9ce2e9d2007-12-30 00:57:42 +00005595 PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[pi].second,
5596 false));
5597 PHI->addOperand(MachineOperand::CreateMBB(cBB));
Anton Korobeynikov4198c582007-04-09 12:31:58 +00005598 }
5599 }
5600 }
5601 }
5602
Nate Begeman9453eea2006-04-23 06:26:20 +00005603 // If the JumpTable record is filled in, then we need to emit a jump table.
5604 // Updating the PHI nodes is tricky in this case, since we need to determine
5605 // whether the PHI is a successor of the range check MBB or the jump table MBB
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00005606 for (unsigned i = 0, e = JTCases.size(); i != e; ++i) {
5607 // Lower header first, if it wasn't already lowered
5608 if (!JTCases[i].first.Emitted) {
Chris Lattneread0d882008-06-17 06:09:18 +00005609 SelectionDAG HSDAG(TLI, MF, FuncInfo,
Dan Gohman0e5f1302008-07-07 23:02:41 +00005610 getAnalysisToUpdate<MachineModuleInfo>(),
Dan Gohmanfed90b62008-07-28 21:51:04 +00005611 NodeAllocator);
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00005612 CurDAG = &HSDAG;
Gordon Henriksen5eca0752008-08-17 18:44:35 +00005613 SelectionDAGLowering HSDL(HSDAG, TLI, *AA, FuncInfo, GFI);
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00005614 // Set the current basic block to the mbb we wish to insert the code into
5615 BB = JTCases[i].first.HeaderBB;
5616 HSDL.setCurrentBasicBlock(BB);
5617 // Emit the code
5618 HSDL.visitJumpTableHeader(JTCases[i].second, JTCases[i].first);
5619 HSDAG.setRoot(HSDL.getRoot());
5620 CodeGenAndEmitDAG(HSDAG);
Anton Korobeynikov4198c582007-04-09 12:31:58 +00005621 }
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00005622
Chris Lattneread0d882008-06-17 06:09:18 +00005623 SelectionDAG JSDAG(TLI, MF, FuncInfo,
Dan Gohman0e5f1302008-07-07 23:02:41 +00005624 getAnalysisToUpdate<MachineModuleInfo>(),
Dan Gohmanfed90b62008-07-28 21:51:04 +00005625 NodeAllocator);
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00005626 CurDAG = &JSDAG;
Gordon Henriksen5eca0752008-08-17 18:44:35 +00005627 SelectionDAGLowering JSDL(JSDAG, TLI, *AA, FuncInfo, GFI);
Nate Begeman37efe672006-04-22 18:53:45 +00005628 // Set the current basic block to the mbb we wish to insert the code into
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00005629 BB = JTCases[i].second.MBB;
5630 JSDL.setCurrentBasicBlock(BB);
Nate Begeman37efe672006-04-22 18:53:45 +00005631 // Emit the code
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00005632 JSDL.visitJumpTable(JTCases[i].second);
5633 JSDAG.setRoot(JSDL.getRoot());
5634 CodeGenAndEmitDAG(JSDAG);
5635
Nate Begeman37efe672006-04-22 18:53:45 +00005636 // Update PHI Nodes
5637 for (unsigned pi = 0, pe = PHINodesToUpdate.size(); pi != pe; ++pi) {
5638 MachineInstr *PHI = PHINodesToUpdate[pi].first;
5639 MachineBasicBlock *PHIBB = PHI->getParent();
5640 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
5641 "This is not a machine PHI node that we are updating!");
Anton Korobeynikov4198c582007-04-09 12:31:58 +00005642 // "default" BB. We can go there only from header BB.
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00005643 if (PHIBB == JTCases[i].second.Default) {
Chris Lattner9ce2e9d2007-12-30 00:57:42 +00005644 PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[pi].second,
5645 false));
5646 PHI->addOperand(MachineOperand::CreateMBB(JTCases[i].first.HeaderBB));
Nate Begemanf4360a42006-05-03 03:48:02 +00005647 }
Anton Korobeynikov4198c582007-04-09 12:31:58 +00005648 // JT BB. Just iterate over successors here
Nate Begemanf4360a42006-05-03 03:48:02 +00005649 if (BB->succ_end() != std::find(BB->succ_begin(),BB->succ_end(), PHIBB)) {
Chris Lattner9ce2e9d2007-12-30 00:57:42 +00005650 PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[pi].second,
5651 false));
5652 PHI->addOperand(MachineOperand::CreateMBB(BB));
Nate Begeman37efe672006-04-22 18:53:45 +00005653 }
5654 }
Nate Begeman37efe672006-04-22 18:53:45 +00005655 }
5656
Chris Lattnerb2e806e2006-10-22 23:00:53 +00005657 // If the switch block involved a branch to one of the actual successors, we
5658 // need to update PHI nodes in that block.
5659 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
5660 MachineInstr *PHI = PHINodesToUpdate[i].first;
5661 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
5662 "This is not a machine PHI node that we are updating!");
5663 if (BB->isSuccessor(PHI->getParent())) {
Chris Lattner9ce2e9d2007-12-30 00:57:42 +00005664 PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[i].second,
5665 false));
5666 PHI->addOperand(MachineOperand::CreateMBB(BB));
Chris Lattnerb2e806e2006-10-22 23:00:53 +00005667 }
5668 }
5669
Nate Begemanf15485a2006-03-27 01:32:24 +00005670 // If we generated any switch lowering information, build and codegen any
5671 // additional DAGs necessary.
Chris Lattnerd5e93c02006-09-07 01:59:34 +00005672 for (unsigned i = 0, e = SwitchCases.size(); i != e; ++i) {
Chris Lattneread0d882008-06-17 06:09:18 +00005673 SelectionDAG SDAG(TLI, MF, FuncInfo,
Dan Gohman0e5f1302008-07-07 23:02:41 +00005674 getAnalysisToUpdate<MachineModuleInfo>(),
Dan Gohmanfed90b62008-07-28 21:51:04 +00005675 NodeAllocator);
Nate Begemanf15485a2006-03-27 01:32:24 +00005676 CurDAG = &SDAG;
Gordon Henriksen5eca0752008-08-17 18:44:35 +00005677 SelectionDAGLowering SDL(SDAG, TLI, *AA, FuncInfo, GFI);
Chris Lattnerd5e93c02006-09-07 01:59:34 +00005678
Nate Begemanf15485a2006-03-27 01:32:24 +00005679 // Set the current basic block to the mbb we wish to insert the code into
5680 BB = SwitchCases[i].ThisBB;
5681 SDL.setCurrentBasicBlock(BB);
Chris Lattnerd5e93c02006-09-07 01:59:34 +00005682
Nate Begemanf15485a2006-03-27 01:32:24 +00005683 // Emit the code
5684 SDL.visitSwitchCase(SwitchCases[i]);
5685 SDAG.setRoot(SDL.getRoot());
5686 CodeGenAndEmitDAG(SDAG);
Chris Lattnerd5e93c02006-09-07 01:59:34 +00005687
5688 // Handle any PHI nodes in successors of this chunk, as if we were coming
5689 // from the original BB before switch expansion. Note that PHI nodes can
5690 // occur multiple times in PHINodesToUpdate. We have to be very careful to
5691 // handle them the right number of times.
Chris Lattner57ab6592006-10-24 17:57:59 +00005692 while ((BB = SwitchCases[i].TrueBB)) { // Handle LHS and RHS.
Chris Lattnerd5e93c02006-09-07 01:59:34 +00005693 for (MachineBasicBlock::iterator Phi = BB->begin();
5694 Phi != BB->end() && Phi->getOpcode() == TargetInstrInfo::PHI; ++Phi){
5695 // This value for this PHI node is recorded in PHINodesToUpdate, get it.
5696 for (unsigned pn = 0; ; ++pn) {
5697 assert(pn != PHINodesToUpdate.size() && "Didn't find PHI entry!");
5698 if (PHINodesToUpdate[pn].first == Phi) {
Chris Lattner9ce2e9d2007-12-30 00:57:42 +00005699 Phi->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[pn].
5700 second, false));
5701 Phi->addOperand(MachineOperand::CreateMBB(SwitchCases[i].ThisBB));
Chris Lattnerd5e93c02006-09-07 01:59:34 +00005702 break;
5703 }
5704 }
Nate Begemanf15485a2006-03-27 01:32:24 +00005705 }
Chris Lattnerd5e93c02006-09-07 01:59:34 +00005706
5707 // Don't process RHS if same block as LHS.
Chris Lattner57ab6592006-10-24 17:57:59 +00005708 if (BB == SwitchCases[i].FalseBB)
5709 SwitchCases[i].FalseBB = 0;
Chris Lattnerd5e93c02006-09-07 01:59:34 +00005710
5711 // If we haven't handled the RHS, do so now. Otherwise, we're done.
Chris Lattner24525952006-10-24 18:07:37 +00005712 SwitchCases[i].TrueBB = SwitchCases[i].FalseBB;
Chris Lattner57ab6592006-10-24 17:57:59 +00005713 SwitchCases[i].FalseBB = 0;
Nate Begemanf15485a2006-03-27 01:32:24 +00005714 }
Chris Lattner57ab6592006-10-24 17:57:59 +00005715 assert(SwitchCases[i].TrueBB == 0 && SwitchCases[i].FalseBB == 0);
Chris Lattnera33ef482005-03-30 01:10:47 +00005716 }
Chris Lattner1c08c712005-01-07 07:47:53 +00005717}
Evan Chenga9c20912006-01-21 02:32:06 +00005718
Jim Laskey13ec7022006-08-01 14:21:23 +00005719
Dan Gohman5e843682008-07-14 18:19:29 +00005720/// Schedule - Pick a safe ordering for instructions for each
Evan Chenga9c20912006-01-21 02:32:06 +00005721/// target node in the graph.
Dan Gohman5e843682008-07-14 18:19:29 +00005722///
5723ScheduleDAG *SelectionDAGISel::Schedule(SelectionDAG &DAG) {
Jim Laskeyeb577ba2006-08-02 12:30:23 +00005724 RegisterScheduler::FunctionPassCtor Ctor = RegisterScheduler::getDefault();
Jim Laskey13ec7022006-08-01 14:21:23 +00005725
5726 if (!Ctor) {
Jim Laskeyeb577ba2006-08-02 12:30:23 +00005727 Ctor = ISHeuristic;
Jim Laskey9373beb2006-08-01 19:14:14 +00005728 RegisterScheduler::setDefault(Ctor);
Evan Cheng4ef10862006-01-23 07:01:07 +00005729 }
Jim Laskey13ec7022006-08-01 14:21:23 +00005730
Dan Gohman925a7e82008-08-13 19:47:40 +00005731 ScheduleDAG *Scheduler = Ctor(this, &DAG, BB, Fast);
Dan Gohman5e843682008-07-14 18:19:29 +00005732 Scheduler->Run();
Dan Gohman3e1a7ae2007-08-28 20:32:58 +00005733
Dan Gohman5e843682008-07-14 18:19:29 +00005734 return Scheduler;
Evan Chenga9c20912006-01-21 02:32:06 +00005735}
Chris Lattner0e43f2b2006-02-24 02:13:54 +00005736
Chris Lattner03fc53c2006-03-06 00:22:00 +00005737
Jim Laskey9ff542f2006-08-01 18:29:48 +00005738HazardRecognizer *SelectionDAGISel::CreateTargetHazardRecognizer() {
5739 return new HazardRecognizer();
5740}
5741
Chris Lattner75548062006-10-11 03:58:02 +00005742//===----------------------------------------------------------------------===//
5743// Helper functions used by the generated instruction selector.
5744//===----------------------------------------------------------------------===//
5745// Calls to these methods are generated by tblgen.
5746
5747/// CheckAndMask - The isel is trying to match something like (and X, 255). If
5748/// the dag combiner simplified the 255, we still want to match. RHS is the
5749/// actual value in the DAG on the RHS of an AND, and DesiredMaskS is the value
5750/// specified in the .td file (e.g. 255).
Dan Gohman475871a2008-07-27 21:46:04 +00005751bool SelectionDAGISel::CheckAndMask(SDValue LHS, ConstantSDNode *RHS,
Dan Gohmandc9b3d02007-07-24 23:00:27 +00005752 int64_t DesiredMaskS) const {
Dan Gohman2e68b6f2008-02-25 21:11:39 +00005753 const APInt &ActualMask = RHS->getAPIntValue();
5754 const APInt &DesiredMask = APInt(LHS.getValueSizeInBits(), DesiredMaskS);
Chris Lattner75548062006-10-11 03:58:02 +00005755
5756 // If the actual mask exactly matches, success!
5757 if (ActualMask == DesiredMask)
5758 return true;
5759
5760 // If the actual AND mask is allowing unallowed bits, this doesn't match.
Dan Gohman2e68b6f2008-02-25 21:11:39 +00005761 if (ActualMask.intersects(~DesiredMask))
Chris Lattner75548062006-10-11 03:58:02 +00005762 return false;
5763
5764 // Otherwise, the DAG Combiner may have proven that the value coming in is
5765 // either already zero or is not demanded. Check for known zero input bits.
Dan Gohman2e68b6f2008-02-25 21:11:39 +00005766 APInt NeededMask = DesiredMask & ~ActualMask;
Dan Gohmanea859be2007-06-22 14:59:07 +00005767 if (CurDAG->MaskedValueIsZero(LHS, NeededMask))
Chris Lattner75548062006-10-11 03:58:02 +00005768 return true;
5769
5770 // TODO: check to see if missing bits are just not demanded.
5771
5772 // Otherwise, this pattern doesn't match.
5773 return false;
5774}
5775
5776/// CheckOrMask - The isel is trying to match something like (or X, 255). If
5777/// the dag combiner simplified the 255, we still want to match. RHS is the
5778/// actual value in the DAG on the RHS of an OR, and DesiredMaskS is the value
5779/// specified in the .td file (e.g. 255).
Dan Gohman475871a2008-07-27 21:46:04 +00005780bool SelectionDAGISel::CheckOrMask(SDValue LHS, ConstantSDNode *RHS,
Dan Gohman2e68b6f2008-02-25 21:11:39 +00005781 int64_t DesiredMaskS) const {
5782 const APInt &ActualMask = RHS->getAPIntValue();
5783 const APInt &DesiredMask = APInt(LHS.getValueSizeInBits(), DesiredMaskS);
Chris Lattner75548062006-10-11 03:58:02 +00005784
5785 // If the actual mask exactly matches, success!
5786 if (ActualMask == DesiredMask)
5787 return true;
5788
5789 // If the actual AND mask is allowing unallowed bits, this doesn't match.
Dan Gohman2e68b6f2008-02-25 21:11:39 +00005790 if (ActualMask.intersects(~DesiredMask))
Chris Lattner75548062006-10-11 03:58:02 +00005791 return false;
5792
5793 // Otherwise, the DAG Combiner may have proven that the value coming in is
5794 // either already zero or is not demanded. Check for known zero input bits.
Dan Gohman2e68b6f2008-02-25 21:11:39 +00005795 APInt NeededMask = DesiredMask & ~ActualMask;
Chris Lattner75548062006-10-11 03:58:02 +00005796
Dan Gohman2e68b6f2008-02-25 21:11:39 +00005797 APInt KnownZero, KnownOne;
Dan Gohmanea859be2007-06-22 14:59:07 +00005798 CurDAG->ComputeMaskedBits(LHS, NeededMask, KnownZero, KnownOne);
Chris Lattner75548062006-10-11 03:58:02 +00005799
5800 // If all the missing bits in the or are already known to be set, match!
5801 if ((NeededMask & KnownOne) == NeededMask)
5802 return true;
5803
5804 // TODO: check to see if missing bits are just not demanded.
5805
5806 // Otherwise, this pattern doesn't match.
5807 return false;
5808}
5809
Jim Laskey9ff542f2006-08-01 18:29:48 +00005810
Chris Lattner0e43f2b2006-02-24 02:13:54 +00005811/// SelectInlineAsmMemoryOperands - Calls to this are automatically generated
5812/// by tblgen. Others should not call it.
5813void SelectionDAGISel::
Dan Gohman475871a2008-07-27 21:46:04 +00005814SelectInlineAsmMemoryOperands(std::vector<SDValue> &Ops, SelectionDAG &DAG) {
5815 std::vector<SDValue> InOps;
Chris Lattner0e43f2b2006-02-24 02:13:54 +00005816 std::swap(InOps, Ops);
5817
5818 Ops.push_back(InOps[0]); // input chain.
5819 Ops.push_back(InOps[1]); // input asm string.
5820
Chris Lattner0e43f2b2006-02-24 02:13:54 +00005821 unsigned i = 2, e = InOps.size();
5822 if (InOps[e-1].getValueType() == MVT::Flag)
5823 --e; // Don't process a flag operand if it is here.
5824
5825 while (i != e) {
5826 unsigned Flags = cast<ConstantSDNode>(InOps[i])->getValue();
5827 if ((Flags & 7) != 4 /*MEM*/) {
5828 // Just skip over this operand, copying the operands verbatim.
5829 Ops.insert(Ops.end(), InOps.begin()+i, InOps.begin()+i+(Flags >> 3) + 1);
5830 i += (Flags >> 3) + 1;
5831 } else {
5832 assert((Flags >> 3) == 1 && "Memory operand with multiple values?");
5833 // Otherwise, this is a memory operand. Ask the target to select it.
Dan Gohman475871a2008-07-27 21:46:04 +00005834 std::vector<SDValue> SelOps;
Chris Lattner0e43f2b2006-02-24 02:13:54 +00005835 if (SelectInlineAsmMemoryOperand(InOps[i+1], 'm', SelOps, DAG)) {
Bill Wendling832171c2006-12-07 20:04:42 +00005836 cerr << "Could not match memory address. Inline asm failure!\n";
Chris Lattner0e43f2b2006-02-24 02:13:54 +00005837 exit(1);
5838 }
5839
5840 // Add this to the output node.
Duncan Sands83ec4b62008-06-06 12:08:01 +00005841 MVT IntPtrTy = DAG.getTargetLoweringInfo().getPointerTy();
Chris Lattner36d43962006-12-16 21:14:48 +00005842 Ops.push_back(DAG.getTargetConstant(4/*MEM*/ | (SelOps.size() << 3),
Chris Lattner4b993b12007-04-09 00:33:58 +00005843 IntPtrTy));
Chris Lattner0e43f2b2006-02-24 02:13:54 +00005844 Ops.insert(Ops.end(), SelOps.begin(), SelOps.end());
5845 i += 2;
5846 }
5847 }
5848
5849 // Add the flag input back if present.
5850 if (e != InOps.size())
5851 Ops.push_back(InOps.back());
5852}
Devang Patel794fd752007-05-01 21:15:47 +00005853
Devang Patel19974732007-05-03 01:11:54 +00005854char SelectionDAGISel::ID = 0;