blob: 01f00f459f1ee9bb697624b35f04b1d9087c9331 [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"
Anton Korobeynikov5502bf62007-04-04 21:14:49 +000015#include "llvm/ADT/BitVector.h"
Jim Laskeyc7c3f112006-10-16 20:52:31 +000016#include "llvm/Analysis/AliasAnalysis.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000017#include "llvm/CodeGen/SelectionDAGISel.h"
Evan Chenga9c20912006-01-21 02:32:06 +000018#include "llvm/CodeGen/ScheduleDAG.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"
Gordon Henriksence224772008-01-07 01:30:38 +000029#include "llvm/CodeGen/Collector.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000030#include "llvm/CodeGen/MachineFunction.h"
31#include "llvm/CodeGen/MachineFrameInfo.h"
32#include "llvm/CodeGen/MachineInstrBuilder.h"
Chris Lattner84bc5422007-12-31 04:13:23 +000033#include "llvm/CodeGen/MachineJumpTableInfo.h"
34#include "llvm/CodeGen/MachineModuleInfo.h"
35#include "llvm/CodeGen/MachineRegisterInfo.h"
Jim Laskeyeb577ba2006-08-02 12:30:23 +000036#include "llvm/CodeGen/SchedulerRegistry.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000037#include "llvm/CodeGen/SelectionDAG.h"
Dan Gohman6f0d0242008-02-10 18:45:23 +000038#include "llvm/Target/TargetRegisterInfo.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000039#include "llvm/Target/TargetData.h"
40#include "llvm/Target/TargetFrameInfo.h"
41#include "llvm/Target/TargetInstrInfo.h"
42#include "llvm/Target/TargetLowering.h"
43#include "llvm/Target/TargetMachine.h"
Vladimir Prus12472912006-05-23 13:43:15 +000044#include "llvm/Target/TargetOptions.h"
Chris Lattner7c0104b2005-11-09 04:45:33 +000045#include "llvm/Support/MathExtras.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000046#include "llvm/Support/Debug.h"
Chris Lattnera4f0b3a2006-08-27 12:54:02 +000047#include "llvm/Support/Compiler.h"
Jeff Cohen7e881032006-02-24 02:52:40 +000048#include <algorithm>
Chris Lattner1c08c712005-01-07 07:47:53 +000049using namespace llvm;
50
Chris Lattnerda8abb02005-09-01 18:44:10 +000051#ifndef NDEBUG
Chris Lattner7944d9d2005-01-12 03:41:21 +000052static cl::opt<bool>
Evan Chenga9c20912006-01-21 02:32:06 +000053ViewISelDAGs("view-isel-dags", cl::Hidden,
54 cl::desc("Pop up a window to show isel dags as they are selected"));
55static cl::opt<bool>
56ViewSchedDAGs("view-sched-dags", cl::Hidden,
57 cl::desc("Pop up a window to show sched dags as they are processed"));
Dan Gohman3e1a7ae2007-08-28 20:32:58 +000058static cl::opt<bool>
59ViewSUnitDAGs("view-sunit-dags", cl::Hidden,
Chris Lattner5bab7852008-01-25 17:24:52 +000060 cl::desc("Pop up a window to show SUnit dags after they are processed"));
Chris Lattner7944d9d2005-01-12 03:41:21 +000061#else
Dan Gohman3e1a7ae2007-08-28 20:32:58 +000062static const bool ViewISelDAGs = 0, ViewSchedDAGs = 0, ViewSUnitDAGs = 0;
Chris Lattner7944d9d2005-01-12 03:41:21 +000063#endif
64
Jim Laskeyeb577ba2006-08-02 12:30:23 +000065//===---------------------------------------------------------------------===//
66///
67/// RegisterScheduler class - Track the registration of instruction schedulers.
68///
69//===---------------------------------------------------------------------===//
70MachinePassRegistry RegisterScheduler::Registry;
71
72//===---------------------------------------------------------------------===//
73///
74/// ISHeuristic command line option for instruction schedulers.
75///
76//===---------------------------------------------------------------------===//
Dan Gohman844731a2008-05-13 00:00:25 +000077static cl::opt<RegisterScheduler::FunctionPassCtor, false,
78 RegisterPassParser<RegisterScheduler> >
79ISHeuristic("pre-RA-sched",
80 cl::init(&createDefaultScheduler),
81 cl::desc("Instruction schedulers available (before register"
82 " allocation):"));
Jim Laskey13ec7022006-08-01 14:21:23 +000083
Dan Gohman844731a2008-05-13 00:00:25 +000084static RegisterScheduler
85defaultListDAGScheduler("default", " Best scheduler for the target",
86 createDefaultScheduler);
Evan Cheng4ef10862006-01-23 07:01:07 +000087
Evan Cheng5c807602008-02-26 02:33:44 +000088namespace { struct SDISelAsmOperandInfo; }
Chris Lattnerbf996f12007-04-30 17:29:31 +000089
Chris Lattnerf899fce2008-04-27 23:48:12 +000090/// ComputeValueVTs - Given an LLVM IR type, compute a sequence of
Duncan Sands83ec4b62008-06-06 12:08:01 +000091/// MVTs that represent all the individual underlying
Chris Lattnerf899fce2008-04-27 23:48:12 +000092/// non-aggregate types that comprise it.
93static void ComputeValueVTs(const TargetLowering &TLI, const Type *Ty,
Duncan Sands83ec4b62008-06-06 12:08:01 +000094 SmallVectorImpl<MVT> &ValueVTs) {
Chris Lattnerf899fce2008-04-27 23:48:12 +000095 // Given a struct type, recursively traverse the elements.
96 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
97 for (StructType::element_iterator EI = STy->element_begin(),
98 EB = STy->element_end();
99 EI != EB; ++EI)
100 ComputeValueVTs(TLI, *EI, ValueVTs);
101 return;
Dan Gohman23ce5022008-04-25 18:27:55 +0000102 }
Chris Lattnerf899fce2008-04-27 23:48:12 +0000103 // Given an array type, recursively traverse the elements.
104 if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
105 const Type *EltTy = ATy->getElementType();
106 for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i)
107 ComputeValueVTs(TLI, EltTy, ValueVTs);
108 return;
109 }
Duncan Sands83ec4b62008-06-06 12:08:01 +0000110 // Base case: we can get an MVT for this LLVM IR type.
Chris Lattnerf899fce2008-04-27 23:48:12 +0000111 ValueVTs.push_back(TLI.getValueType(Ty));
112}
Dan Gohman23ce5022008-04-25 18:27:55 +0000113
Chris Lattnerf899fce2008-04-27 23:48:12 +0000114namespace {
Dan Gohman0fe00902008-04-28 18:10:39 +0000115 /// RegsForValue - This struct represents the registers (physical or virtual)
116 /// that a particular set of values is assigned, and the type information about
117 /// the value. The most common situation is to represent one value at a time,
118 /// but struct or array values are handled element-wise as multiple values.
119 /// The splitting of aggregates is performed recursively, so that we never
120 /// have aggregate-typed registers. The values at this point do not necessarily
121 /// have legal types, so each value may require one or more registers of some
122 /// legal type.
123 ///
Chris Lattner95255282006-06-28 23:17:24 +0000124 struct VISIBILITY_HIDDEN RegsForValue {
Dan Gohman23ce5022008-04-25 18:27:55 +0000125 /// TLI - The TargetLowering object.
Dan Gohman0fe00902008-04-28 18:10:39 +0000126 ///
Dan Gohman23ce5022008-04-25 18:27:55 +0000127 const TargetLowering *TLI;
128
Dan Gohman0fe00902008-04-28 18:10:39 +0000129 /// ValueVTs - The value types of the values, which may not be legal, and
130 /// may need be promoted or synthesized from one or more registers.
131 ///
Duncan Sands83ec4b62008-06-06 12:08:01 +0000132 SmallVector<MVT, 4> ValueVTs;
Chris Lattner864635a2006-02-22 22:37:12 +0000133
Dan Gohman0fe00902008-04-28 18:10:39 +0000134 /// RegVTs - The value types of the registers. This is the same size as
135 /// ValueVTs and it records, for each value, what the type of the assigned
136 /// register or registers are. (Individual values are never synthesized
137 /// from more than one type of register.)
138 ///
139 /// With virtual registers, the contents of RegVTs is redundant with TLI's
140 /// getRegisterType member function, however when with physical registers
141 /// it is necessary to have a separate record of the types.
Chris Lattner864635a2006-02-22 22:37:12 +0000142 ///
Duncan Sands83ec4b62008-06-06 12:08:01 +0000143 SmallVector<MVT, 4> RegVTs;
Chris Lattner864635a2006-02-22 22:37:12 +0000144
Dan Gohman0fe00902008-04-28 18:10:39 +0000145 /// Regs - This list holds the registers assigned to the values.
146 /// Each legal or promoted value requires one register, and each
147 /// expanded value requires multiple registers.
148 ///
149 SmallVector<unsigned, 4> Regs;
Chris Lattner864635a2006-02-22 22:37:12 +0000150
Dan Gohman23ce5022008-04-25 18:27:55 +0000151 RegsForValue() : TLI(0) {}
Chris Lattner864635a2006-02-22 22:37:12 +0000152
Dan Gohman23ce5022008-04-25 18:27:55 +0000153 RegsForValue(const TargetLowering &tli,
Chris Lattnerb606dba2008-04-28 06:44:42 +0000154 const SmallVector<unsigned, 4> &regs,
Duncan Sands83ec4b62008-06-06 12:08:01 +0000155 MVT regvt, MVT valuevt)
Dan Gohman0fe00902008-04-28 18:10:39 +0000156 : TLI(&tli), ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs) {}
Dan Gohman23ce5022008-04-25 18:27:55 +0000157 RegsForValue(const TargetLowering &tli,
Chris Lattnerb606dba2008-04-28 06:44:42 +0000158 const SmallVector<unsigned, 4> &regs,
Duncan Sands83ec4b62008-06-06 12:08:01 +0000159 const SmallVector<MVT, 4> &regvts,
160 const SmallVector<MVT, 4> &valuevts)
Dan Gohman0fe00902008-04-28 18:10:39 +0000161 : TLI(&tli), ValueVTs(valuevts), RegVTs(regvts), Regs(regs) {}
Dan Gohman23ce5022008-04-25 18:27:55 +0000162 RegsForValue(const TargetLowering &tli,
163 unsigned Reg, const Type *Ty) : TLI(&tli) {
164 ComputeValueVTs(tli, Ty, ValueVTs);
165
Dan Gohmanb20d4f82008-04-28 17:42:03 +0000166 for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
Duncan Sands83ec4b62008-06-06 12:08:01 +0000167 MVT ValueVT = ValueVTs[Value];
Dan Gohman23ce5022008-04-25 18:27:55 +0000168 unsigned NumRegs = TLI->getNumRegisters(ValueVT);
Duncan Sands83ec4b62008-06-06 12:08:01 +0000169 MVT RegisterVT = TLI->getRegisterType(ValueVT);
Dan Gohman23ce5022008-04-25 18:27:55 +0000170 for (unsigned i = 0; i != NumRegs; ++i)
171 Regs.push_back(Reg + i);
172 RegVTs.push_back(RegisterVT);
173 Reg += NumRegs;
174 }
Chris Lattner864635a2006-02-22 22:37:12 +0000175 }
176
Chris Lattner41f62592008-04-29 04:29:54 +0000177 /// append - Add the specified values to this one.
178 void append(const RegsForValue &RHS) {
179 TLI = RHS.TLI;
180 ValueVTs.append(RHS.ValueVTs.begin(), RHS.ValueVTs.end());
181 RegVTs.append(RHS.RegVTs.begin(), RHS.RegVTs.end());
182 Regs.append(RHS.Regs.begin(), RHS.Regs.end());
183 }
184
185
Chris Lattner864635a2006-02-22 22:37:12 +0000186 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
Dan Gohman23ce5022008-04-25 18:27:55 +0000187 /// this value and returns the result as a ValueVTs value. This uses
Chris Lattner864635a2006-02-22 22:37:12 +0000188 /// Chain/Flag as the input and updates them for the output Chain/Flag.
Dan Gohmanb6f5b002007-06-28 23:29:44 +0000189 /// If the Flag pointer is NULL, no flag is used.
Chris Lattner864635a2006-02-22 22:37:12 +0000190 SDOperand getCopyFromRegs(SelectionDAG &DAG,
Dan Gohmanb6f5b002007-06-28 23:29:44 +0000191 SDOperand &Chain, SDOperand *Flag) const;
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +0000192
193 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
194 /// specified value into the registers specified by this object. This uses
195 /// Chain/Flag as the input and updates them for the output Chain/Flag.
Dan Gohmanb6f5b002007-06-28 23:29:44 +0000196 /// If the Flag pointer is NULL, no flag is used.
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +0000197 void getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
Dan Gohmanb6f5b002007-06-28 23:29:44 +0000198 SDOperand &Chain, SDOperand *Flag) const;
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +0000199
200 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
201 /// operand list. This adds the code marker and includes the number of
202 /// values added into it.
203 void AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
Chris Lattner9f6637d2006-02-23 20:06:57 +0000204 std::vector<SDOperand> &Ops) const;
Chris Lattner864635a2006-02-22 22:37:12 +0000205 };
206}
Evan Cheng4ef10862006-01-23 07:01:07 +0000207
Chris Lattner1c08c712005-01-07 07:47:53 +0000208namespace llvm {
209 //===--------------------------------------------------------------------===//
Jim Laskey9373beb2006-08-01 19:14:14 +0000210 /// createDefaultScheduler - This creates an instruction scheduler appropriate
211 /// for the target.
212 ScheduleDAG* createDefaultScheduler(SelectionDAGISel *IS,
213 SelectionDAG *DAG,
214 MachineBasicBlock *BB) {
215 TargetLowering &TLI = IS->getTargetLowering();
216
217 if (TLI.getSchedulingPreference() == TargetLowering::SchedulingForLatency) {
218 return createTDListDAGScheduler(IS, DAG, BB);
219 } else {
220 assert(TLI.getSchedulingPreference() ==
221 TargetLowering::SchedulingForRegPressure && "Unknown sched type!");
222 return createBURRListDAGScheduler(IS, DAG, BB);
223 }
224 }
225
226
227 //===--------------------------------------------------------------------===//
Chris Lattner1c08c712005-01-07 07:47:53 +0000228 /// FunctionLoweringInfo - This contains information that is global to a
229 /// function that is used when lowering a region of the function.
Chris Lattnerf26bc8e2005-01-08 19:52:31 +0000230 class FunctionLoweringInfo {
231 public:
Chris Lattner1c08c712005-01-07 07:47:53 +0000232 TargetLowering &TLI;
233 Function &Fn;
234 MachineFunction &MF;
Chris Lattner84bc5422007-12-31 04:13:23 +0000235 MachineRegisterInfo &RegInfo;
Chris Lattner1c08c712005-01-07 07:47:53 +0000236
237 FunctionLoweringInfo(TargetLowering &TLI, Function &Fn,MachineFunction &MF);
238
239 /// MBBMap - A mapping from LLVM basic blocks to their machine code entry.
240 std::map<const BasicBlock*, MachineBasicBlock *> MBBMap;
241
242 /// ValueMap - Since we emit code for the function a basic block at a time,
243 /// we must remember which virtual registers hold the values for
244 /// cross-basic-block values.
Chris Lattner9f24ad72007-02-04 01:35:11 +0000245 DenseMap<const Value*, unsigned> ValueMap;
Chris Lattner1c08c712005-01-07 07:47:53 +0000246
247 /// StaticAllocaMap - Keep track of frame indices for fixed sized allocas in
248 /// the entry block. This allows the allocas to be efficiently referenced
249 /// anywhere in the function.
250 std::map<const AllocaInst*, int> StaticAllocaMap;
251
Duncan Sandsf4070822007-06-15 19:04:19 +0000252#ifndef NDEBUG
253 SmallSet<Instruction*, 8> CatchInfoLost;
254 SmallSet<Instruction*, 8> CatchInfoFound;
255#endif
256
Duncan Sands83ec4b62008-06-06 12:08:01 +0000257 unsigned MakeReg(MVT VT) {
Chris Lattner84bc5422007-12-31 04:13:23 +0000258 return RegInfo.createVirtualRegister(TLI.getRegClassFor(VT));
Chris Lattner1c08c712005-01-07 07:47:53 +0000259 }
Chris Lattner571e4342006-10-27 21:36:01 +0000260
261 /// isExportedInst - Return true if the specified value is an instruction
262 /// exported from its block.
263 bool isExportedInst(const Value *V) {
264 return ValueMap.count(V);
265 }
Misha Brukmanedf128a2005-04-21 22:36:52 +0000266
Chris Lattner3c384492006-03-16 19:51:18 +0000267 unsigned CreateRegForValue(const Value *V);
268
Chris Lattner1c08c712005-01-07 07:47:53 +0000269 unsigned InitializeRegForValue(const Value *V) {
270 unsigned &R = ValueMap[V];
271 assert(R == 0 && "Already initialized this value register!");
272 return R = CreateRegForValue(V);
273 }
274 };
275}
276
Duncan Sandscf26d7c2007-07-04 20:52:51 +0000277/// isSelector - Return true if this instruction is a call to the
278/// eh.selector intrinsic.
279static bool isSelector(Instruction *I) {
Duncan Sandsf4070822007-06-15 19:04:19 +0000280 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
Anton Korobeynikov8806c7b2007-09-07 11:39:35 +0000281 return (II->getIntrinsicID() == Intrinsic::eh_selector_i32 ||
282 II->getIntrinsicID() == Intrinsic::eh_selector_i64);
Duncan Sandsf4070822007-06-15 19:04:19 +0000283 return false;
284}
285
Chris Lattner1c08c712005-01-07 07:47:53 +0000286/// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by
Nate Begemanf15485a2006-03-27 01:32:24 +0000287/// PHI nodes or outside of the basic block that defines it, or used by a
Andrew Lenharthab0b9492008-02-21 06:45:13 +0000288/// switch or atomic instruction, which may expand to multiple basic blocks.
Chris Lattner1c08c712005-01-07 07:47:53 +0000289static bool isUsedOutsideOfDefiningBlock(Instruction *I) {
290 if (isa<PHINode>(I)) return true;
291 BasicBlock *BB = I->getParent();
292 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; ++UI)
Nate Begemanf15485a2006-03-27 01:32:24 +0000293 if (cast<Instruction>(*UI)->getParent() != BB || isa<PHINode>(*UI) ||
Chris Lattner571e4342006-10-27 21:36:01 +0000294 // FIXME: Remove switchinst special case.
Nate Begemanf15485a2006-03-27 01:32:24 +0000295 isa<SwitchInst>(*UI))
Chris Lattner1c08c712005-01-07 07:47:53 +0000296 return true;
297 return false;
298}
299
Chris Lattnerbf209482005-10-30 19:42:35 +0000300/// isOnlyUsedInEntryBlock - If the specified argument is only used in the
Nate Begemanf15485a2006-03-27 01:32:24 +0000301/// entry block, return true. This includes arguments used by switches, since
302/// the switch may expand into multiple basic blocks.
Chris Lattnerbf209482005-10-30 19:42:35 +0000303static bool isOnlyUsedInEntryBlock(Argument *A) {
304 BasicBlock *Entry = A->getParent()->begin();
305 for (Value::use_iterator UI = A->use_begin(), E = A->use_end(); UI != E; ++UI)
Nate Begemanf15485a2006-03-27 01:32:24 +0000306 if (cast<Instruction>(*UI)->getParent() != Entry || isa<SwitchInst>(*UI))
Chris Lattnerbf209482005-10-30 19:42:35 +0000307 return false; // Use not in entry block.
308 return true;
309}
310
Chris Lattner1c08c712005-01-07 07:47:53 +0000311FunctionLoweringInfo::FunctionLoweringInfo(TargetLowering &tli,
Misha Brukmanedf128a2005-04-21 22:36:52 +0000312 Function &fn, MachineFunction &mf)
Chris Lattner84bc5422007-12-31 04:13:23 +0000313 : TLI(tli), Fn(fn), MF(mf), RegInfo(MF.getRegInfo()) {
Chris Lattner1c08c712005-01-07 07:47:53 +0000314
Chris Lattnerbf209482005-10-30 19:42:35 +0000315 // Create a vreg for each argument register that is not dead and is used
316 // outside of the entry block for the function.
317 for (Function::arg_iterator AI = Fn.arg_begin(), E = Fn.arg_end();
318 AI != E; ++AI)
319 if (!isOnlyUsedInEntryBlock(AI))
320 InitializeRegForValue(AI);
321
Chris Lattner1c08c712005-01-07 07:47:53 +0000322 // Initialize the mapping of values to registers. This is only set up for
323 // instruction values that are used outside of the block that defines
324 // them.
Jeff Cohen2aeaf4e2005-10-01 03:57:14 +0000325 Function::iterator BB = Fn.begin(), EB = Fn.end();
Chris Lattner1c08c712005-01-07 07:47:53 +0000326 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
327 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
Reid Spencerb83eb642006-10-20 07:07:24 +0000328 if (ConstantInt *CUI = dyn_cast<ConstantInt>(AI->getArraySize())) {
Chris Lattner1c08c712005-01-07 07:47:53 +0000329 const Type *Ty = AI->getAllocatedType();
Duncan Sands514ab342007-11-01 20:53:16 +0000330 uint64_t TySize = TLI.getTargetData()->getABITypeSize(Ty);
Nate Begemanae232e72005-11-06 09:00:38 +0000331 unsigned Align =
Chris Lattnerd2b7cec2007-02-14 05:52:17 +0000332 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
Nate Begemanae232e72005-11-06 09:00:38 +0000333 AI->getAlignment());
Chris Lattnera8217e32005-05-13 23:14:17 +0000334
Reid Spencerb83eb642006-10-20 07:07:24 +0000335 TySize *= CUI->getZExtValue(); // Get total allocated size.
Chris Lattnerd222f6a2005-10-18 22:14:06 +0000336 if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
Chris Lattner1c08c712005-01-07 07:47:53 +0000337 StaticAllocaMap[AI] =
Chris Lattner6266c182007-04-25 04:08:28 +0000338 MF.getFrameInfo()->CreateStackObject(TySize, Align);
Chris Lattner1c08c712005-01-07 07:47:53 +0000339 }
340
Jeff Cohen2aeaf4e2005-10-01 03:57:14 +0000341 for (; BB != EB; ++BB)
342 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
Chris Lattner1c08c712005-01-07 07:47:53 +0000343 if (!I->use_empty() && isUsedOutsideOfDefiningBlock(I))
344 if (!isa<AllocaInst>(I) ||
345 !StaticAllocaMap.count(cast<AllocaInst>(I)))
346 InitializeRegForValue(I);
347
348 // Create an initial MachineBasicBlock for each LLVM BasicBlock in F. This
349 // also creates the initial PHI MachineInstrs, though none of the input
350 // operands are populated.
Jeff Cohen2aeaf4e2005-10-01 03:57:14 +0000351 for (BB = Fn.begin(), EB = Fn.end(); BB != EB; ++BB) {
Chris Lattner1c08c712005-01-07 07:47:53 +0000352 MachineBasicBlock *MBB = new MachineBasicBlock(BB);
353 MBBMap[BB] = MBB;
354 MF.getBasicBlockList().push_back(MBB);
355
356 // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
357 // appropriate.
358 PHINode *PN;
Chris Lattner8c494ab2006-10-27 23:50:33 +0000359 for (BasicBlock::iterator I = BB->begin();(PN = dyn_cast<PHINode>(I)); ++I){
360 if (PN->use_empty()) continue;
361
Duncan Sands83ec4b62008-06-06 12:08:01 +0000362 MVT VT = TLI.getValueType(PN->getType());
Dan Gohman7f321562007-06-25 16:23:39 +0000363 unsigned NumRegisters = TLI.getNumRegisters(VT);
Chris Lattner8c494ab2006-10-27 23:50:33 +0000364 unsigned PHIReg = ValueMap[PN];
365 assert(PHIReg && "PHI node does not have an assigned virtual register!");
Evan Chengc0f64ff2006-11-27 23:37:22 +0000366 const TargetInstrInfo *TII = TLI.getTargetMachine().getInstrInfo();
Dan Gohmanb9f10192007-06-21 14:42:22 +0000367 for (unsigned i = 0; i != NumRegisters; ++i)
Evan Chengc0f64ff2006-11-27 23:37:22 +0000368 BuildMI(MBB, TII->get(TargetInstrInfo::PHI), PHIReg+i);
Chris Lattner8c494ab2006-10-27 23:50:33 +0000369 }
Chris Lattner1c08c712005-01-07 07:47:53 +0000370 }
371}
372
Chris Lattner3c384492006-03-16 19:51:18 +0000373/// CreateRegForValue - Allocate the appropriate number of virtual registers of
374/// the correctly promoted or expanded types. Assign these registers
375/// consecutive vreg numbers and return the first assigned number.
Dan Gohman10a6b7a2008-04-28 18:19:43 +0000376///
377/// In the case that the given value has struct or array type, this function
378/// will assign registers for each member or element.
379///
Chris Lattner3c384492006-03-16 19:51:18 +0000380unsigned FunctionLoweringInfo::CreateRegForValue(const Value *V) {
Duncan Sands83ec4b62008-06-06 12:08:01 +0000381 SmallVector<MVT, 4> ValueVTs;
Chris Lattnerb606dba2008-04-28 06:44:42 +0000382 ComputeValueVTs(TLI, V->getType(), ValueVTs);
Bill Wendling95b39552007-04-24 21:13:23 +0000383
Dan Gohman23ce5022008-04-25 18:27:55 +0000384 unsigned FirstReg = 0;
Dan Gohmanb20d4f82008-04-28 17:42:03 +0000385 for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
Duncan Sands83ec4b62008-06-06 12:08:01 +0000386 MVT ValueVT = ValueVTs[Value];
387 MVT RegisterVT = TLI.getRegisterType(ValueVT);
Dan Gohman8c8c5fc2007-06-27 14:34:07 +0000388
Chris Lattnerb606dba2008-04-28 06:44:42 +0000389 unsigned NumRegs = TLI.getNumRegisters(ValueVT);
Dan Gohman23ce5022008-04-25 18:27:55 +0000390 for (unsigned i = 0; i != NumRegs; ++i) {
391 unsigned R = MakeReg(RegisterVT);
392 if (!FirstReg) FirstReg = R;
393 }
394 }
395 return FirstReg;
Chris Lattner3c384492006-03-16 19:51:18 +0000396}
Chris Lattner1c08c712005-01-07 07:47:53 +0000397
398//===----------------------------------------------------------------------===//
399/// SelectionDAGLowering - This is the common target-independent lowering
400/// implementation that is parameterized by a TargetLowering object.
401/// Also, targets can overload any lowering method.
402///
403namespace llvm {
404class SelectionDAGLowering {
405 MachineBasicBlock *CurMBB;
406
Chris Lattner0da331f2007-02-04 01:31:47 +0000407 DenseMap<const Value*, SDOperand> NodeMap;
Chris Lattner1c08c712005-01-07 07:47:53 +0000408
Chris Lattnerd3948112005-01-17 22:19:26 +0000409 /// PendingLoads - Loads are not emitted to the program immediately. We bunch
410 /// them up and then emit token factor nodes when possible. This allows us to
411 /// get simple disambiguation between loads without worrying about alias
412 /// analysis.
413 std::vector<SDOperand> PendingLoads;
414
Dan Gohman86e1ebf2008-03-27 19:56:19 +0000415 /// PendingExports - CopyToReg nodes that copy values to virtual registers
416 /// for export to other blocks need to be emitted before any terminator
417 /// instruction, but they have no other ordering requirements. We bunch them
418 /// up and the emit a single tokenfactor for them just before terminator
419 /// instructions.
420 std::vector<SDOperand> PendingExports;
421
Anton Korobeynikov5502bf62007-04-04 21:14:49 +0000422 /// Case - A struct to record the Value for a switch case, and the
423 /// case's target basic block.
424 struct Case {
425 Constant* Low;
426 Constant* High;
427 MachineBasicBlock* BB;
428
429 Case() : Low(0), High(0), BB(0) { }
430 Case(Constant* low, Constant* high, MachineBasicBlock* bb) :
431 Low(low), High(high), BB(bb) { }
432 uint64_t size() const {
433 uint64_t rHigh = cast<ConstantInt>(High)->getSExtValue();
434 uint64_t rLow = cast<ConstantInt>(Low)->getSExtValue();
435 return (rHigh - rLow + 1ULL);
436 }
437 };
438
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000439 struct CaseBits {
440 uint64_t Mask;
441 MachineBasicBlock* BB;
442 unsigned Bits;
443
444 CaseBits(uint64_t mask, MachineBasicBlock* bb, unsigned bits):
445 Mask(mask), BB(bb), Bits(bits) { }
446 };
447
Anton Korobeynikov5502bf62007-04-04 21:14:49 +0000448 typedef std::vector<Case> CaseVector;
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000449 typedef std::vector<CaseBits> CaseBitsVector;
Anton Korobeynikov5502bf62007-04-04 21:14:49 +0000450 typedef CaseVector::iterator CaseItr;
451 typedef std::pair<CaseItr, CaseItr> CaseRange;
Nate Begemanf15485a2006-03-27 01:32:24 +0000452
453 /// CaseRec - A struct with ctor used in lowering switches to a binary tree
454 /// of conditional branches.
455 struct CaseRec {
456 CaseRec(MachineBasicBlock *bb, Constant *lt, Constant *ge, CaseRange r) :
457 CaseBB(bb), LT(lt), GE(ge), Range(r) {}
458
459 /// CaseBB - The MBB in which to emit the compare and branch
460 MachineBasicBlock *CaseBB;
461 /// LT, GE - If nonzero, we know the current case value must be less-than or
462 /// greater-than-or-equal-to these Constants.
463 Constant *LT;
464 Constant *GE;
465 /// Range - A pair of iterators representing the range of case values to be
466 /// processed at this point in the binary search tree.
467 CaseRange Range;
468 };
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +0000469
470 typedef std::vector<CaseRec> CaseRecVector;
Anton Korobeynikov5502bf62007-04-04 21:14:49 +0000471
472 /// The comparison function for sorting the switch case values in the vector.
473 /// WARNING: Case ranges should be disjoint!
Nate Begemanf15485a2006-03-27 01:32:24 +0000474 struct CaseCmp {
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000475 bool operator () (const Case& C1, const Case& C2) {
Anton Korobeynikov5502bf62007-04-04 21:14:49 +0000476 assert(isa<ConstantInt>(C1.Low) && isa<ConstantInt>(C2.High));
477 const ConstantInt* CI1 = cast<const ConstantInt>(C1.Low);
478 const ConstantInt* CI2 = cast<const ConstantInt>(C2.High);
479 return CI1->getValue().slt(CI2->getValue());
Nate Begemanf15485a2006-03-27 01:32:24 +0000480 }
481 };
Anton Korobeynikov5502bf62007-04-04 21:14:49 +0000482
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000483 struct CaseBitsCmp {
484 bool operator () (const CaseBits& C1, const CaseBits& C2) {
485 return C1.Bits > C2.Bits;
486 }
487 };
488
Anton Korobeynikov5502bf62007-04-04 21:14:49 +0000489 unsigned Clusterify(CaseVector& Cases, const SwitchInst &SI);
Nate Begemanf15485a2006-03-27 01:32:24 +0000490
Chris Lattner1c08c712005-01-07 07:47:53 +0000491public:
492 // TLI - This is information that describes the available target features we
493 // need for lowering. This indicates when operations are unavailable,
494 // implemented with a libcall, etc.
495 TargetLowering &TLI;
496 SelectionDAG &DAG;
Owen Andersona69571c2006-05-03 01:29:57 +0000497 const TargetData *TD;
Dan Gohman5f43f922007-08-27 16:26:13 +0000498 AliasAnalysis &AA;
Chris Lattner1c08c712005-01-07 07:47:53 +0000499
Nate Begemanf15485a2006-03-27 01:32:24 +0000500 /// SwitchCases - Vector of CaseBlock structures used to communicate
501 /// SwitchInst code generation information.
502 std::vector<SelectionDAGISel::CaseBlock> SwitchCases;
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +0000503 /// JTCases - Vector of JumpTable structures used to communicate
504 /// SwitchInst code generation information.
505 std::vector<SelectionDAGISel::JumpTableBlock> JTCases;
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000506 std::vector<SelectionDAGISel::BitTestBlock> BitTestCases;
Nate Begemanf15485a2006-03-27 01:32:24 +0000507
Chris Lattner1c08c712005-01-07 07:47:53 +0000508 /// FuncInfo - Information about the function as a whole.
509 ///
510 FunctionLoweringInfo &FuncInfo;
Gordon Henriksence224772008-01-07 01:30:38 +0000511
512 /// GCI - Garbage collection metadata for the function.
513 CollectorMetadata *GCI;
Chris Lattner1c08c712005-01-07 07:47:53 +0000514
515 SelectionDAGLowering(SelectionDAG &dag, TargetLowering &tli,
Dan Gohman5f43f922007-08-27 16:26:13 +0000516 AliasAnalysis &aa,
Gordon Henriksence224772008-01-07 01:30:38 +0000517 FunctionLoweringInfo &funcinfo,
518 CollectorMetadata *gci)
Dan Gohman5f43f922007-08-27 16:26:13 +0000519 : TLI(tli), DAG(dag), TD(DAG.getTarget().getTargetData()), AA(aa),
Gordon Henriksence224772008-01-07 01:30:38 +0000520 FuncInfo(funcinfo), GCI(gci) {
Chris Lattner1c08c712005-01-07 07:47:53 +0000521 }
522
Dan Gohman86e1ebf2008-03-27 19:56:19 +0000523 /// getRoot - Return the current virtual root of the Selection DAG,
524 /// flushing any PendingLoad items. This must be done before emitting
525 /// a store or any other node that may need to be ordered after any
526 /// prior load instructions.
Chris Lattnera651cf62005-01-17 19:43:36 +0000527 ///
528 SDOperand getRoot() {
Chris Lattnerd3948112005-01-17 22:19:26 +0000529 if (PendingLoads.empty())
530 return DAG.getRoot();
Misha Brukmanedf128a2005-04-21 22:36:52 +0000531
Chris Lattnerd3948112005-01-17 22:19:26 +0000532 if (PendingLoads.size() == 1) {
533 SDOperand Root = PendingLoads[0];
534 DAG.setRoot(Root);
535 PendingLoads.clear();
536 return Root;
537 }
538
539 // Otherwise, we have to make a token factor node.
Chris Lattnerbd564bf2006-08-08 02:23:42 +0000540 SDOperand Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
541 &PendingLoads[0], PendingLoads.size());
Chris Lattnerd3948112005-01-17 22:19:26 +0000542 PendingLoads.clear();
543 DAG.setRoot(Root);
544 return Root;
Chris Lattnera651cf62005-01-17 19:43:36 +0000545 }
546
Dan Gohman86e1ebf2008-03-27 19:56:19 +0000547 /// getControlRoot - Similar to getRoot, but instead of flushing all the
548 /// PendingLoad items, flush all the PendingExports items. It is necessary
549 /// to do this before emitting a terminator instruction.
550 ///
551 SDOperand getControlRoot() {
552 SDOperand Root = DAG.getRoot();
553
554 if (PendingExports.empty())
555 return Root;
556
557 // Turn all of the CopyToReg chains into one factored node.
558 if (Root.getOpcode() != ISD::EntryToken) {
559 unsigned i = 0, e = PendingExports.size();
560 for (; i != e; ++i) {
561 assert(PendingExports[i].Val->getNumOperands() > 1);
562 if (PendingExports[i].Val->getOperand(0) == Root)
563 break; // Don't add the root if we already indirectly depend on it.
564 }
565
566 if (i == e)
567 PendingExports.push_back(Root);
568 }
569
570 Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
571 &PendingExports[0],
572 PendingExports.size());
573 PendingExports.clear();
574 DAG.setRoot(Root);
575 return Root;
576 }
577
578 void CopyValueToVirtualRegister(Value *V, unsigned Reg);
Chris Lattner571e4342006-10-27 21:36:01 +0000579
Chris Lattner1c08c712005-01-07 07:47:53 +0000580 void visit(Instruction &I) { visit(I.getOpcode(), I); }
581
582 void visit(unsigned Opcode, User &I) {
Chris Lattner1e7aa5c2006-11-10 04:41:34 +0000583 // Note: this doesn't use InstVisitor, because it has to work with
584 // ConstantExpr's in addition to instructions.
Chris Lattner1c08c712005-01-07 07:47:53 +0000585 switch (Opcode) {
586 default: assert(0 && "Unknown instruction type encountered!");
587 abort();
588 // Build the switch statement using the Instruction.def file.
589#define HANDLE_INST(NUM, OPCODE, CLASS) \
590 case Instruction::OPCODE:return visit##OPCODE((CLASS&)I);
591#include "llvm/Instruction.def"
592 }
593 }
594
595 void setCurrentBasicBlock(MachineBasicBlock *MBB) { CurMBB = MBB; }
596
Chris Lattner28b5b1c2006-03-15 22:19:46 +0000597 SDOperand getLoadFrom(const Type *Ty, SDOperand Ptr,
Evan Cheng466685d2006-10-09 20:57:25 +0000598 const Value *SV, SDOperand Root,
Christopher Lamb95c218a2007-04-22 23:15:30 +0000599 bool isVolatile, unsigned Alignment);
Chris Lattner1c08c712005-01-07 07:47:53 +0000600
Chris Lattner199862b2006-03-16 19:57:50 +0000601 SDOperand getValue(const Value *V);
Chris Lattner1c08c712005-01-07 07:47:53 +0000602
Chris Lattner0da331f2007-02-04 01:31:47 +0000603 void setValue(const Value *V, SDOperand NewN) {
Chris Lattner1c08c712005-01-07 07:47:53 +0000604 SDOperand &N = NodeMap[V];
605 assert(N.Val == 0 && "Already set a value for this node!");
Chris Lattner0da331f2007-02-04 01:31:47 +0000606 N = NewN;
Chris Lattner1c08c712005-01-07 07:47:53 +0000607 }
Chris Lattner4e4b5762006-02-01 18:59:47 +0000608
Evan Cheng5c807602008-02-26 02:33:44 +0000609 void GetRegistersForValue(SDISelAsmOperandInfo &OpInfo, bool HasEarlyClobber,
Chris Lattnere7cf56a2007-04-30 21:11:17 +0000610 std::set<unsigned> &OutputRegs,
611 std::set<unsigned> &InputRegs);
Nate Begemanf15485a2006-03-27 01:32:24 +0000612
Chris Lattner571e4342006-10-27 21:36:01 +0000613 void FindMergedConditions(Value *Cond, MachineBasicBlock *TBB,
614 MachineBasicBlock *FBB, MachineBasicBlock *CurBB,
615 unsigned Opc);
Chris Lattner8c494ab2006-10-27 23:50:33 +0000616 bool isExportableFromCurrentBlock(Value *V, const BasicBlock *FromBB);
Chris Lattner571e4342006-10-27 21:36:01 +0000617 void ExportFromCurrentBlock(Value *V);
Duncan Sands6f74b482007-12-19 09:48:52 +0000618 void LowerCallTo(CallSite CS, SDOperand Callee, bool IsTailCall,
Anton Korobeynikov070280e2007-05-23 11:08:31 +0000619 MachineBasicBlock *LandingPad = NULL);
Duncan Sandsdc024672007-11-27 13:23:08 +0000620
Chris Lattner1c08c712005-01-07 07:47:53 +0000621 // Terminator instructions.
622 void visitRet(ReturnInst &I);
623 void visitBr(BranchInst &I);
Nate Begemanf15485a2006-03-27 01:32:24 +0000624 void visitSwitch(SwitchInst &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000625 void visitUnreachable(UnreachableInst &I) { /* noop */ }
626
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +0000627 // Helpers for visitSwitch
Anton Korobeynikovdd433212007-03-27 12:05:48 +0000628 bool handleSmallSwitchRange(CaseRec& CR,
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +0000629 CaseRecVector& WorkList,
630 Value* SV,
631 MachineBasicBlock* Default);
Anton Korobeynikovdd433212007-03-27 12:05:48 +0000632 bool handleJTSwitchCase(CaseRec& CR,
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +0000633 CaseRecVector& WorkList,
634 Value* SV,
635 MachineBasicBlock* Default);
Anton Korobeynikovdd433212007-03-27 12:05:48 +0000636 bool handleBTSplitSwitchCase(CaseRec& CR,
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +0000637 CaseRecVector& WorkList,
638 Value* SV,
639 MachineBasicBlock* Default);
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000640 bool handleBitTestsSwitchCase(CaseRec& CR,
641 CaseRecVector& WorkList,
642 Value* SV,
643 MachineBasicBlock* Default);
Nate Begemanf15485a2006-03-27 01:32:24 +0000644 void visitSwitchCase(SelectionDAGISel::CaseBlock &CB);
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000645 void visitBitTestHeader(SelectionDAGISel::BitTestBlock &B);
646 void visitBitTestCase(MachineBasicBlock* NextMBB,
647 unsigned Reg,
648 SelectionDAGISel::BitTestCase &B);
Nate Begeman37efe672006-04-22 18:53:45 +0000649 void visitJumpTable(SelectionDAGISel::JumpTable &JT);
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +0000650 void visitJumpTableHeader(SelectionDAGISel::JumpTable &JT,
651 SelectionDAGISel::JumpTableHeader &JTH);
Nate Begemanf15485a2006-03-27 01:32:24 +0000652
Chris Lattner1c08c712005-01-07 07:47:53 +0000653 // These all get lowered before this pass.
Jim Laskeyb180aa12007-02-21 22:53:45 +0000654 void visitInvoke(InvokeInst &I);
655 void visitUnwind(UnwindInst &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000656
Dan Gohman7f321562007-06-25 16:23:39 +0000657 void visitBinary(User &I, unsigned OpCode);
Nate Begemane21ea612005-11-18 07:42:56 +0000658 void visitShift(User &I, unsigned Opcode);
Nate Begeman5fbb5d22005-11-19 00:36:38 +0000659 void visitAdd(User &I) {
Dan Gohman7f321562007-06-25 16:23:39 +0000660 if (I.getType()->isFPOrFPVector())
661 visitBinary(I, ISD::FADD);
Reid Spencer1628cec2006-10-26 06:15:43 +0000662 else
Dan Gohman7f321562007-06-25 16:23:39 +0000663 visitBinary(I, ISD::ADD);
Chris Lattner01b3d732005-09-28 22:28:18 +0000664 }
Chris Lattnerb9fccc42005-04-02 05:04:50 +0000665 void visitSub(User &I);
Reid Spencer1628cec2006-10-26 06:15:43 +0000666 void visitMul(User &I) {
Dan Gohman7f321562007-06-25 16:23:39 +0000667 if (I.getType()->isFPOrFPVector())
668 visitBinary(I, ISD::FMUL);
Reid Spencer1628cec2006-10-26 06:15:43 +0000669 else
Dan Gohman7f321562007-06-25 16:23:39 +0000670 visitBinary(I, ISD::MUL);
Chris Lattner01b3d732005-09-28 22:28:18 +0000671 }
Dan Gohman7f321562007-06-25 16:23:39 +0000672 void visitURem(User &I) { visitBinary(I, ISD::UREM); }
673 void visitSRem(User &I) { visitBinary(I, ISD::SREM); }
674 void visitFRem(User &I) { visitBinary(I, ISD::FREM); }
675 void visitUDiv(User &I) { visitBinary(I, ISD::UDIV); }
676 void visitSDiv(User &I) { visitBinary(I, ISD::SDIV); }
677 void visitFDiv(User &I) { visitBinary(I, ISD::FDIV); }
678 void visitAnd (User &I) { visitBinary(I, ISD::AND); }
679 void visitOr (User &I) { visitBinary(I, ISD::OR); }
680 void visitXor (User &I) { visitBinary(I, ISD::XOR); }
Reid Spencer24d6da52007-01-21 00:29:26 +0000681 void visitShl (User &I) { visitShift(I, ISD::SHL); }
Reid Spencer3822ff52006-11-08 06:47:33 +0000682 void visitLShr(User &I) { visitShift(I, ISD::SRL); }
683 void visitAShr(User &I) { visitShift(I, ISD::SRA); }
Reid Spencer45fb3f32006-11-20 01:22:35 +0000684 void visitICmp(User &I);
685 void visitFCmp(User &I);
Nate Begemanb43e9c12008-05-12 19:40:03 +0000686 void visitVICmp(User &I);
687 void visitVFCmp(User &I);
Reid Spencer3da59db2006-11-27 01:05:10 +0000688 // Visit the conversion instructions
689 void visitTrunc(User &I);
690 void visitZExt(User &I);
691 void visitSExt(User &I);
692 void visitFPTrunc(User &I);
693 void visitFPExt(User &I);
694 void visitFPToUI(User &I);
695 void visitFPToSI(User &I);
696 void visitUIToFP(User &I);
697 void visitSIToFP(User &I);
698 void visitPtrToInt(User &I);
699 void visitIntToPtr(User &I);
700 void visitBitCast(User &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000701
Chris Lattner2bbd8102006-03-29 00:11:43 +0000702 void visitExtractElement(User &I);
703 void visitInsertElement(User &I);
Chris Lattner3e104b12006-04-08 04:15:24 +0000704 void visitShuffleVector(User &I);
Chris Lattnerc7029802006-03-18 01:44:44 +0000705
Dan Gohman041e2eb2008-05-15 19:50:34 +0000706 void visitExtractValue(User &I);
707 void visitInsertValue(User &I);
708
Chris Lattner1c08c712005-01-07 07:47:53 +0000709 void visitGetElementPtr(User &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000710 void visitSelect(User &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000711
712 void visitMalloc(MallocInst &I);
713 void visitFree(FreeInst &I);
714 void visitAlloca(AllocaInst &I);
715 void visitLoad(LoadInst &I);
716 void visitStore(StoreInst &I);
717 void visitPHI(PHINode &I) { } // PHI nodes are handled specially.
718 void visitCall(CallInst &I);
Duncan Sandsfd7b3262007-12-17 18:08:19 +0000719 void visitInlineAsm(CallSite CS);
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +0000720 const char *visitIntrinsicCall(CallInst &I, unsigned Intrinsic);
Chris Lattner0eade312006-03-24 02:22:33 +0000721 void visitTargetIntrinsic(CallInst &I, unsigned Intrinsic);
Chris Lattner1c08c712005-01-07 07:47:53 +0000722
Chris Lattner1c08c712005-01-07 07:47:53 +0000723 void visitVAStart(CallInst &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000724 void visitVAArg(VAArgInst &I);
725 void visitVAEnd(CallInst &I);
726 void visitVACopy(CallInst &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000727
Dan Gohmanef5d1942008-03-11 21:11:25 +0000728 void visitGetResult(GetResultInst &I);
Devang Patel40a04212008-02-19 22:15:16 +0000729
Chris Lattner1c08c712005-01-07 07:47:53 +0000730 void visitUserOp1(Instruction &I) {
731 assert(0 && "UserOp1 should not exist at instruction selection time!");
732 abort();
733 }
734 void visitUserOp2(Instruction &I) {
735 assert(0 && "UserOp2 should not exist at instruction selection time!");
736 abort();
737 }
Mon P Wang63307c32008-05-05 19:05:59 +0000738
739private:
740 inline const char *implVisitBinaryAtomic(CallInst& I, ISD::NodeType Op);
741
Chris Lattner1c08c712005-01-07 07:47:53 +0000742};
743} // end namespace llvm
744
Dan Gohman6183f782007-07-05 20:12:34 +0000745
Duncan Sandsb988bac2008-02-11 20:58:28 +0000746/// getCopyFromParts - Create a value that contains the specified legal parts
747/// combined into the value they represent. If the parts combine to a type
748/// larger then ValueVT then AssertOp can be used to specify whether the extra
749/// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
Chris Lattner4468c1f2008-03-09 09:38:46 +0000750/// (ISD::AssertSext).
Dan Gohman6183f782007-07-05 20:12:34 +0000751static SDOperand getCopyFromParts(SelectionDAG &DAG,
752 const SDOperand *Parts,
753 unsigned NumParts,
Duncan Sands83ec4b62008-06-06 12:08:01 +0000754 MVT PartVT,
755 MVT ValueVT,
Chris Lattner4468c1f2008-03-09 09:38:46 +0000756 ISD::NodeType AssertOp = ISD::DELETED_NODE) {
Duncan Sands014e04a2008-02-12 20:46:31 +0000757 assert(NumParts > 0 && "No parts to assemble!");
758 TargetLowering &TLI = DAG.getTargetLoweringInfo();
759 SDOperand Val = Parts[0];
Dan Gohman6183f782007-07-05 20:12:34 +0000760
Duncan Sands014e04a2008-02-12 20:46:31 +0000761 if (NumParts > 1) {
762 // Assemble the value from multiple parts.
Duncan Sands83ec4b62008-06-06 12:08:01 +0000763 if (!ValueVT.isVector()) {
764 unsigned PartBits = PartVT.getSizeInBits();
765 unsigned ValueBits = ValueVT.getSizeInBits();
Dan Gohman6183f782007-07-05 20:12:34 +0000766
Duncan Sands014e04a2008-02-12 20:46:31 +0000767 // Assemble the power of 2 part.
768 unsigned RoundParts = NumParts & (NumParts - 1) ?
769 1 << Log2_32(NumParts) : NumParts;
770 unsigned RoundBits = PartBits * RoundParts;
Duncan Sands83ec4b62008-06-06 12:08:01 +0000771 MVT RoundVT = RoundBits == ValueBits ?
772 ValueVT : MVT::getIntegerVT(RoundBits);
Duncan Sands014e04a2008-02-12 20:46:31 +0000773 SDOperand Lo, Hi;
774
775 if (RoundParts > 2) {
Duncan Sands83ec4b62008-06-06 12:08:01 +0000776 MVT HalfVT = MVT::getIntegerVT(RoundBits/2);
Duncan Sands014e04a2008-02-12 20:46:31 +0000777 Lo = getCopyFromParts(DAG, Parts, RoundParts/2, PartVT, HalfVT);
778 Hi = getCopyFromParts(DAG, Parts+RoundParts/2, RoundParts/2,
779 PartVT, HalfVT);
Dan Gohman6183f782007-07-05 20:12:34 +0000780 } else {
Duncan Sands014e04a2008-02-12 20:46:31 +0000781 Lo = Parts[0];
782 Hi = Parts[1];
Dan Gohman6183f782007-07-05 20:12:34 +0000783 }
Duncan Sands014e04a2008-02-12 20:46:31 +0000784 if (TLI.isBigEndian())
785 std::swap(Lo, Hi);
786 Val = DAG.getNode(ISD::BUILD_PAIR, RoundVT, Lo, Hi);
787
788 if (RoundParts < NumParts) {
789 // Assemble the trailing non-power-of-2 part.
790 unsigned OddParts = NumParts - RoundParts;
Duncan Sands83ec4b62008-06-06 12:08:01 +0000791 MVT OddVT = MVT::getIntegerVT(OddParts * PartBits);
Duncan Sands014e04a2008-02-12 20:46:31 +0000792 Hi = getCopyFromParts(DAG, Parts+RoundParts, OddParts, PartVT, OddVT);
793
794 // Combine the round and odd parts.
795 Lo = Val;
796 if (TLI.isBigEndian())
797 std::swap(Lo, Hi);
Duncan Sands83ec4b62008-06-06 12:08:01 +0000798 MVT TotalVT = MVT::getIntegerVT(NumParts * PartBits);
Duncan Sands014e04a2008-02-12 20:46:31 +0000799 Hi = DAG.getNode(ISD::ANY_EXTEND, TotalVT, Hi);
800 Hi = DAG.getNode(ISD::SHL, TotalVT, Hi,
Duncan Sands83ec4b62008-06-06 12:08:01 +0000801 DAG.getConstant(Lo.getValueType().getSizeInBits(),
Duncan Sands014e04a2008-02-12 20:46:31 +0000802 TLI.getShiftAmountTy()));
803 Lo = DAG.getNode(ISD::ZERO_EXTEND, TotalVT, Lo);
804 Val = DAG.getNode(ISD::OR, TotalVT, Lo, Hi);
805 }
806 } else {
807 // Handle a multi-element vector.
Duncan Sands83ec4b62008-06-06 12:08:01 +0000808 MVT IntermediateVT, RegisterVT;
Duncan Sands014e04a2008-02-12 20:46:31 +0000809 unsigned NumIntermediates;
810 unsigned NumRegs =
811 TLI.getVectorTypeBreakdown(ValueVT, IntermediateVT, NumIntermediates,
812 RegisterVT);
Duncan Sands014e04a2008-02-12 20:46:31 +0000813 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
Evan Cheng35213342008-05-14 20:29:30 +0000814 NumParts = NumRegs; // Silence a compiler warning.
Duncan Sands014e04a2008-02-12 20:46:31 +0000815 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
816 assert(RegisterVT == Parts[0].getValueType() &&
817 "Part type doesn't match part!");
818
819 // Assemble the parts into intermediate operands.
820 SmallVector<SDOperand, 8> Ops(NumIntermediates);
821 if (NumIntermediates == NumParts) {
822 // If the register was not expanded, truncate or copy the value,
823 // as appropriate.
824 for (unsigned i = 0; i != NumParts; ++i)
825 Ops[i] = getCopyFromParts(DAG, &Parts[i], 1,
826 PartVT, IntermediateVT);
827 } else if (NumParts > 0) {
828 // If the intermediate type was expanded, build the intermediate operands
829 // from the parts.
830 assert(NumParts % NumIntermediates == 0 &&
831 "Must expand into a divisible number of parts!");
832 unsigned Factor = NumParts / NumIntermediates;
833 for (unsigned i = 0; i != NumIntermediates; ++i)
834 Ops[i] = getCopyFromParts(DAG, &Parts[i * Factor], Factor,
835 PartVT, IntermediateVT);
836 }
837
838 // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the intermediate
839 // operands.
Duncan Sands83ec4b62008-06-06 12:08:01 +0000840 Val = DAG.getNode(IntermediateVT.isVector() ?
Duncan Sands014e04a2008-02-12 20:46:31 +0000841 ISD::CONCAT_VECTORS : ISD::BUILD_VECTOR,
842 ValueVT, &Ops[0], NumIntermediates);
Dan Gohman6183f782007-07-05 20:12:34 +0000843 }
Dan Gohman6183f782007-07-05 20:12:34 +0000844 }
845
Duncan Sands014e04a2008-02-12 20:46:31 +0000846 // There is now one part, held in Val. Correct it to match ValueVT.
847 PartVT = Val.getValueType();
Dan Gohman6183f782007-07-05 20:12:34 +0000848
Duncan Sands014e04a2008-02-12 20:46:31 +0000849 if (PartVT == ValueVT)
850 return Val;
Dan Gohman6183f782007-07-05 20:12:34 +0000851
Duncan Sands83ec4b62008-06-06 12:08:01 +0000852 if (PartVT.isVector()) {
853 assert(ValueVT.isVector() && "Unknown vector conversion!");
Duncan Sands014e04a2008-02-12 20:46:31 +0000854 return DAG.getNode(ISD::BIT_CONVERT, ValueVT, Val);
Dan Gohman6183f782007-07-05 20:12:34 +0000855 }
Duncan Sands014e04a2008-02-12 20:46:31 +0000856
Duncan Sands83ec4b62008-06-06 12:08:01 +0000857 if (ValueVT.isVector()) {
858 assert(ValueVT.getVectorElementType() == PartVT &&
859 ValueVT.getVectorNumElements() == 1 &&
Duncan Sands014e04a2008-02-12 20:46:31 +0000860 "Only trivial scalar-to-vector conversions should get here!");
861 return DAG.getNode(ISD::BUILD_VECTOR, ValueVT, Val);
862 }
863
Duncan Sands83ec4b62008-06-06 12:08:01 +0000864 if (PartVT.isInteger() &&
865 ValueVT.isInteger()) {
866 if (ValueVT.getSizeInBits() < PartVT.getSizeInBits()) {
Duncan Sands014e04a2008-02-12 20:46:31 +0000867 // For a truncate, see if we have any information to
868 // indicate whether the truncated bits will always be
869 // zero or sign-extension.
870 if (AssertOp != ISD::DELETED_NODE)
871 Val = DAG.getNode(AssertOp, PartVT, Val,
872 DAG.getValueType(ValueVT));
873 return DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
874 } else {
875 return DAG.getNode(ISD::ANY_EXTEND, ValueVT, Val);
876 }
877 }
878
Duncan Sands83ec4b62008-06-06 12:08:01 +0000879 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
Chris Lattnerd43d85c2008-03-09 07:47:22 +0000880 if (ValueVT < Val.getValueType())
Chris Lattner4468c1f2008-03-09 09:38:46 +0000881 // FP_ROUND's are always exact here.
Chris Lattnerd43d85c2008-03-09 07:47:22 +0000882 return DAG.getNode(ISD::FP_ROUND, ValueVT, Val,
Chris Lattner4468c1f2008-03-09 09:38:46 +0000883 DAG.getIntPtrConstant(1));
Chris Lattnerd43d85c2008-03-09 07:47:22 +0000884 return DAG.getNode(ISD::FP_EXTEND, ValueVT, Val);
885 }
Duncan Sands014e04a2008-02-12 20:46:31 +0000886
Duncan Sands83ec4b62008-06-06 12:08:01 +0000887 if (PartVT.getSizeInBits() == ValueVT.getSizeInBits())
Duncan Sands014e04a2008-02-12 20:46:31 +0000888 return DAG.getNode(ISD::BIT_CONVERT, ValueVT, Val);
889
890 assert(0 && "Unknown mismatch!");
Chris Lattnerd27c9912008-03-30 18:22:13 +0000891 return SDOperand();
Dan Gohman6183f782007-07-05 20:12:34 +0000892}
893
Duncan Sandsb988bac2008-02-11 20:58:28 +0000894/// getCopyToParts - Create a series of nodes that contain the specified value
895/// split into legal parts. If the parts contain more bits than Val, then, for
896/// integers, ExtendKind can be used to specify how to generate the extra bits.
Dan Gohman6183f782007-07-05 20:12:34 +0000897static void getCopyToParts(SelectionDAG &DAG,
898 SDOperand Val,
899 SDOperand *Parts,
900 unsigned NumParts,
Duncan Sands83ec4b62008-06-06 12:08:01 +0000901 MVT PartVT,
Duncan Sandsb988bac2008-02-11 20:58:28 +0000902 ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
Dan Gohman25ac7e82007-08-10 14:59:38 +0000903 TargetLowering &TLI = DAG.getTargetLoweringInfo();
Duncan Sands83ec4b62008-06-06 12:08:01 +0000904 MVT PtrVT = TLI.getPointerTy();
905 MVT ValueVT = Val.getValueType();
906 unsigned PartBits = PartVT.getSizeInBits();
Duncan Sands014e04a2008-02-12 20:46:31 +0000907 assert(TLI.isTypeLegal(PartVT) && "Copying to an illegal type!");
Dan Gohman6183f782007-07-05 20:12:34 +0000908
Duncan Sands014e04a2008-02-12 20:46:31 +0000909 if (!NumParts)
910 return;
911
Duncan Sands83ec4b62008-06-06 12:08:01 +0000912 if (!ValueVT.isVector()) {
Duncan Sands014e04a2008-02-12 20:46:31 +0000913 if (PartVT == ValueVT) {
914 assert(NumParts == 1 && "No-op copy with multiple parts!");
915 Parts[0] = Val;
Dan Gohman6183f782007-07-05 20:12:34 +0000916 return;
917 }
918
Duncan Sands83ec4b62008-06-06 12:08:01 +0000919 if (NumParts * PartBits > ValueVT.getSizeInBits()) {
Duncan Sands014e04a2008-02-12 20:46:31 +0000920 // If the parts cover more bits than the value has, promote the value.
Duncan Sands83ec4b62008-06-06 12:08:01 +0000921 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
Duncan Sands014e04a2008-02-12 20:46:31 +0000922 assert(NumParts == 1 && "Do not know what to promote to!");
Dan Gohman6183f782007-07-05 20:12:34 +0000923 Val = DAG.getNode(ISD::FP_EXTEND, PartVT, Val);
Duncan Sands83ec4b62008-06-06 12:08:01 +0000924 } else if (PartVT.isInteger() && ValueVT.isInteger()) {
925 ValueVT = MVT::getIntegerVT(NumParts * PartBits);
Duncan Sands014e04a2008-02-12 20:46:31 +0000926 Val = DAG.getNode(ExtendKind, ValueVT, Val);
927 } else {
928 assert(0 && "Unknown mismatch!");
929 }
Duncan Sands83ec4b62008-06-06 12:08:01 +0000930 } else if (PartBits == ValueVT.getSizeInBits()) {
Duncan Sands014e04a2008-02-12 20:46:31 +0000931 // Different types of the same size.
932 assert(NumParts == 1 && PartVT != ValueVT);
933 Val = DAG.getNode(ISD::BIT_CONVERT, PartVT, Val);
Duncan Sands83ec4b62008-06-06 12:08:01 +0000934 } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
Duncan Sands014e04a2008-02-12 20:46:31 +0000935 // If the parts cover less bits than value has, truncate the value.
Duncan Sands83ec4b62008-06-06 12:08:01 +0000936 if (PartVT.isInteger() && ValueVT.isInteger()) {
937 ValueVT = MVT::getIntegerVT(NumParts * PartBits);
Duncan Sands014e04a2008-02-12 20:46:31 +0000938 Val = DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
Dan Gohman6183f782007-07-05 20:12:34 +0000939 } else {
940 assert(0 && "Unknown mismatch!");
941 }
942 }
Duncan Sands014e04a2008-02-12 20:46:31 +0000943
944 // The value may have changed - recompute ValueVT.
945 ValueVT = Val.getValueType();
Duncan Sands83ec4b62008-06-06 12:08:01 +0000946 assert(NumParts * PartBits == ValueVT.getSizeInBits() &&
Duncan Sands014e04a2008-02-12 20:46:31 +0000947 "Failed to tile the value with PartVT!");
948
949 if (NumParts == 1) {
950 assert(PartVT == ValueVT && "Type conversion failed!");
951 Parts[0] = Val;
952 return;
953 }
954
955 // Expand the value into multiple parts.
956 if (NumParts & (NumParts - 1)) {
957 // The number of parts is not a power of 2. Split off and copy the tail.
Duncan Sands83ec4b62008-06-06 12:08:01 +0000958 assert(PartVT.isInteger() && ValueVT.isInteger() &&
Duncan Sands014e04a2008-02-12 20:46:31 +0000959 "Do not know what to expand to!");
960 unsigned RoundParts = 1 << Log2_32(NumParts);
961 unsigned RoundBits = RoundParts * PartBits;
962 unsigned OddParts = NumParts - RoundParts;
963 SDOperand OddVal = DAG.getNode(ISD::SRL, ValueVT, Val,
964 DAG.getConstant(RoundBits,
965 TLI.getShiftAmountTy()));
966 getCopyToParts(DAG, OddVal, Parts + RoundParts, OddParts, PartVT);
967 if (TLI.isBigEndian())
968 // The odd parts were reversed by getCopyToParts - unreverse them.
969 std::reverse(Parts + RoundParts, Parts + NumParts);
970 NumParts = RoundParts;
Duncan Sands83ec4b62008-06-06 12:08:01 +0000971 ValueVT = MVT::getIntegerVT(NumParts * PartBits);
Duncan Sands014e04a2008-02-12 20:46:31 +0000972 Val = DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
973 }
974
975 // The number of parts is a power of 2. Repeatedly bisect the value using
976 // EXTRACT_ELEMENT.
Duncan Sands25eb0432008-03-12 20:30:08 +0000977 Parts[0] = DAG.getNode(ISD::BIT_CONVERT,
Duncan Sands83ec4b62008-06-06 12:08:01 +0000978 MVT::getIntegerVT(ValueVT.getSizeInBits()),
Duncan Sands25eb0432008-03-12 20:30:08 +0000979 Val);
Duncan Sands014e04a2008-02-12 20:46:31 +0000980 for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
981 for (unsigned i = 0; i < NumParts; i += StepSize) {
982 unsigned ThisBits = StepSize * PartBits / 2;
Duncan Sands83ec4b62008-06-06 12:08:01 +0000983 MVT ThisVT = MVT::getIntegerVT (ThisBits);
Duncan Sands25eb0432008-03-12 20:30:08 +0000984 SDOperand &Part0 = Parts[i];
985 SDOperand &Part1 = Parts[i+StepSize/2];
Duncan Sands014e04a2008-02-12 20:46:31 +0000986
Duncan Sands25eb0432008-03-12 20:30:08 +0000987 Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, ThisVT, Part0,
988 DAG.getConstant(1, PtrVT));
989 Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, ThisVT, Part0,
990 DAG.getConstant(0, PtrVT));
991
992 if (ThisBits == PartBits && ThisVT != PartVT) {
993 Part0 = DAG.getNode(ISD::BIT_CONVERT, PartVT, Part0);
994 Part1 = DAG.getNode(ISD::BIT_CONVERT, PartVT, Part1);
995 }
Duncan Sands014e04a2008-02-12 20:46:31 +0000996 }
997 }
998
999 if (TLI.isBigEndian())
1000 std::reverse(Parts, Parts + NumParts);
1001
1002 return;
1003 }
1004
1005 // Vector ValueVT.
1006 if (NumParts == 1) {
1007 if (PartVT != ValueVT) {
Duncan Sands83ec4b62008-06-06 12:08:01 +00001008 if (PartVT.isVector()) {
Duncan Sands014e04a2008-02-12 20:46:31 +00001009 Val = DAG.getNode(ISD::BIT_CONVERT, PartVT, Val);
1010 } else {
Duncan Sands83ec4b62008-06-06 12:08:01 +00001011 assert(ValueVT.getVectorElementType() == PartVT &&
1012 ValueVT.getVectorNumElements() == 1 &&
Duncan Sands014e04a2008-02-12 20:46:31 +00001013 "Only trivial vector-to-scalar conversions should get here!");
1014 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, PartVT, Val,
1015 DAG.getConstant(0, PtrVT));
1016 }
1017 }
1018
Dan Gohman6183f782007-07-05 20:12:34 +00001019 Parts[0] = Val;
1020 return;
1021 }
1022
1023 // Handle a multi-element vector.
Duncan Sands83ec4b62008-06-06 12:08:01 +00001024 MVT IntermediateVT, RegisterVT;
Dan Gohman6183f782007-07-05 20:12:34 +00001025 unsigned NumIntermediates;
1026 unsigned NumRegs =
1027 DAG.getTargetLoweringInfo()
1028 .getVectorTypeBreakdown(ValueVT, IntermediateVT, NumIntermediates,
1029 RegisterVT);
Duncan Sands83ec4b62008-06-06 12:08:01 +00001030 unsigned NumElements = ValueVT.getVectorNumElements();
Dan Gohman6183f782007-07-05 20:12:34 +00001031
1032 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
Evan Cheng35213342008-05-14 20:29:30 +00001033 NumParts = NumRegs; // Silence a compiler warning.
Dan Gohman6183f782007-07-05 20:12:34 +00001034 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
1035
1036 // Split the vector into intermediate operands.
1037 SmallVector<SDOperand, 8> Ops(NumIntermediates);
1038 for (unsigned i = 0; i != NumIntermediates; ++i)
Duncan Sands83ec4b62008-06-06 12:08:01 +00001039 if (IntermediateVT.isVector())
Dan Gohman6183f782007-07-05 20:12:34 +00001040 Ops[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR,
1041 IntermediateVT, Val,
1042 DAG.getConstant(i * (NumElements / NumIntermediates),
Dan Gohman25ac7e82007-08-10 14:59:38 +00001043 PtrVT));
Dan Gohman6183f782007-07-05 20:12:34 +00001044 else
1045 Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
1046 IntermediateVT, Val,
Dan Gohman25ac7e82007-08-10 14:59:38 +00001047 DAG.getConstant(i, PtrVT));
Dan Gohman6183f782007-07-05 20:12:34 +00001048
1049 // Split the intermediate operands into legal parts.
1050 if (NumParts == NumIntermediates) {
1051 // If the register was not expanded, promote or copy the value,
1052 // as appropriate.
1053 for (unsigned i = 0; i != NumParts; ++i)
Dan Gohman532dc2e2007-07-09 20:59:04 +00001054 getCopyToParts(DAG, Ops[i], &Parts[i], 1, PartVT);
Dan Gohman6183f782007-07-05 20:12:34 +00001055 } else if (NumParts > 0) {
1056 // If the intermediate type was expanded, split each the value into
1057 // legal parts.
1058 assert(NumParts % NumIntermediates == 0 &&
1059 "Must expand into a divisible number of parts!");
1060 unsigned Factor = NumParts / NumIntermediates;
1061 for (unsigned i = 0; i != NumIntermediates; ++i)
Dan Gohman532dc2e2007-07-09 20:59:04 +00001062 getCopyToParts(DAG, Ops[i], &Parts[i * Factor], Factor, PartVT);
Dan Gohman6183f782007-07-05 20:12:34 +00001063 }
1064}
1065
1066
Chris Lattner199862b2006-03-16 19:57:50 +00001067SDOperand SelectionDAGLowering::getValue(const Value *V) {
1068 SDOperand &N = NodeMap[V];
1069 if (N.Val) return N;
1070
Chris Lattner199862b2006-03-16 19:57:50 +00001071 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V))) {
Duncan Sands83ec4b62008-06-06 12:08:01 +00001072 MVT VT = TLI.getValueType(V->getType(), true);
Chris Lattnerb606dba2008-04-28 06:44:42 +00001073
1074 if (ConstantInt *CI = dyn_cast<ConstantInt>(C))
1075 return N = DAG.getConstant(CI->getValue(), VT);
1076
1077 if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
Chris Lattner199862b2006-03-16 19:57:50 +00001078 return N = DAG.getGlobalAddress(GV, VT);
Chris Lattnerb606dba2008-04-28 06:44:42 +00001079
1080 if (isa<ConstantPointerNull>(C))
Chris Lattner199862b2006-03-16 19:57:50 +00001081 return N = DAG.getConstant(0, TLI.getPointerTy());
Chris Lattnerb606dba2008-04-28 06:44:42 +00001082
1083 if (ConstantFP *CFP = dyn_cast<ConstantFP>(C))
1084 return N = DAG.getConstantFP(CFP->getValueAPF(), VT);
1085
Chris Lattner6833b062008-04-28 07:16:35 +00001086 if (isa<UndefValue>(C) && !isa<VectorType>(V->getType()))
1087 return N = DAG.getNode(ISD::UNDEF, VT);
Chris Lattnerb606dba2008-04-28 06:44:42 +00001088
1089 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
1090 visit(CE->getOpcode(), *CE);
1091 SDOperand N1 = NodeMap[V];
1092 assert(N1.Val && "visit didn't populate the ValueMap!");
1093 return N1;
1094 }
1095
Chris Lattner6833b062008-04-28 07:16:35 +00001096 const VectorType *VecTy = cast<VectorType>(V->getType());
Chris Lattnerb606dba2008-04-28 06:44:42 +00001097 unsigned NumElements = VecTy->getNumElements();
Chris Lattnerb606dba2008-04-28 06:44:42 +00001098
Chris Lattner6833b062008-04-28 07:16:35 +00001099 // Now that we know the number and type of the elements, get that number of
1100 // elements into the Ops array based on what kind of constant it is.
1101 SmallVector<SDOperand, 16> Ops;
Chris Lattnerb606dba2008-04-28 06:44:42 +00001102 if (ConstantVector *CP = dyn_cast<ConstantVector>(C)) {
1103 for (unsigned i = 0; i != NumElements; ++i)
1104 Ops.push_back(getValue(CP->getOperand(i)));
1105 } else {
Chris Lattner6833b062008-04-28 07:16:35 +00001106 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
1107 "Unknown vector constant!");
Duncan Sands83ec4b62008-06-06 12:08:01 +00001108 MVT EltVT = TLI.getValueType(VecTy->getElementType());
Chris Lattner6833b062008-04-28 07:16:35 +00001109
Chris Lattnerb606dba2008-04-28 06:44:42 +00001110 SDOperand Op;
Chris Lattner6833b062008-04-28 07:16:35 +00001111 if (isa<UndefValue>(C))
1112 Op = DAG.getNode(ISD::UNDEF, EltVT);
Duncan Sands83ec4b62008-06-06 12:08:01 +00001113 else if (EltVT.isFloatingPoint())
Chris Lattner6833b062008-04-28 07:16:35 +00001114 Op = DAG.getConstantFP(0, EltVT);
Chris Lattnerb606dba2008-04-28 06:44:42 +00001115 else
Chris Lattner6833b062008-04-28 07:16:35 +00001116 Op = DAG.getConstant(0, EltVT);
Chris Lattnerb606dba2008-04-28 06:44:42 +00001117 Ops.assign(NumElements, Op);
1118 }
1119
1120 // Create a BUILD_VECTOR node.
1121 return NodeMap[V] = DAG.getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
Chris Lattner199862b2006-03-16 19:57:50 +00001122 }
1123
Chris Lattnerb606dba2008-04-28 06:44:42 +00001124 // If this is a static alloca, generate it as the frameindex instead of
1125 // computation.
Chris Lattner199862b2006-03-16 19:57:50 +00001126 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1127 std::map<const AllocaInst*, int>::iterator SI =
Chris Lattnerb606dba2008-04-28 06:44:42 +00001128 FuncInfo.StaticAllocaMap.find(AI);
Chris Lattner199862b2006-03-16 19:57:50 +00001129 if (SI != FuncInfo.StaticAllocaMap.end())
1130 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
1131 }
1132
Chris Lattner251db182007-02-25 18:40:32 +00001133 unsigned InReg = FuncInfo.ValueMap[V];
1134 assert(InReg && "Value not in map!");
Chris Lattner199862b2006-03-16 19:57:50 +00001135
Chris Lattner6833b062008-04-28 07:16:35 +00001136 RegsForValue RFV(TLI, InReg, V->getType());
Dan Gohmanb6f5b002007-06-28 23:29:44 +00001137 SDOperand Chain = DAG.getEntryNode();
Dan Gohmanb6f5b002007-06-28 23:29:44 +00001138 return RFV.getCopyFromRegs(DAG, Chain, NULL);
Chris Lattner199862b2006-03-16 19:57:50 +00001139}
1140
1141
Chris Lattner1c08c712005-01-07 07:47:53 +00001142void SelectionDAGLowering::visitRet(ReturnInst &I) {
1143 if (I.getNumOperands() == 0) {
Dan Gohman86e1ebf2008-03-27 19:56:19 +00001144 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getControlRoot()));
Chris Lattner1c08c712005-01-07 07:47:53 +00001145 return;
1146 }
Chris Lattnerb606dba2008-04-28 06:44:42 +00001147
Chris Lattnerbd564bf2006-08-08 02:23:42 +00001148 SmallVector<SDOperand, 8> NewValues;
Dan Gohman86e1ebf2008-03-27 19:56:19 +00001149 NewValues.push_back(getControlRoot());
1150 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
Nate Begemanee625572006-01-27 21:09:22 +00001151 SDOperand RetOp = getValue(I.getOperand(i));
Duncan Sands83ec4b62008-06-06 12:08:01 +00001152 MVT VT = RetOp.getValueType();
Duncan Sandsb988bac2008-02-11 20:58:28 +00001153
Evan Cheng8e7d0562006-05-26 23:09:09 +00001154 // FIXME: C calling convention requires the return type to be promoted to
1155 // at least 32-bit. But this is not necessary for non-C calling conventions.
Duncan Sands83ec4b62008-06-06 12:08:01 +00001156 if (VT.isInteger()) {
1157 MVT MinVT = TLI.getRegisterType(MVT::i32);
1158 if (VT.getSizeInBits() < MinVT.getSizeInBits())
Duncan Sandsb988bac2008-02-11 20:58:28 +00001159 VT = MinVT;
1160 }
1161
1162 unsigned NumParts = TLI.getNumRegisters(VT);
Duncan Sands83ec4b62008-06-06 12:08:01 +00001163 MVT PartVT = TLI.getRegisterType(VT);
Duncan Sandsb988bac2008-02-11 20:58:28 +00001164 SmallVector<SDOperand, 4> Parts(NumParts);
1165 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
1166
1167 const Function *F = I.getParent()->getParent();
1168 if (F->paramHasAttr(0, ParamAttr::SExt))
1169 ExtendKind = ISD::SIGN_EXTEND;
1170 else if (F->paramHasAttr(0, ParamAttr::ZExt))
1171 ExtendKind = ISD::ZERO_EXTEND;
1172
1173 getCopyToParts(DAG, RetOp, &Parts[0], NumParts, PartVT, ExtendKind);
1174
1175 for (unsigned i = 0; i < NumParts; ++i) {
1176 NewValues.push_back(Parts[i]);
Duncan Sands276dcbd2008-03-21 09:14:45 +00001177 NewValues.push_back(DAG.getArgFlags(ISD::ArgFlagsTy()));
Nate Begemanee625572006-01-27 21:09:22 +00001178 }
Chris Lattner1c08c712005-01-07 07:47:53 +00001179 }
Chris Lattnerbd564bf2006-08-08 02:23:42 +00001180 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other,
1181 &NewValues[0], NewValues.size()));
Chris Lattner1c08c712005-01-07 07:47:53 +00001182}
1183
Chris Lattner571e4342006-10-27 21:36:01 +00001184/// ExportFromCurrentBlock - If this condition isn't known to be exported from
1185/// the current basic block, add it to ValueMap now so that we'll get a
1186/// CopyTo/FromReg.
1187void SelectionDAGLowering::ExportFromCurrentBlock(Value *V) {
1188 // No need to export constants.
1189 if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
1190
1191 // Already exported?
1192 if (FuncInfo.isExportedInst(V)) return;
1193
1194 unsigned Reg = FuncInfo.InitializeRegForValue(V);
Dan Gohman86e1ebf2008-03-27 19:56:19 +00001195 CopyValueToVirtualRegister(V, Reg);
Chris Lattner571e4342006-10-27 21:36:01 +00001196}
1197
Chris Lattner8c494ab2006-10-27 23:50:33 +00001198bool SelectionDAGLowering::isExportableFromCurrentBlock(Value *V,
1199 const BasicBlock *FromBB) {
1200 // The operands of the setcc have to be in this block. We don't know
1201 // how to export them from some other block.
1202 if (Instruction *VI = dyn_cast<Instruction>(V)) {
1203 // Can export from current BB.
1204 if (VI->getParent() == FromBB)
1205 return true;
1206
1207 // Is already exported, noop.
1208 return FuncInfo.isExportedInst(V);
1209 }
1210
1211 // If this is an argument, we can export it if the BB is the entry block or
1212 // if it is already exported.
1213 if (isa<Argument>(V)) {
1214 if (FromBB == &FromBB->getParent()->getEntryBlock())
1215 return true;
1216
1217 // Otherwise, can only export this if it is already exported.
1218 return FuncInfo.isExportedInst(V);
1219 }
1220
1221 // Otherwise, constants can always be exported.
1222 return true;
1223}
1224
Chris Lattner6a586c82006-10-29 21:01:20 +00001225static bool InBlock(const Value *V, const BasicBlock *BB) {
1226 if (const Instruction *I = dyn_cast<Instruction>(V))
1227 return I->getParent() == BB;
1228 return true;
1229}
1230
Chris Lattner571e4342006-10-27 21:36:01 +00001231/// FindMergedConditions - If Cond is an expression like
1232void SelectionDAGLowering::FindMergedConditions(Value *Cond,
1233 MachineBasicBlock *TBB,
1234 MachineBasicBlock *FBB,
1235 MachineBasicBlock *CurBB,
1236 unsigned Opc) {
Chris Lattner571e4342006-10-27 21:36:01 +00001237 // If this node is not part of the or/and tree, emit it as a branch.
Reid Spencere4d87aa2006-12-23 06:05:41 +00001238 Instruction *BOp = dyn_cast<Instruction>(Cond);
Chris Lattner571e4342006-10-27 21:36:01 +00001239
Reid Spencere4d87aa2006-12-23 06:05:41 +00001240 if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
1241 (unsigned)BOp->getOpcode() != Opc || !BOp->hasOneUse() ||
Chris Lattner6a586c82006-10-29 21:01:20 +00001242 BOp->getParent() != CurBB->getBasicBlock() ||
1243 !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
1244 !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
Chris Lattner571e4342006-10-27 21:36:01 +00001245 const BasicBlock *BB = CurBB->getBasicBlock();
1246
Reid Spencere4d87aa2006-12-23 06:05:41 +00001247 // If the leaf of the tree is a comparison, merge the condition into
1248 // the caseblock.
1249 if ((isa<ICmpInst>(Cond) || isa<FCmpInst>(Cond)) &&
1250 // The operands of the cmp have to be in this block. We don't know
Chris Lattner5a145f02006-10-29 18:23:37 +00001251 // how to export them from some other block. If this is the first block
1252 // of the sequence, no exporting is needed.
1253 (CurBB == CurMBB ||
1254 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
1255 isExportableFromCurrentBlock(BOp->getOperand(1), BB)))) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00001256 BOp = cast<Instruction>(Cond);
1257 ISD::CondCode Condition;
1258 if (ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
1259 switch (IC->getPredicate()) {
1260 default: assert(0 && "Unknown icmp predicate opcode!");
1261 case ICmpInst::ICMP_EQ: Condition = ISD::SETEQ; break;
1262 case ICmpInst::ICMP_NE: Condition = ISD::SETNE; break;
1263 case ICmpInst::ICMP_SLE: Condition = ISD::SETLE; break;
1264 case ICmpInst::ICMP_ULE: Condition = ISD::SETULE; break;
1265 case ICmpInst::ICMP_SGE: Condition = ISD::SETGE; break;
1266 case ICmpInst::ICMP_UGE: Condition = ISD::SETUGE; break;
1267 case ICmpInst::ICMP_SLT: Condition = ISD::SETLT; break;
1268 case ICmpInst::ICMP_ULT: Condition = ISD::SETULT; break;
1269 case ICmpInst::ICMP_SGT: Condition = ISD::SETGT; break;
1270 case ICmpInst::ICMP_UGT: Condition = ISD::SETUGT; break;
1271 }
1272 } else if (FCmpInst *FC = dyn_cast<FCmpInst>(Cond)) {
1273 ISD::CondCode FPC, FOC;
1274 switch (FC->getPredicate()) {
1275 default: assert(0 && "Unknown fcmp predicate opcode!");
1276 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
1277 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
1278 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
1279 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
1280 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
1281 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
1282 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
Chris Lattner6bf30ab2008-05-01 07:26:11 +00001283 case FCmpInst::FCMP_ORD: FOC = FPC = ISD::SETO; break;
1284 case FCmpInst::FCMP_UNO: FOC = FPC = ISD::SETUO; break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00001285 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
1286 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
1287 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
1288 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
1289 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
1290 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
1291 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
1292 }
1293 if (FiniteOnlyFPMath())
1294 Condition = FOC;
1295 else
1296 Condition = FPC;
1297 } else {
Chris Lattner0da331f2007-02-04 01:31:47 +00001298 Condition = ISD::SETEQ; // silence warning.
Reid Spencere4d87aa2006-12-23 06:05:41 +00001299 assert(0 && "Unknown compare instruction");
Chris Lattner571e4342006-10-27 21:36:01 +00001300 }
1301
Chris Lattner571e4342006-10-27 21:36:01 +00001302 SelectionDAGISel::CaseBlock CB(Condition, BOp->getOperand(0),
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001303 BOp->getOperand(1), NULL, TBB, FBB, CurBB);
Chris Lattner571e4342006-10-27 21:36:01 +00001304 SwitchCases.push_back(CB);
1305 return;
1306 }
1307
1308 // Create a CaseBlock record representing this branch.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001309 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, Cond, ConstantInt::getTrue(),
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001310 NULL, TBB, FBB, CurBB);
Chris Lattner571e4342006-10-27 21:36:01 +00001311 SwitchCases.push_back(CB);
Chris Lattner571e4342006-10-27 21:36:01 +00001312 return;
1313 }
1314
Chris Lattnerd2f9ee92006-10-27 21:54:23 +00001315
1316 // Create TmpBB after CurBB.
Chris Lattner571e4342006-10-27 21:36:01 +00001317 MachineFunction::iterator BBI = CurBB;
1318 MachineBasicBlock *TmpBB = new MachineBasicBlock(CurBB->getBasicBlock());
1319 CurBB->getParent()->getBasicBlockList().insert(++BBI, TmpBB);
1320
Chris Lattnerd2f9ee92006-10-27 21:54:23 +00001321 if (Opc == Instruction::Or) {
1322 // Codegen X | Y as:
1323 // jmp_if_X TBB
1324 // jmp TmpBB
1325 // TmpBB:
1326 // jmp_if_Y TBB
1327 // jmp FBB
1328 //
Chris Lattner571e4342006-10-27 21:36:01 +00001329
Chris Lattnerd2f9ee92006-10-27 21:54:23 +00001330 // Emit the LHS condition.
1331 FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, Opc);
1332
1333 // Emit the RHS condition into TmpBB.
1334 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
1335 } else {
1336 assert(Opc == Instruction::And && "Unknown merge op!");
1337 // Codegen X & Y as:
1338 // jmp_if_X TmpBB
1339 // jmp FBB
1340 // TmpBB:
1341 // jmp_if_Y TBB
1342 // jmp FBB
1343 //
1344 // This requires creation of TmpBB after CurBB.
1345
1346 // Emit the LHS condition.
1347 FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, Opc);
1348
1349 // Emit the RHS condition into TmpBB.
1350 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
1351 }
Chris Lattner571e4342006-10-27 21:36:01 +00001352}
1353
Chris Lattnerdf19f272006-10-31 22:37:42 +00001354/// If the set of cases should be emitted as a series of branches, return true.
1355/// If we should emit this as a bunch of and/or'd together conditions, return
1356/// false.
1357static bool
1358ShouldEmitAsBranches(const std::vector<SelectionDAGISel::CaseBlock> &Cases) {
1359 if (Cases.size() != 2) return true;
1360
Chris Lattner0ccb5002006-10-31 23:06:00 +00001361 // If this is two comparisons of the same values or'd or and'd together, they
1362 // will get folded into a single comparison, so don't emit two blocks.
1363 if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
1364 Cases[0].CmpRHS == Cases[1].CmpRHS) ||
1365 (Cases[0].CmpRHS == Cases[1].CmpLHS &&
1366 Cases[0].CmpLHS == Cases[1].CmpRHS)) {
1367 return false;
1368 }
1369
Chris Lattnerdf19f272006-10-31 22:37:42 +00001370 return true;
1371}
1372
Chris Lattner1c08c712005-01-07 07:47:53 +00001373void SelectionDAGLowering::visitBr(BranchInst &I) {
1374 // Update machine-CFG edges.
1375 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
Chris Lattner1c08c712005-01-07 07:47:53 +00001376
1377 // Figure out which block is immediately after the current one.
1378 MachineBasicBlock *NextBlock = 0;
1379 MachineFunction::iterator BBI = CurMBB;
1380 if (++BBI != CurMBB->getParent()->end())
1381 NextBlock = BBI;
1382
1383 if (I.isUnconditional()) {
Owen Anderson2d389e82008-06-07 00:00:23 +00001384 // Update machine-CFG edges.
1385 CurMBB->addSuccessor(Succ0MBB);
1386
Chris Lattner1c08c712005-01-07 07:47:53 +00001387 // If this is not a fall-through branch, emit the branch.
1388 if (Succ0MBB != NextBlock)
Dan Gohman86e1ebf2008-03-27 19:56:19 +00001389 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getControlRoot(),
Misha Brukmandedf2bd2005-04-22 04:01:18 +00001390 DAG.getBasicBlock(Succ0MBB)));
Chris Lattner57ab6592006-10-24 17:57:59 +00001391 return;
1392 }
1393
1394 // If this condition is one of the special cases we handle, do special stuff
1395 // now.
1396 Value *CondVal = I.getCondition();
Chris Lattner57ab6592006-10-24 17:57:59 +00001397 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
Chris Lattner571e4342006-10-27 21:36:01 +00001398
1399 // If this is a series of conditions that are or'd or and'd together, emit
1400 // this as a sequence of branches instead of setcc's with and/or operations.
1401 // For example, instead of something like:
1402 // cmp A, B
1403 // C = seteq
1404 // cmp D, E
1405 // F = setle
1406 // or C, F
1407 // jnz foo
1408 // Emit:
1409 // cmp A, B
1410 // je foo
1411 // cmp D, E
1412 // jle foo
1413 //
1414 if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
1415 if (BOp->hasOneUse() &&
Chris Lattnerd2f9ee92006-10-27 21:54:23 +00001416 (BOp->getOpcode() == Instruction::And ||
Chris Lattner571e4342006-10-27 21:36:01 +00001417 BOp->getOpcode() == Instruction::Or)) {
1418 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, CurMBB, BOp->getOpcode());
Chris Lattner0ccb5002006-10-31 23:06:00 +00001419 // If the compares in later blocks need to use values not currently
1420 // exported from this block, export them now. This block should always
1421 // be the first entry.
1422 assert(SwitchCases[0].ThisBB == CurMBB && "Unexpected lowering!");
1423
Chris Lattnerdf19f272006-10-31 22:37:42 +00001424 // Allow some cases to be rejected.
1425 if (ShouldEmitAsBranches(SwitchCases)) {
Chris Lattnerdf19f272006-10-31 22:37:42 +00001426 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
1427 ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
1428 ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
1429 }
1430
1431 // Emit the branch for this block.
1432 visitSwitchCase(SwitchCases[0]);
1433 SwitchCases.erase(SwitchCases.begin());
1434 return;
Chris Lattner5a145f02006-10-29 18:23:37 +00001435 }
1436
Chris Lattner0ccb5002006-10-31 23:06:00 +00001437 // Okay, we decided not to do this, remove any inserted MBB's and clear
1438 // SwitchCases.
1439 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
1440 CurMBB->getParent()->getBasicBlockList().erase(SwitchCases[i].ThisBB);
1441
Chris Lattnerdf19f272006-10-31 22:37:42 +00001442 SwitchCases.clear();
Chris Lattner571e4342006-10-27 21:36:01 +00001443 }
1444 }
Chris Lattner24525952006-10-24 18:07:37 +00001445
1446 // Create a CaseBlock record representing this branch.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001447 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(),
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001448 NULL, Succ0MBB, Succ1MBB, CurMBB);
Chris Lattner24525952006-10-24 18:07:37 +00001449 // Use visitSwitchCase to actually insert the fast branch sequence for this
1450 // cond branch.
1451 visitSwitchCase(CB);
Chris Lattner1c08c712005-01-07 07:47:53 +00001452}
1453
Nate Begemanf15485a2006-03-27 01:32:24 +00001454/// visitSwitchCase - Emits the necessary code to represent a single node in
1455/// the binary search tree resulting from lowering a switch instruction.
1456void SelectionDAGLowering::visitSwitchCase(SelectionDAGISel::CaseBlock &CB) {
Chris Lattner57ab6592006-10-24 17:57:59 +00001457 SDOperand Cond;
1458 SDOperand CondLHS = getValue(CB.CmpLHS);
1459
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001460 // Build the setcc now.
1461 if (CB.CmpMHS == NULL) {
1462 // Fold "(X == true)" to X and "(X == false)" to !X to
1463 // handle common cases produced by branch lowering.
1464 if (CB.CmpRHS == ConstantInt::getTrue() && CB.CC == ISD::SETEQ)
1465 Cond = CondLHS;
1466 else if (CB.CmpRHS == ConstantInt::getFalse() && CB.CC == ISD::SETEQ) {
1467 SDOperand True = DAG.getConstant(1, CondLHS.getValueType());
1468 Cond = DAG.getNode(ISD::XOR, CondLHS.getValueType(), CondLHS, True);
1469 } else
1470 Cond = DAG.getSetCC(MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
1471 } else {
1472 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001473
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001474 uint64_t Low = cast<ConstantInt>(CB.CmpLHS)->getSExtValue();
1475 uint64_t High = cast<ConstantInt>(CB.CmpRHS)->getSExtValue();
1476
1477 SDOperand CmpOp = getValue(CB.CmpMHS);
Duncan Sands83ec4b62008-06-06 12:08:01 +00001478 MVT VT = CmpOp.getValueType();
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001479
1480 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
1481 Cond = DAG.getSetCC(MVT::i1, CmpOp, DAG.getConstant(High, VT), ISD::SETLE);
1482 } else {
1483 SDOperand SUB = DAG.getNode(ISD::SUB, VT, CmpOp, DAG.getConstant(Low, VT));
1484 Cond = DAG.getSetCC(MVT::i1, SUB,
1485 DAG.getConstant(High-Low, VT), ISD::SETULE);
1486 }
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001487 }
1488
Owen Anderson2d389e82008-06-07 00:00:23 +00001489 // Update successor info
1490 CurMBB->addSuccessor(CB.TrueBB);
1491 CurMBB->addSuccessor(CB.FalseBB);
1492
Nate Begemanf15485a2006-03-27 01:32:24 +00001493 // Set NextBlock to be the MBB immediately after the current one, if any.
1494 // This is used to avoid emitting unnecessary branches to the next block.
1495 MachineBasicBlock *NextBlock = 0;
1496 MachineFunction::iterator BBI = CurMBB;
1497 if (++BBI != CurMBB->getParent()->end())
1498 NextBlock = BBI;
1499
1500 // If the lhs block is the next block, invert the condition so that we can
1501 // fall through to the lhs instead of the rhs block.
Chris Lattner57ab6592006-10-24 17:57:59 +00001502 if (CB.TrueBB == NextBlock) {
1503 std::swap(CB.TrueBB, CB.FalseBB);
Nate Begemanf15485a2006-03-27 01:32:24 +00001504 SDOperand True = DAG.getConstant(1, Cond.getValueType());
1505 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
1506 }
Dan Gohman86e1ebf2008-03-27 19:56:19 +00001507 SDOperand BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, getControlRoot(), Cond,
Chris Lattner57ab6592006-10-24 17:57:59 +00001508 DAG.getBasicBlock(CB.TrueBB));
1509 if (CB.FalseBB == NextBlock)
Nate Begemanf15485a2006-03-27 01:32:24 +00001510 DAG.setRoot(BrCond);
1511 else
1512 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond,
Chris Lattner57ab6592006-10-24 17:57:59 +00001513 DAG.getBasicBlock(CB.FalseBB)));
Nate Begemanf15485a2006-03-27 01:32:24 +00001514}
1515
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001516/// visitJumpTable - Emit JumpTable node in the current MBB
Nate Begeman37efe672006-04-22 18:53:45 +00001517void SelectionDAGLowering::visitJumpTable(SelectionDAGISel::JumpTable &JT) {
Nate Begeman37efe672006-04-22 18:53:45 +00001518 // Emit the code for the jump table
Scott Michelf147a8d2007-04-24 01:24:20 +00001519 assert(JT.Reg != -1U && "Should lower JT Header first!");
Duncan Sands83ec4b62008-06-06 12:08:01 +00001520 MVT PTy = TLI.getPointerTy();
Dan Gohman86e1ebf2008-03-27 19:56:19 +00001521 SDOperand Index = DAG.getCopyFromReg(getControlRoot(), JT.Reg, PTy);
Evan Cheng3d4ce112006-10-30 08:00:44 +00001522 SDOperand Table = DAG.getJumpTable(JT.JTI, PTy);
1523 DAG.setRoot(DAG.getNode(ISD::BR_JT, MVT::Other, Index.getValue(1),
1524 Table, Index));
1525 return;
Nate Begeman37efe672006-04-22 18:53:45 +00001526}
1527
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001528/// visitJumpTableHeader - This function emits necessary code to produce index
1529/// in the JumpTable from switch case.
1530void SelectionDAGLowering::visitJumpTableHeader(SelectionDAGISel::JumpTable &JT,
1531 SelectionDAGISel::JumpTableHeader &JTH) {
1532 // Subtract the lowest switch case value from the value being switched on
1533 // and conditional branch to default mbb if the result is greater than the
1534 // difference between smallest and largest cases.
1535 SDOperand SwitchOp = getValue(JTH.SValue);
Duncan Sands83ec4b62008-06-06 12:08:01 +00001536 MVT VT = SwitchOp.getValueType();
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001537 SDOperand SUB = DAG.getNode(ISD::SUB, VT, SwitchOp,
1538 DAG.getConstant(JTH.First, VT));
1539
1540 // The SDNode we just created, which holds the value being switched on
1541 // minus the the smallest case value, needs to be copied to a virtual
1542 // register so it can be used as an index into the jump table in a
1543 // subsequent basic block. This value may be smaller or larger than the
1544 // target's pointer type, and therefore require extension or truncating.
Duncan Sands83ec4b62008-06-06 12:08:01 +00001545 if (VT.getSizeInBits() > TLI.getPointerTy().getSizeInBits())
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001546 SwitchOp = DAG.getNode(ISD::TRUNCATE, TLI.getPointerTy(), SUB);
1547 else
1548 SwitchOp = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(), SUB);
1549
1550 unsigned JumpTableReg = FuncInfo.MakeReg(TLI.getPointerTy());
Dan Gohman86e1ebf2008-03-27 19:56:19 +00001551 SDOperand CopyTo = DAG.getCopyToReg(getControlRoot(), JumpTableReg, SwitchOp);
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001552 JT.Reg = JumpTableReg;
1553
1554 // Emit the range check for the jump table, and branch to the default
1555 // block for the switch statement if the value being switched on exceeds
1556 // the largest case in the switch.
Scott Michel5b8f82e2008-03-10 15:42:14 +00001557 SDOperand CMP = DAG.getSetCC(TLI.getSetCCResultType(SUB), SUB,
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001558 DAG.getConstant(JTH.Last-JTH.First,VT),
1559 ISD::SETUGT);
1560
1561 // Set NextBlock to be the MBB immediately after the current one, if any.
1562 // This is used to avoid emitting unnecessary branches to the next block.
1563 MachineBasicBlock *NextBlock = 0;
1564 MachineFunction::iterator BBI = CurMBB;
1565 if (++BBI != CurMBB->getParent()->end())
1566 NextBlock = BBI;
1567
1568 SDOperand BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, CopyTo, CMP,
1569 DAG.getBasicBlock(JT.Default));
1570
1571 if (JT.MBB == NextBlock)
1572 DAG.setRoot(BrCond);
1573 else
1574 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond,
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001575 DAG.getBasicBlock(JT.MBB)));
1576
1577 return;
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001578}
1579
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001580/// visitBitTestHeader - This function emits necessary code to produce value
1581/// suitable for "bit tests"
1582void SelectionDAGLowering::visitBitTestHeader(SelectionDAGISel::BitTestBlock &B) {
1583 // Subtract the minimum value
1584 SDOperand SwitchOp = getValue(B.SValue);
Duncan Sands83ec4b62008-06-06 12:08:01 +00001585 MVT VT = SwitchOp.getValueType();
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001586 SDOperand SUB = DAG.getNode(ISD::SUB, VT, SwitchOp,
1587 DAG.getConstant(B.First, VT));
1588
1589 // Check range
Scott Michel5b8f82e2008-03-10 15:42:14 +00001590 SDOperand RangeCmp = DAG.getSetCC(TLI.getSetCCResultType(SUB), SUB,
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001591 DAG.getConstant(B.Range, VT),
1592 ISD::SETUGT);
1593
1594 SDOperand ShiftOp;
Duncan Sands83ec4b62008-06-06 12:08:01 +00001595 if (VT.getSizeInBits() > TLI.getShiftAmountTy().getSizeInBits())
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001596 ShiftOp = DAG.getNode(ISD::TRUNCATE, TLI.getShiftAmountTy(), SUB);
1597 else
1598 ShiftOp = DAG.getNode(ISD::ZERO_EXTEND, TLI.getShiftAmountTy(), SUB);
1599
1600 // Make desired shift
1601 SDOperand SwitchVal = DAG.getNode(ISD::SHL, TLI.getPointerTy(),
1602 DAG.getConstant(1, TLI.getPointerTy()),
1603 ShiftOp);
1604
1605 unsigned SwitchReg = FuncInfo.MakeReg(TLI.getPointerTy());
Dan Gohman86e1ebf2008-03-27 19:56:19 +00001606 SDOperand CopyTo = DAG.getCopyToReg(getControlRoot(), SwitchReg, SwitchVal);
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001607 B.Reg = SwitchReg;
1608
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001609 // Set NextBlock to be the MBB immediately after the current one, if any.
1610 // This is used to avoid emitting unnecessary branches to the next block.
1611 MachineBasicBlock *NextBlock = 0;
1612 MachineFunction::iterator BBI = CurMBB;
1613 if (++BBI != CurMBB->getParent()->end())
1614 NextBlock = BBI;
1615
1616 MachineBasicBlock* MBB = B.Cases[0].ThisBB;
Owen Anderson2d389e82008-06-07 00:00:23 +00001617
1618 CurMBB->addSuccessor(B.Default);
1619 CurMBB->addSuccessor(MBB);
1620
1621 SDOperand BrRange = DAG.getNode(ISD::BRCOND, MVT::Other, CopyTo, RangeCmp,
1622 DAG.getBasicBlock(B.Default));
1623
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001624 if (MBB == NextBlock)
1625 DAG.setRoot(BrRange);
1626 else
1627 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, CopyTo,
1628 DAG.getBasicBlock(MBB)));
1629
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001630 return;
1631}
1632
1633/// visitBitTestCase - this function produces one "bit test"
1634void SelectionDAGLowering::visitBitTestCase(MachineBasicBlock* NextMBB,
1635 unsigned Reg,
1636 SelectionDAGISel::BitTestCase &B) {
1637 // Emit bit tests and jumps
Dan Gohman86e1ebf2008-03-27 19:56:19 +00001638 SDOperand SwitchVal = DAG.getCopyFromReg(getControlRoot(), Reg, TLI.getPointerTy());
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001639
1640 SDOperand AndOp = DAG.getNode(ISD::AND, TLI.getPointerTy(),
1641 SwitchVal,
1642 DAG.getConstant(B.Mask,
1643 TLI.getPointerTy()));
Scott Michel5b8f82e2008-03-10 15:42:14 +00001644 SDOperand AndCmp = DAG.getSetCC(TLI.getSetCCResultType(AndOp), AndOp,
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001645 DAG.getConstant(0, TLI.getPointerTy()),
1646 ISD::SETNE);
Owen Anderson2d389e82008-06-07 00:00:23 +00001647
1648 CurMBB->addSuccessor(B.TargetBB);
1649 CurMBB->addSuccessor(NextMBB);
1650
Dan Gohman86e1ebf2008-03-27 19:56:19 +00001651 SDOperand BrAnd = DAG.getNode(ISD::BRCOND, MVT::Other, getControlRoot(),
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001652 AndCmp, DAG.getBasicBlock(B.TargetBB));
1653
1654 // Set NextBlock to be the MBB immediately after the current one, if any.
1655 // This is used to avoid emitting unnecessary branches to the next block.
1656 MachineBasicBlock *NextBlock = 0;
1657 MachineFunction::iterator BBI = CurMBB;
1658 if (++BBI != CurMBB->getParent()->end())
1659 NextBlock = BBI;
1660
1661 if (NextMBB == NextBlock)
1662 DAG.setRoot(BrAnd);
1663 else
1664 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrAnd,
1665 DAG.getBasicBlock(NextMBB)));
1666
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001667 return;
1668}
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001669
Jim Laskeyb180aa12007-02-21 22:53:45 +00001670void SelectionDAGLowering::visitInvoke(InvokeInst &I) {
1671 // Retrieve successors.
1672 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
Duncan Sandsf19f6bb2007-06-13 05:51:31 +00001673 MachineBasicBlock *LandingPad = FuncInfo.MBBMap[I.getSuccessor(1)];
Duncan Sands9fac0b52007-06-06 10:05:18 +00001674
Duncan Sandsfd7b3262007-12-17 18:08:19 +00001675 if (isa<InlineAsm>(I.getCalledValue()))
1676 visitInlineAsm(&I);
1677 else
Duncan Sands6f74b482007-12-19 09:48:52 +00001678 LowerCallTo(&I, getValue(I.getOperand(0)), false, LandingPad);
Duncan Sands9fac0b52007-06-06 10:05:18 +00001679
Duncan Sandsf19f6bb2007-06-13 05:51:31 +00001680 // If the value of the invoke is used outside of its defining block, make it
1681 // available as a virtual register.
1682 if (!I.use_empty()) {
1683 DenseMap<const Value*, unsigned>::iterator VMI = FuncInfo.ValueMap.find(&I);
1684 if (VMI != FuncInfo.ValueMap.end())
Dan Gohman86e1ebf2008-03-27 19:56:19 +00001685 CopyValueToVirtualRegister(&I, VMI->second);
Jim Laskey183f47f2007-02-25 21:43:59 +00001686 }
Duncan Sandsf19f6bb2007-06-13 05:51:31 +00001687
Duncan Sandsf19f6bb2007-06-13 05:51:31 +00001688 // Update successor info
1689 CurMBB->addSuccessor(Return);
1690 CurMBB->addSuccessor(LandingPad);
Owen Anderson2d389e82008-06-07 00:00:23 +00001691
1692 // Drop into normal successor.
1693 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getControlRoot(),
1694 DAG.getBasicBlock(Return)));
Jim Laskeyb180aa12007-02-21 22:53:45 +00001695}
1696
1697void SelectionDAGLowering::visitUnwind(UnwindInst &I) {
1698}
1699
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001700/// handleSmallSwitchCaseRange - Emit a series of specific tests (suitable for
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001701/// small case ranges).
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001702bool SelectionDAGLowering::handleSmallSwitchRange(CaseRec& CR,
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001703 CaseRecVector& WorkList,
1704 Value* SV,
1705 MachineBasicBlock* Default) {
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001706 Case& BackCase = *(CR.Range.second-1);
1707
1708 // Size is the number of Cases represented by this range.
1709 unsigned Size = CR.Range.second - CR.Range.first;
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001710 if (Size > 3)
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001711 return false;
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001712
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001713 // Get the MachineFunction which holds the current MBB. This is used when
1714 // inserting any additional MBBs necessary to represent the switch.
1715 MachineFunction *CurMF = CurMBB->getParent();
1716
1717 // Figure out which block is immediately after the current one.
1718 MachineBasicBlock *NextBlock = 0;
1719 MachineFunction::iterator BBI = CR.CaseBB;
1720
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001721 if (++BBI != CurMBB->getParent()->end())
1722 NextBlock = BBI;
1723
1724 // TODO: If any two of the cases has the same destination, and if one value
1725 // is the same as the other, but has one bit unset that the other has set,
1726 // use bit manipulation to do two compares at once. For example:
1727 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
1728
1729 // Rearrange the case blocks so that the last one falls through if possible.
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001730 if (NextBlock && Default != NextBlock && BackCase.BB != NextBlock) {
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001731 // The last case block won't fall through into 'NextBlock' if we emit the
1732 // branches in this order. See if rearranging a case value would help.
1733 for (CaseItr I = CR.Range.first, E = CR.Range.second-1; I != E; ++I) {
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001734 if (I->BB == NextBlock) {
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001735 std::swap(*I, BackCase);
1736 break;
1737 }
1738 }
1739 }
1740
1741 // Create a CaseBlock record representing a conditional branch to
1742 // the Case's target mbb if the value being switched on SV is equal
1743 // to C.
1744 MachineBasicBlock *CurBlock = CR.CaseBB;
1745 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I) {
1746 MachineBasicBlock *FallThrough;
1747 if (I != E-1) {
1748 FallThrough = new MachineBasicBlock(CurBlock->getBasicBlock());
1749 CurMF->getBasicBlockList().insert(BBI, FallThrough);
1750 } else {
1751 // If the last case doesn't match, go to the default block.
1752 FallThrough = Default;
1753 }
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001754
1755 Value *RHS, *LHS, *MHS;
1756 ISD::CondCode CC;
1757 if (I->High == I->Low) {
1758 // This is just small small case range :) containing exactly 1 case
1759 CC = ISD::SETEQ;
1760 LHS = SV; RHS = I->High; MHS = NULL;
1761 } else {
1762 CC = ISD::SETLE;
1763 LHS = I->Low; MHS = SV; RHS = I->High;
1764 }
1765 SelectionDAGISel::CaseBlock CB(CC, LHS, RHS, MHS,
1766 I->BB, FallThrough, CurBlock);
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001767
1768 // If emitting the first comparison, just call visitSwitchCase to emit the
1769 // code into the current block. Otherwise, push the CaseBlock onto the
1770 // vector to be later processed by SDISel, and insert the node's MBB
1771 // before the next MBB.
1772 if (CurBlock == CurMBB)
1773 visitSwitchCase(CB);
1774 else
1775 SwitchCases.push_back(CB);
1776
1777 CurBlock = FallThrough;
1778 }
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001779
1780 return true;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001781}
1782
Anton Korobeynikov7294b582007-05-09 20:07:08 +00001783static inline bool areJTsAllowed(const TargetLowering &TLI) {
1784 return (TLI.isOperationLegal(ISD::BR_JT, MVT::Other) ||
1785 TLI.isOperationLegal(ISD::BRIND, MVT::Other));
1786}
1787
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001788/// handleJTSwitchCase - Emit jumptable for current switch case range
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001789bool SelectionDAGLowering::handleJTSwitchCase(CaseRec& CR,
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001790 CaseRecVector& WorkList,
1791 Value* SV,
1792 MachineBasicBlock* Default) {
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001793 Case& FrontCase = *CR.Range.first;
1794 Case& BackCase = *(CR.Range.second-1);
1795
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001796 int64_t First = cast<ConstantInt>(FrontCase.Low)->getSExtValue();
1797 int64_t Last = cast<ConstantInt>(BackCase.High)->getSExtValue();
1798
1799 uint64_t TSize = 0;
1800 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1801 I!=E; ++I)
1802 TSize += I->size();
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001803
Anton Korobeynikov7294b582007-05-09 20:07:08 +00001804 if (!areJTsAllowed(TLI) || TSize <= 3)
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001805 return false;
1806
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001807 double Density = (double)TSize / (double)((Last - First) + 1ULL);
1808 if (Density < 0.4)
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001809 return false;
1810
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001811 DOUT << "Lowering jump table\n"
1812 << "First entry: " << First << ". Last entry: " << Last << "\n"
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001813 << "Size: " << TSize << ". Density: " << Density << "\n\n";
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001814
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001815 // Get the MachineFunction which holds the current MBB. This is used when
1816 // inserting any additional MBBs necessary to represent the switch.
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001817 MachineFunction *CurMF = CurMBB->getParent();
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001818
1819 // Figure out which block is immediately after the current one.
1820 MachineBasicBlock *NextBlock = 0;
1821 MachineFunction::iterator BBI = CR.CaseBB;
1822
1823 if (++BBI != CurMBB->getParent()->end())
1824 NextBlock = BBI;
1825
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001826 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1827
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001828 // Create a new basic block to hold the code for loading the address
1829 // of the jump table, and jumping to it. Update successor information;
1830 // we will either branch to the default case for the switch, or the jump
1831 // table.
1832 MachineBasicBlock *JumpTableBB = new MachineBasicBlock(LLVMBB);
1833 CurMF->getBasicBlockList().insert(BBI, JumpTableBB);
1834 CR.CaseBB->addSuccessor(Default);
1835 CR.CaseBB->addSuccessor(JumpTableBB);
1836
1837 // Build a vector of destination BBs, corresponding to each target
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001838 // of the jump table. If the value of the jump table slot corresponds to
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001839 // a case statement, push the case's BB onto the vector, otherwise, push
1840 // the default BB.
1841 std::vector<MachineBasicBlock*> DestBBs;
1842 int64_t TEI = First;
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001843 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++TEI) {
1844 int64_t Low = cast<ConstantInt>(I->Low)->getSExtValue();
1845 int64_t High = cast<ConstantInt>(I->High)->getSExtValue();
1846
1847 if ((Low <= TEI) && (TEI <= High)) {
1848 DestBBs.push_back(I->BB);
1849 if (TEI==High)
1850 ++I;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001851 } else {
1852 DestBBs.push_back(Default);
1853 }
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001854 }
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001855
1856 // Update successor info. Add one edge to each unique successor.
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001857 BitVector SuccsHandled(CR.CaseBB->getParent()->getNumBlockIDs());
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001858 for (std::vector<MachineBasicBlock*>::iterator I = DestBBs.begin(),
1859 E = DestBBs.end(); I != E; ++I) {
1860 if (!SuccsHandled[(*I)->getNumber()]) {
1861 SuccsHandled[(*I)->getNumber()] = true;
1862 JumpTableBB->addSuccessor(*I);
1863 }
1864 }
1865
1866 // Create a jump table index for this jump table, or return an existing
1867 // one.
1868 unsigned JTI = CurMF->getJumpTableInfo()->getJumpTableIndex(DestBBs);
1869
1870 // Set the jump table information so that we can codegen it as a second
1871 // MachineBasicBlock
Scott Michelf147a8d2007-04-24 01:24:20 +00001872 SelectionDAGISel::JumpTable JT(-1U, JTI, JumpTableBB, Default);
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001873 SelectionDAGISel::JumpTableHeader JTH(First, Last, SV, CR.CaseBB,
1874 (CR.CaseBB == CurMBB));
1875 if (CR.CaseBB == CurMBB)
1876 visitJumpTableHeader(JT, JTH);
1877
1878 JTCases.push_back(SelectionDAGISel::JumpTableBlock(JTH, JT));
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001879
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001880 return true;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001881}
1882
1883/// handleBTSplitSwitchCase - emit comparison and split binary search tree into
1884/// 2 subtrees.
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001885bool SelectionDAGLowering::handleBTSplitSwitchCase(CaseRec& CR,
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001886 CaseRecVector& WorkList,
1887 Value* SV,
1888 MachineBasicBlock* Default) {
1889 // Get the MachineFunction which holds the current MBB. This is used when
1890 // inserting any additional MBBs necessary to represent the switch.
1891 MachineFunction *CurMF = CurMBB->getParent();
1892
1893 // Figure out which block is immediately after the current one.
1894 MachineBasicBlock *NextBlock = 0;
1895 MachineFunction::iterator BBI = CR.CaseBB;
1896
1897 if (++BBI != CurMBB->getParent()->end())
1898 NextBlock = BBI;
1899
1900 Case& FrontCase = *CR.Range.first;
1901 Case& BackCase = *(CR.Range.second-1);
1902 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1903
1904 // Size is the number of Cases represented by this range.
1905 unsigned Size = CR.Range.second - CR.Range.first;
1906
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001907 int64_t First = cast<ConstantInt>(FrontCase.Low)->getSExtValue();
1908 int64_t Last = cast<ConstantInt>(BackCase.High)->getSExtValue();
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001909 double FMetric = 0;
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001910 CaseItr Pivot = CR.Range.first + Size/2;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001911
1912 // Select optimal pivot, maximizing sum density of LHS and RHS. This will
1913 // (heuristically) allow us to emit JumpTable's later.
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001914 uint64_t TSize = 0;
1915 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1916 I!=E; ++I)
1917 TSize += I->size();
1918
1919 uint64_t LSize = FrontCase.size();
1920 uint64_t RSize = TSize-LSize;
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001921 DOUT << "Selecting best pivot: \n"
1922 << "First: " << First << ", Last: " << Last <<"\n"
1923 << "LSize: " << LSize << ", RSize: " << RSize << "\n";
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001924 for (CaseItr I = CR.Range.first, J=I+1, E = CR.Range.second;
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001925 J!=E; ++I, ++J) {
1926 int64_t LEnd = cast<ConstantInt>(I->High)->getSExtValue();
1927 int64_t RBegin = cast<ConstantInt>(J->Low)->getSExtValue();
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001928 assert((RBegin-LEnd>=1) && "Invalid case distance");
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001929 double LDensity = (double)LSize / (double)((LEnd - First) + 1ULL);
1930 double RDensity = (double)RSize / (double)((Last - RBegin) + 1ULL);
Anton Korobeynikov54e2b142007-04-09 21:57:03 +00001931 double Metric = Log2_64(RBegin-LEnd)*(LDensity+RDensity);
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001932 // Should always split in some non-trivial place
1933 DOUT <<"=>Step\n"
1934 << "LEnd: " << LEnd << ", RBegin: " << RBegin << "\n"
1935 << "LDensity: " << LDensity << ", RDensity: " << RDensity << "\n"
1936 << "Metric: " << Metric << "\n";
1937 if (FMetric < Metric) {
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001938 Pivot = J;
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001939 FMetric = Metric;
1940 DOUT << "Current metric set to: " << FMetric << "\n";
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001941 }
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001942
1943 LSize += J->size();
1944 RSize -= J->size();
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001945 }
Anton Korobeynikov7294b582007-05-09 20:07:08 +00001946 if (areJTsAllowed(TLI)) {
1947 // If our case is dense we *really* should handle it earlier!
1948 assert((FMetric > 0) && "Should handle dense range earlier!");
1949 } else {
1950 Pivot = CR.Range.first + Size/2;
1951 }
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001952
1953 CaseRange LHSR(CR.Range.first, Pivot);
1954 CaseRange RHSR(Pivot, CR.Range.second);
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001955 Constant *C = Pivot->Low;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001956 MachineBasicBlock *FalseBB = 0, *TrueBB = 0;
1957
1958 // We know that we branch to the LHS if the Value being switched on is
1959 // less than the Pivot value, C. We use this to optimize our binary
1960 // tree a bit, by recognizing that if SV is greater than or equal to the
1961 // LHS's Case Value, and that Case Value is exactly one less than the
1962 // Pivot's Value, then we can branch directly to the LHS's Target,
1963 // rather than creating a leaf node for it.
1964 if ((LHSR.second - LHSR.first) == 1 &&
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001965 LHSR.first->High == CR.GE &&
1966 cast<ConstantInt>(C)->getSExtValue() ==
1967 (cast<ConstantInt>(CR.GE)->getSExtValue() + 1LL)) {
1968 TrueBB = LHSR.first->BB;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001969 } else {
1970 TrueBB = new MachineBasicBlock(LLVMBB);
1971 CurMF->getBasicBlockList().insert(BBI, TrueBB);
1972 WorkList.push_back(CaseRec(TrueBB, C, CR.GE, LHSR));
1973 }
1974
1975 // Similar to the optimization above, if the Value being switched on is
1976 // known to be less than the Constant CR.LT, and the current Case Value
1977 // is CR.LT - 1, then we can branch directly to the target block for
1978 // the current Case Value, rather than emitting a RHS leaf node for it.
1979 if ((RHSR.second - RHSR.first) == 1 && CR.LT &&
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001980 cast<ConstantInt>(RHSR.first->Low)->getSExtValue() ==
1981 (cast<ConstantInt>(CR.LT)->getSExtValue() - 1LL)) {
1982 FalseBB = RHSR.first->BB;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001983 } else {
1984 FalseBB = new MachineBasicBlock(LLVMBB);
1985 CurMF->getBasicBlockList().insert(BBI, FalseBB);
1986 WorkList.push_back(CaseRec(FalseBB,CR.LT,C,RHSR));
1987 }
1988
1989 // Create a CaseBlock record representing a conditional branch to
1990 // the LHS node if the value being switched on SV is less than C.
1991 // Otherwise, branch to LHS.
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001992 SelectionDAGISel::CaseBlock CB(ISD::SETLT, SV, C, NULL,
1993 TrueBB, FalseBB, CR.CaseBB);
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001994
1995 if (CR.CaseBB == CurMBB)
1996 visitSwitchCase(CB);
1997 else
1998 SwitchCases.push_back(CB);
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001999
2000 return true;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00002001}
2002
Anton Korobeynikov4198c582007-04-09 12:31:58 +00002003/// handleBitTestsSwitchCase - if current case range has few destination and
2004/// range span less, than machine word bitwidth, encode case range into series
2005/// of masks and emit bit tests with these masks.
2006bool SelectionDAGLowering::handleBitTestsSwitchCase(CaseRec& CR,
2007 CaseRecVector& WorkList,
2008 Value* SV,
Chris Lattner3ff98172007-04-14 02:26:56 +00002009 MachineBasicBlock* Default){
Duncan Sands83ec4b62008-06-06 12:08:01 +00002010 unsigned IntPtrBits = TLI.getPointerTy().getSizeInBits();
Anton Korobeynikov4198c582007-04-09 12:31:58 +00002011
2012 Case& FrontCase = *CR.Range.first;
2013 Case& BackCase = *(CR.Range.second-1);
2014
2015 // Get the MachineFunction which holds the current MBB. This is used when
2016 // inserting any additional MBBs necessary to represent the switch.
2017 MachineFunction *CurMF = CurMBB->getParent();
2018
2019 unsigned numCmps = 0;
2020 for (CaseItr I = CR.Range.first, E = CR.Range.second;
2021 I!=E; ++I) {
2022 // Single case counts one, case range - two.
2023 if (I->Low == I->High)
2024 numCmps +=1;
2025 else
2026 numCmps +=2;
2027 }
2028
2029 // Count unique destinations
2030 SmallSet<MachineBasicBlock*, 4> Dests;
2031 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
2032 Dests.insert(I->BB);
2033 if (Dests.size() > 3)
2034 // Don't bother the code below, if there are too much unique destinations
2035 return false;
2036 }
2037 DOUT << "Total number of unique destinations: " << Dests.size() << "\n"
2038 << "Total number of comparisons: " << numCmps << "\n";
2039
2040 // Compute span of values.
2041 Constant* minValue = FrontCase.Low;
2042 Constant* maxValue = BackCase.High;
2043 uint64_t range = cast<ConstantInt>(maxValue)->getSExtValue() -
2044 cast<ConstantInt>(minValue)->getSExtValue();
2045 DOUT << "Compare range: " << range << "\n"
2046 << "Low bound: " << cast<ConstantInt>(minValue)->getSExtValue() << "\n"
2047 << "High bound: " << cast<ConstantInt>(maxValue)->getSExtValue() << "\n";
2048
Anton Korobeynikovab8fd402007-04-26 20:44:04 +00002049 if (range>=IntPtrBits ||
Anton Korobeynikov4198c582007-04-09 12:31:58 +00002050 (!(Dests.size() == 1 && numCmps >= 3) &&
2051 !(Dests.size() == 2 && numCmps >= 5) &&
2052 !(Dests.size() >= 3 && numCmps >= 6)))
2053 return false;
2054
2055 DOUT << "Emitting bit tests\n";
2056 int64_t lowBound = 0;
2057
2058 // Optimize the case where all the case values fit in a
2059 // word without having to subtract minValue. In this case,
2060 // we can optimize away the subtraction.
2061 if (cast<ConstantInt>(minValue)->getSExtValue() >= 0 &&
Anton Korobeynikove01017b2007-04-14 13:25:55 +00002062 cast<ConstantInt>(maxValue)->getSExtValue() < IntPtrBits) {
Anton Korobeynikov4198c582007-04-09 12:31:58 +00002063 range = cast<ConstantInt>(maxValue)->getSExtValue();
2064 } else {
2065 lowBound = cast<ConstantInt>(minValue)->getSExtValue();
2066 }
2067
2068 CaseBitsVector CasesBits;
2069 unsigned i, count = 0;
2070
2071 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
2072 MachineBasicBlock* Dest = I->BB;
2073 for (i = 0; i < count; ++i)
2074 if (Dest == CasesBits[i].BB)
2075 break;
2076
2077 if (i == count) {
2078 assert((count < 3) && "Too much destinations to test!");
2079 CasesBits.push_back(CaseBits(0, Dest, 0));
2080 count++;
2081 }
2082
2083 uint64_t lo = cast<ConstantInt>(I->Low)->getSExtValue() - lowBound;
2084 uint64_t hi = cast<ConstantInt>(I->High)->getSExtValue() - lowBound;
2085
2086 for (uint64_t j = lo; j <= hi; j++) {
Anton Korobeynikove01017b2007-04-14 13:25:55 +00002087 CasesBits[i].Mask |= 1ULL << j;
Anton Korobeynikov4198c582007-04-09 12:31:58 +00002088 CasesBits[i].Bits++;
2089 }
2090
2091 }
2092 std::sort(CasesBits.begin(), CasesBits.end(), CaseBitsCmp());
2093
2094 SelectionDAGISel::BitTestInfo BTC;
2095
2096 // Figure out which block is immediately after the current one.
2097 MachineFunction::iterator BBI = CR.CaseBB;
2098 ++BBI;
2099
2100 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
2101
2102 DOUT << "Cases:\n";
2103 for (unsigned i = 0, e = CasesBits.size(); i!=e; ++i) {
2104 DOUT << "Mask: " << CasesBits[i].Mask << ", Bits: " << CasesBits[i].Bits
2105 << ", BB: " << CasesBits[i].BB << "\n";
2106
2107 MachineBasicBlock *CaseBB = new MachineBasicBlock(LLVMBB);
2108 CurMF->getBasicBlockList().insert(BBI, CaseBB);
2109 BTC.push_back(SelectionDAGISel::BitTestCase(CasesBits[i].Mask,
2110 CaseBB,
2111 CasesBits[i].BB));
2112 }
2113
2114 SelectionDAGISel::BitTestBlock BTB(lowBound, range, SV,
Jeff Cohenefc36622007-04-09 14:32:59 +00002115 -1U, (CR.CaseBB == CurMBB),
Anton Korobeynikov4198c582007-04-09 12:31:58 +00002116 CR.CaseBB, Default, BTC);
2117
2118 if (CR.CaseBB == CurMBB)
2119 visitBitTestHeader(BTB);
2120
2121 BitTestCases.push_back(BTB);
2122
2123 return true;
2124}
2125
2126
Dan Gohman86e1ebf2008-03-27 19:56:19 +00002127/// Clusterify - Transform simple list of Cases into list of CaseRange's
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002128unsigned SelectionDAGLowering::Clusterify(CaseVector& Cases,
2129 const SwitchInst& SI) {
2130 unsigned numCmps = 0;
2131
2132 // Start with "simple" cases
2133 for (unsigned i = 1; i < SI.getNumSuccessors(); ++i) {
2134 MachineBasicBlock *SMBB = FuncInfo.MBBMap[SI.getSuccessor(i)];
2135 Cases.push_back(Case(SI.getSuccessorValue(i),
2136 SI.getSuccessorValue(i),
2137 SMBB));
2138 }
Chris Lattnerb3d9cdb2007-11-27 06:14:32 +00002139 std::sort(Cases.begin(), Cases.end(), CaseCmp());
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002140
2141 // Merge case into clusters
2142 if (Cases.size()>=2)
David Greenea2a48852007-06-29 03:42:23 +00002143 // Must recompute end() each iteration because it may be
2144 // invalidated by erase if we hold on to it
Chris Lattner27a6c732007-11-24 07:07:01 +00002145 for (CaseItr I=Cases.begin(), J=++(Cases.begin()); J!=Cases.end(); ) {
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002146 int64_t nextValue = cast<ConstantInt>(J->Low)->getSExtValue();
2147 int64_t currentValue = cast<ConstantInt>(I->High)->getSExtValue();
2148 MachineBasicBlock* nextBB = J->BB;
2149 MachineBasicBlock* currentBB = I->BB;
2150
2151 // If the two neighboring cases go to the same destination, merge them
2152 // into a single case.
2153 if ((nextValue-currentValue==1) && (currentBB == nextBB)) {
2154 I->High = J->High;
2155 J = Cases.erase(J);
2156 } else {
2157 I = J++;
2158 }
2159 }
2160
2161 for (CaseItr I=Cases.begin(), E=Cases.end(); I!=E; ++I, ++numCmps) {
2162 if (I->Low != I->High)
2163 // A range counts double, since it requires two compares.
2164 ++numCmps;
2165 }
2166
2167 return numCmps;
2168}
2169
2170void SelectionDAGLowering::visitSwitch(SwitchInst &SI) {
Nate Begemanf15485a2006-03-27 01:32:24 +00002171 // Figure out which block is immediately after the current one.
2172 MachineBasicBlock *NextBlock = 0;
2173 MachineFunction::iterator BBI = CurMBB;
Bill Wendlingc70ddad2006-10-19 21:46:38 +00002174
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002175 MachineBasicBlock *Default = FuncInfo.MBBMap[SI.getDefaultDest()];
Chris Lattnerd2c1d222006-10-22 21:36:53 +00002176
Nate Begemanf15485a2006-03-27 01:32:24 +00002177 // If there is only the default destination, branch to it if it is not the
2178 // next basic block. Otherwise, just fall through.
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002179 if (SI.getNumOperands() == 2) {
Nate Begemanf15485a2006-03-27 01:32:24 +00002180 // Update machine-CFG edges.
Bill Wendlingc70ddad2006-10-19 21:46:38 +00002181
Nate Begemanf15485a2006-03-27 01:32:24 +00002182 // If this is not a fall-through branch, emit the branch.
Owen Anderson2d389e82008-06-07 00:00:23 +00002183 CurMBB->addSuccessor(Default);
Chris Lattnerd2c1d222006-10-22 21:36:53 +00002184 if (Default != NextBlock)
Dan Gohman86e1ebf2008-03-27 19:56:19 +00002185 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getControlRoot(),
Chris Lattnerd2c1d222006-10-22 21:36:53 +00002186 DAG.getBasicBlock(Default)));
Owen Anderson2d389e82008-06-07 00:00:23 +00002187
Nate Begemanf15485a2006-03-27 01:32:24 +00002188 return;
2189 }
2190
2191 // If there are any non-default case statements, create a vector of Cases
2192 // representing each one, and sort the vector so that we can efficiently
2193 // create a binary search tree from them.
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002194 CaseVector Cases;
2195 unsigned numCmps = Clusterify(Cases, SI);
2196 DOUT << "Clusterify finished. Total clusters: " << Cases.size()
2197 << ". Total compares: " << numCmps << "\n";
Bill Wendlingc70ddad2006-10-19 21:46:38 +00002198
Nate Begemanf15485a2006-03-27 01:32:24 +00002199 // Get the Value to be switched on and default basic blocks, which will be
2200 // inserted into CaseBlock records, representing basic blocks in the binary
2201 // search tree.
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002202 Value *SV = SI.getOperand(0);
Nate Begeman37efe672006-04-22 18:53:45 +00002203
Nate Begemanf15485a2006-03-27 01:32:24 +00002204 // Push the initial CaseRec onto the worklist
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00002205 CaseRecVector WorkList;
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00002206 WorkList.push_back(CaseRec(CurMBB,0,0,CaseRange(Cases.begin(),Cases.end())));
2207
2208 while (!WorkList.empty()) {
Nate Begemanf15485a2006-03-27 01:32:24 +00002209 // Grab a record representing a case range to process off the worklist
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00002210 CaseRec CR = WorkList.back();
2211 WorkList.pop_back();
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00002212
Anton Korobeynikov4198c582007-04-09 12:31:58 +00002213 if (handleBitTestsSwitchCase(CR, WorkList, SV, Default))
2214 continue;
2215
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00002216 // If the range has few cases (two or less) emit a series of specific
2217 // tests.
Anton Korobeynikovdd433212007-03-27 12:05:48 +00002218 if (handleSmallSwitchRange(CR, WorkList, SV, Default))
2219 continue;
2220
Anton Korobeynikov4198c582007-04-09 12:31:58 +00002221 // If the switch has more than 5 blocks, and at least 40% dense, and the
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00002222 // target supports indirect branches, then emit a jump table rather than
2223 // lowering the switch to a binary tree of conditional branches.
Anton Korobeynikovdd433212007-03-27 12:05:48 +00002224 if (handleJTSwitchCase(CR, WorkList, SV, Default))
2225 continue;
2226
2227 // Emit binary tree. We need to pick a pivot, and push left and right ranges
2228 // onto the worklist. Leafs are handled via handleSmallSwitchRange() call.
2229 handleBTSplitSwitchCase(CR, WorkList, SV, Default);
Nate Begemanf15485a2006-03-27 01:32:24 +00002230 }
2231}
2232
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00002233
Chris Lattnerb9fccc42005-04-02 05:04:50 +00002234void SelectionDAGLowering::visitSub(User &I) {
2235 // -0.0 - X --> fneg
Reid Spencer24d6da52007-01-21 00:29:26 +00002236 const Type *Ty = I.getType();
Reid Spencer9d6565a2007-02-15 02:26:10 +00002237 if (isa<VectorType>(Ty)) {
Dan Gohman7f321562007-06-25 16:23:39 +00002238 if (ConstantVector *CV = dyn_cast<ConstantVector>(I.getOperand(0))) {
2239 const VectorType *DestTy = cast<VectorType>(I.getType());
2240 const Type *ElTy = DestTy->getElementType();
Evan Chengc45453f2007-06-29 21:44:35 +00002241 if (ElTy->isFloatingPoint()) {
2242 unsigned VL = DestTy->getNumElements();
Dale Johannesen9e3d3ab2007-09-14 22:26:36 +00002243 std::vector<Constant*> NZ(VL, ConstantFP::getNegativeZero(ElTy));
Evan Chengc45453f2007-06-29 21:44:35 +00002244 Constant *CNZ = ConstantVector::get(&NZ[0], NZ.size());
2245 if (CV == CNZ) {
2246 SDOperand Op2 = getValue(I.getOperand(1));
2247 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
2248 return;
2249 }
Dan Gohman7f321562007-06-25 16:23:39 +00002250 }
2251 }
2252 }
2253 if (Ty->isFloatingPoint()) {
Chris Lattner01b3d732005-09-28 22:28:18 +00002254 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
Dale Johannesen9e3d3ab2007-09-14 22:26:36 +00002255 if (CFP->isExactlyValue(ConstantFP::getNegativeZero(Ty)->getValueAPF())) {
Chris Lattner01b3d732005-09-28 22:28:18 +00002256 SDOperand Op2 = getValue(I.getOperand(1));
2257 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
2258 return;
2259 }
Dan Gohman7f321562007-06-25 16:23:39 +00002260 }
2261
2262 visitBinary(I, Ty->isFPOrFPVector() ? ISD::FSUB : ISD::SUB);
Chris Lattnerb9fccc42005-04-02 05:04:50 +00002263}
2264
Dan Gohman7f321562007-06-25 16:23:39 +00002265void SelectionDAGLowering::visitBinary(User &I, unsigned OpCode) {
Chris Lattner1c08c712005-01-07 07:47:53 +00002266 SDOperand Op1 = getValue(I.getOperand(0));
2267 SDOperand Op2 = getValue(I.getOperand(1));
Reid Spencer24d6da52007-01-21 00:29:26 +00002268
2269 setValue(&I, DAG.getNode(OpCode, Op1.getValueType(), Op1, Op2));
Reid Spencer1628cec2006-10-26 06:15:43 +00002270}
2271
Nate Begemane21ea612005-11-18 07:42:56 +00002272void SelectionDAGLowering::visitShift(User &I, unsigned Opcode) {
2273 SDOperand Op1 = getValue(I.getOperand(0));
2274 SDOperand Op2 = getValue(I.getOperand(1));
2275
Duncan Sands83ec4b62008-06-06 12:08:01 +00002276 if (TLI.getShiftAmountTy().getSizeInBits() <
2277 Op2.getValueType().getSizeInBits())
Reid Spencer832254e2007-02-02 02:16:23 +00002278 Op2 = DAG.getNode(ISD::TRUNCATE, TLI.getShiftAmountTy(), Op2);
2279 else if (TLI.getShiftAmountTy() > Op2.getValueType())
2280 Op2 = DAG.getNode(ISD::ANY_EXTEND, TLI.getShiftAmountTy(), Op2);
Nate Begemane21ea612005-11-18 07:42:56 +00002281
Chris Lattner1c08c712005-01-07 07:47:53 +00002282 setValue(&I, DAG.getNode(Opcode, Op1.getValueType(), Op1, Op2));
2283}
2284
Reid Spencer45fb3f32006-11-20 01:22:35 +00002285void SelectionDAGLowering::visitICmp(User &I) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002286 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
2287 if (ICmpInst *IC = dyn_cast<ICmpInst>(&I))
2288 predicate = IC->getPredicate();
2289 else if (ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
2290 predicate = ICmpInst::Predicate(IC->getPredicate());
2291 SDOperand Op1 = getValue(I.getOperand(0));
2292 SDOperand Op2 = getValue(I.getOperand(1));
Reid Spencer45fb3f32006-11-20 01:22:35 +00002293 ISD::CondCode Opcode;
Reid Spencere4d87aa2006-12-23 06:05:41 +00002294 switch (predicate) {
Reid Spencer45fb3f32006-11-20 01:22:35 +00002295 case ICmpInst::ICMP_EQ : Opcode = ISD::SETEQ; break;
2296 case ICmpInst::ICMP_NE : Opcode = ISD::SETNE; break;
2297 case ICmpInst::ICMP_UGT : Opcode = ISD::SETUGT; break;
2298 case ICmpInst::ICMP_UGE : Opcode = ISD::SETUGE; break;
2299 case ICmpInst::ICMP_ULT : Opcode = ISD::SETULT; break;
2300 case ICmpInst::ICMP_ULE : Opcode = ISD::SETULE; break;
2301 case ICmpInst::ICMP_SGT : Opcode = ISD::SETGT; break;
2302 case ICmpInst::ICMP_SGE : Opcode = ISD::SETGE; break;
2303 case ICmpInst::ICMP_SLT : Opcode = ISD::SETLT; break;
2304 case ICmpInst::ICMP_SLE : Opcode = ISD::SETLE; break;
2305 default:
2306 assert(!"Invalid ICmp predicate value");
2307 Opcode = ISD::SETEQ;
2308 break;
2309 }
2310 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Opcode));
2311}
2312
2313void SelectionDAGLowering::visitFCmp(User &I) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002314 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
2315 if (FCmpInst *FC = dyn_cast<FCmpInst>(&I))
2316 predicate = FC->getPredicate();
2317 else if (ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
2318 predicate = FCmpInst::Predicate(FC->getPredicate());
Chris Lattner1c08c712005-01-07 07:47:53 +00002319 SDOperand Op1 = getValue(I.getOperand(0));
2320 SDOperand Op2 = getValue(I.getOperand(1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00002321 ISD::CondCode Condition, FOC, FPC;
2322 switch (predicate) {
2323 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
2324 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
2325 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
2326 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
2327 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
2328 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
2329 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
Dan Gohmancba3b442008-05-01 23:40:44 +00002330 case FCmpInst::FCMP_ORD: FOC = FPC = ISD::SETO; break;
2331 case FCmpInst::FCMP_UNO: FOC = FPC = ISD::SETUO; break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00002332 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
2333 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
2334 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
2335 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
2336 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
2337 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
2338 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
2339 default:
2340 assert(!"Invalid FCmp predicate value");
2341 FOC = FPC = ISD::SETFALSE;
2342 break;
2343 }
2344 if (FiniteOnlyFPMath())
2345 Condition = FOC;
2346 else
2347 Condition = FPC;
2348 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Condition));
Chris Lattner1c08c712005-01-07 07:47:53 +00002349}
2350
Nate Begemanb43e9c12008-05-12 19:40:03 +00002351void SelectionDAGLowering::visitVICmp(User &I) {
2352 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
2353 if (VICmpInst *IC = dyn_cast<VICmpInst>(&I))
2354 predicate = IC->getPredicate();
2355 else if (ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
2356 predicate = ICmpInst::Predicate(IC->getPredicate());
2357 SDOperand Op1 = getValue(I.getOperand(0));
2358 SDOperand Op2 = getValue(I.getOperand(1));
2359 ISD::CondCode Opcode;
2360 switch (predicate) {
2361 case ICmpInst::ICMP_EQ : Opcode = ISD::SETEQ; break;
2362 case ICmpInst::ICMP_NE : Opcode = ISD::SETNE; break;
2363 case ICmpInst::ICMP_UGT : Opcode = ISD::SETUGT; break;
2364 case ICmpInst::ICMP_UGE : Opcode = ISD::SETUGE; break;
2365 case ICmpInst::ICMP_ULT : Opcode = ISD::SETULT; break;
2366 case ICmpInst::ICMP_ULE : Opcode = ISD::SETULE; break;
2367 case ICmpInst::ICMP_SGT : Opcode = ISD::SETGT; break;
2368 case ICmpInst::ICMP_SGE : Opcode = ISD::SETGE; break;
2369 case ICmpInst::ICMP_SLT : Opcode = ISD::SETLT; break;
2370 case ICmpInst::ICMP_SLE : Opcode = ISD::SETLE; break;
2371 default:
2372 assert(!"Invalid ICmp predicate value");
2373 Opcode = ISD::SETEQ;
2374 break;
2375 }
2376 setValue(&I, DAG.getVSetCC(Op1.getValueType(), Op1, Op2, Opcode));
2377}
2378
2379void SelectionDAGLowering::visitVFCmp(User &I) {
2380 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
2381 if (VFCmpInst *FC = dyn_cast<VFCmpInst>(&I))
2382 predicate = FC->getPredicate();
2383 else if (ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
2384 predicate = FCmpInst::Predicate(FC->getPredicate());
2385 SDOperand Op1 = getValue(I.getOperand(0));
2386 SDOperand Op2 = getValue(I.getOperand(1));
2387 ISD::CondCode Condition, FOC, FPC;
2388 switch (predicate) {
2389 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
2390 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
2391 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
2392 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
2393 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
2394 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
2395 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
2396 case FCmpInst::FCMP_ORD: FOC = FPC = ISD::SETO; break;
2397 case FCmpInst::FCMP_UNO: FOC = FPC = ISD::SETUO; break;
2398 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
2399 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
2400 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
2401 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
2402 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
2403 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
2404 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
2405 default:
2406 assert(!"Invalid VFCmp predicate value");
2407 FOC = FPC = ISD::SETFALSE;
2408 break;
2409 }
2410 if (FiniteOnlyFPMath())
2411 Condition = FOC;
2412 else
2413 Condition = FPC;
2414
Duncan Sands83ec4b62008-06-06 12:08:01 +00002415 MVT DestVT = TLI.getValueType(I.getType());
Nate Begemanb43e9c12008-05-12 19:40:03 +00002416
2417 setValue(&I, DAG.getVSetCC(DestVT, Op1, Op2, Condition));
2418}
2419
Chris Lattner1c08c712005-01-07 07:47:53 +00002420void SelectionDAGLowering::visitSelect(User &I) {
2421 SDOperand Cond = getValue(I.getOperand(0));
2422 SDOperand TrueVal = getValue(I.getOperand(1));
2423 SDOperand FalseVal = getValue(I.getOperand(2));
Dan Gohman7f321562007-06-25 16:23:39 +00002424 setValue(&I, DAG.getNode(ISD::SELECT, TrueVal.getValueType(), Cond,
2425 TrueVal, FalseVal));
Chris Lattner1c08c712005-01-07 07:47:53 +00002426}
2427
Reid Spencer3da59db2006-11-27 01:05:10 +00002428
2429void SelectionDAGLowering::visitTrunc(User &I) {
2430 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
2431 SDOperand N = getValue(I.getOperand(0));
Duncan Sands83ec4b62008-06-06 12:08:01 +00002432 MVT DestVT = TLI.getValueType(I.getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00002433 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
2434}
2435
2436void SelectionDAGLowering::visitZExt(User &I) {
2437 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2438 // ZExt also can't be a cast to bool for same reason. So, nothing much to do
2439 SDOperand N = getValue(I.getOperand(0));
Duncan Sands83ec4b62008-06-06 12:08:01 +00002440 MVT DestVT = TLI.getValueType(I.getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00002441 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
2442}
2443
2444void SelectionDAGLowering::visitSExt(User &I) {
2445 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2446 // SExt also can't be a cast to bool for same reason. So, nothing much to do
2447 SDOperand N = getValue(I.getOperand(0));
Duncan Sands83ec4b62008-06-06 12:08:01 +00002448 MVT DestVT = TLI.getValueType(I.getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00002449 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, DestVT, N));
2450}
2451
2452void SelectionDAGLowering::visitFPTrunc(User &I) {
2453 // FPTrunc is never a no-op cast, no need to check
2454 SDOperand N = getValue(I.getOperand(0));
Duncan Sands83ec4b62008-06-06 12:08:01 +00002455 MVT DestVT = TLI.getValueType(I.getType());
Chris Lattner0bd48932008-01-17 07:00:52 +00002456 setValue(&I, DAG.getNode(ISD::FP_ROUND, DestVT, N, DAG.getIntPtrConstant(0)));
Reid Spencer3da59db2006-11-27 01:05:10 +00002457}
2458
2459void SelectionDAGLowering::visitFPExt(User &I){
2460 // FPTrunc is never a no-op cast, no need to check
2461 SDOperand N = getValue(I.getOperand(0));
Duncan Sands83ec4b62008-06-06 12:08:01 +00002462 MVT DestVT = TLI.getValueType(I.getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00002463 setValue(&I, DAG.getNode(ISD::FP_EXTEND, DestVT, N));
2464}
2465
2466void SelectionDAGLowering::visitFPToUI(User &I) {
2467 // FPToUI is never a no-op cast, no need to check
2468 SDOperand N = getValue(I.getOperand(0));
Duncan Sands83ec4b62008-06-06 12:08:01 +00002469 MVT DestVT = TLI.getValueType(I.getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00002470 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, DestVT, N));
2471}
2472
2473void SelectionDAGLowering::visitFPToSI(User &I) {
2474 // FPToSI is never a no-op cast, no need to check
2475 SDOperand N = getValue(I.getOperand(0));
Duncan Sands83ec4b62008-06-06 12:08:01 +00002476 MVT DestVT = TLI.getValueType(I.getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00002477 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, DestVT, N));
2478}
2479
2480void SelectionDAGLowering::visitUIToFP(User &I) {
2481 // UIToFP is never a no-op cast, no need to check
2482 SDOperand N = getValue(I.getOperand(0));
Duncan Sands83ec4b62008-06-06 12:08:01 +00002483 MVT DestVT = TLI.getValueType(I.getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00002484 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, DestVT, N));
2485}
2486
2487void SelectionDAGLowering::visitSIToFP(User &I){
2488 // UIToFP is never a no-op cast, no need to check
2489 SDOperand N = getValue(I.getOperand(0));
Duncan Sands83ec4b62008-06-06 12:08:01 +00002490 MVT DestVT = TLI.getValueType(I.getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00002491 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, DestVT, N));
2492}
2493
2494void SelectionDAGLowering::visitPtrToInt(User &I) {
2495 // What to do depends on the size of the integer and the size of the pointer.
2496 // We can either truncate, zero extend, or no-op, accordingly.
Chris Lattner1c08c712005-01-07 07:47:53 +00002497 SDOperand N = getValue(I.getOperand(0));
Duncan Sands83ec4b62008-06-06 12:08:01 +00002498 MVT SrcVT = N.getValueType();
2499 MVT DestVT = TLI.getValueType(I.getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00002500 SDOperand Result;
Duncan Sands83ec4b62008-06-06 12:08:01 +00002501 if (DestVT.getSizeInBits() < SrcVT.getSizeInBits())
Reid Spencer3da59db2006-11-27 01:05:10 +00002502 Result = DAG.getNode(ISD::TRUNCATE, DestVT, N);
2503 else
2504 // Note: ZERO_EXTEND can handle cases where the sizes are equal too
2505 Result = DAG.getNode(ISD::ZERO_EXTEND, DestVT, N);
2506 setValue(&I, Result);
2507}
Chris Lattner1c08c712005-01-07 07:47:53 +00002508
Reid Spencer3da59db2006-11-27 01:05:10 +00002509void SelectionDAGLowering::visitIntToPtr(User &I) {
2510 // What to do depends on the size of the integer and the size of the pointer.
2511 // We can either truncate, zero extend, or no-op, accordingly.
2512 SDOperand N = getValue(I.getOperand(0));
Duncan Sands83ec4b62008-06-06 12:08:01 +00002513 MVT SrcVT = N.getValueType();
2514 MVT DestVT = TLI.getValueType(I.getType());
2515 if (DestVT.getSizeInBits() < SrcVT.getSizeInBits())
Reid Spencer3da59db2006-11-27 01:05:10 +00002516 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
2517 else
2518 // Note: ZERO_EXTEND can handle cases where the sizes are equal too
2519 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
2520}
2521
2522void SelectionDAGLowering::visitBitCast(User &I) {
2523 SDOperand N = getValue(I.getOperand(0));
Duncan Sands83ec4b62008-06-06 12:08:01 +00002524 MVT DestVT = TLI.getValueType(I.getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00002525
2526 // BitCast assures us that source and destination are the same size so this
2527 // is either a BIT_CONVERT or a no-op.
2528 if (DestVT != N.getValueType())
2529 setValue(&I, DAG.getNode(ISD::BIT_CONVERT, DestVT, N)); // convert types
2530 else
2531 setValue(&I, N); // noop cast.
Chris Lattner1c08c712005-01-07 07:47:53 +00002532}
2533
Chris Lattner2bbd8102006-03-29 00:11:43 +00002534void SelectionDAGLowering::visitInsertElement(User &I) {
Chris Lattnerc7029802006-03-18 01:44:44 +00002535 SDOperand InVec = getValue(I.getOperand(0));
2536 SDOperand InVal = getValue(I.getOperand(1));
2537 SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
2538 getValue(I.getOperand(2)));
2539
Dan Gohman7f321562007-06-25 16:23:39 +00002540 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT,
2541 TLI.getValueType(I.getType()),
2542 InVec, InVal, InIdx));
Chris Lattnerc7029802006-03-18 01:44:44 +00002543}
2544
Chris Lattner2bbd8102006-03-29 00:11:43 +00002545void SelectionDAGLowering::visitExtractElement(User &I) {
Chris Lattner384504c2006-03-21 20:44:12 +00002546 SDOperand InVec = getValue(I.getOperand(0));
2547 SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
2548 getValue(I.getOperand(1)));
Dan Gohman7f321562007-06-25 16:23:39 +00002549 setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
Chris Lattner384504c2006-03-21 20:44:12 +00002550 TLI.getValueType(I.getType()), InVec, InIdx));
2551}
Chris Lattnerc7029802006-03-18 01:44:44 +00002552
Chris Lattner3e104b12006-04-08 04:15:24 +00002553void SelectionDAGLowering::visitShuffleVector(User &I) {
2554 SDOperand V1 = getValue(I.getOperand(0));
2555 SDOperand V2 = getValue(I.getOperand(1));
2556 SDOperand Mask = getValue(I.getOperand(2));
2557
Dan Gohman7f321562007-06-25 16:23:39 +00002558 setValue(&I, DAG.getNode(ISD::VECTOR_SHUFFLE,
2559 TLI.getValueType(I.getType()),
2560 V1, V2, Mask));
Chris Lattner3e104b12006-04-08 04:15:24 +00002561}
2562
Dan Gohman041e2eb2008-05-15 19:50:34 +00002563void SelectionDAGLowering::visitInsertValue(User &I) {
2564 assert(0 && "insertvalue instruction not implemented");
2565 abort();
2566}
2567
2568void SelectionDAGLowering::visitExtractValue(User &I) {
2569 assert(0 && "extractvalue instruction not implemented");
2570 abort();
2571}
2572
Chris Lattner3e104b12006-04-08 04:15:24 +00002573
Chris Lattner1c08c712005-01-07 07:47:53 +00002574void SelectionDAGLowering::visitGetElementPtr(User &I) {
2575 SDOperand N = getValue(I.getOperand(0));
2576 const Type *Ty = I.getOperand(0)->getType();
Chris Lattner1c08c712005-01-07 07:47:53 +00002577
2578 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
2579 OI != E; ++OI) {
2580 Value *Idx = *OI;
Chris Lattnerc88d8e92005-12-05 07:10:48 +00002581 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002582 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
Chris Lattner1c08c712005-01-07 07:47:53 +00002583 if (Field) {
2584 // N = N + Offset
Chris Lattnerb1919e22007-02-10 19:55:17 +00002585 uint64_t Offset = TD->getStructLayout(StTy)->getElementOffset(Field);
Chris Lattner1c08c712005-01-07 07:47:53 +00002586 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
Chris Lattner0bd48932008-01-17 07:00:52 +00002587 DAG.getIntPtrConstant(Offset));
Chris Lattner1c08c712005-01-07 07:47:53 +00002588 }
2589 Ty = StTy->getElementType(Field);
2590 } else {
2591 Ty = cast<SequentialType>(Ty)->getElementType();
Chris Lattner7cc47772005-01-07 21:56:57 +00002592
Chris Lattner7c0104b2005-11-09 04:45:33 +00002593 // If this is a constant subscript, handle it quickly.
2594 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002595 if (CI->getZExtValue() == 0) continue;
Reid Spencer47857812006-12-31 05:55:36 +00002596 uint64_t Offs =
Dale Johannesena7ac2bd2007-10-01 23:08:35 +00002597 TD->getABITypeSize(Ty)*cast<ConstantInt>(CI)->getSExtValue();
Chris Lattner0bd48932008-01-17 07:00:52 +00002598 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
2599 DAG.getIntPtrConstant(Offs));
Chris Lattner7c0104b2005-11-09 04:45:33 +00002600 continue;
Chris Lattner1c08c712005-01-07 07:47:53 +00002601 }
Chris Lattner7c0104b2005-11-09 04:45:33 +00002602
2603 // N = N + Idx * ElementSize;
Dale Johannesena7ac2bd2007-10-01 23:08:35 +00002604 uint64_t ElementSize = TD->getABITypeSize(Ty);
Chris Lattner7c0104b2005-11-09 04:45:33 +00002605 SDOperand IdxN = getValue(Idx);
2606
2607 // If the index is smaller or larger than intptr_t, truncate or extend
2608 // it.
2609 if (IdxN.getValueType() < N.getValueType()) {
Reid Spencer47857812006-12-31 05:55:36 +00002610 IdxN = DAG.getNode(ISD::SIGN_EXTEND, N.getValueType(), IdxN);
Chris Lattner7c0104b2005-11-09 04:45:33 +00002611 } else if (IdxN.getValueType() > N.getValueType())
2612 IdxN = DAG.getNode(ISD::TRUNCATE, N.getValueType(), IdxN);
2613
2614 // If this is a multiply by a power of two, turn it into a shl
2615 // immediately. This is a very common case.
2616 if (isPowerOf2_64(ElementSize)) {
2617 unsigned Amt = Log2_64(ElementSize);
2618 IdxN = DAG.getNode(ISD::SHL, N.getValueType(), IdxN,
Chris Lattner6b2d6962005-11-09 16:50:40 +00002619 DAG.getConstant(Amt, TLI.getShiftAmountTy()));
Chris Lattner7c0104b2005-11-09 04:45:33 +00002620 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
2621 continue;
2622 }
2623
Chris Lattner0bd48932008-01-17 07:00:52 +00002624 SDOperand Scale = DAG.getIntPtrConstant(ElementSize);
Chris Lattner7c0104b2005-11-09 04:45:33 +00002625 IdxN = DAG.getNode(ISD::MUL, N.getValueType(), IdxN, Scale);
2626 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
Chris Lattner1c08c712005-01-07 07:47:53 +00002627 }
2628 }
2629 setValue(&I, N);
2630}
2631
2632void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
2633 // If this is a fixed sized alloca in the entry block of the function,
2634 // allocate it statically on the stack.
2635 if (FuncInfo.StaticAllocaMap.count(&I))
2636 return; // getValue will auto-populate this.
2637
2638 const Type *Ty = I.getAllocatedType();
Duncan Sands514ab342007-11-01 20:53:16 +00002639 uint64_t TySize = TLI.getTargetData()->getABITypeSize(Ty);
Chris Lattner58092e32007-01-20 22:35:55 +00002640 unsigned Align =
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00002641 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
Chris Lattner58092e32007-01-20 22:35:55 +00002642 I.getAlignment());
Chris Lattner1c08c712005-01-07 07:47:53 +00002643
2644 SDOperand AllocSize = getValue(I.getArraySize());
Duncan Sands83ec4b62008-06-06 12:08:01 +00002645 MVT IntPtr = TLI.getPointerTy();
Chris Lattner68cd65e2005-01-22 23:04:37 +00002646 if (IntPtr < AllocSize.getValueType())
2647 AllocSize = DAG.getNode(ISD::TRUNCATE, IntPtr, AllocSize);
2648 else if (IntPtr > AllocSize.getValueType())
2649 AllocSize = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, AllocSize);
Chris Lattner1c08c712005-01-07 07:47:53 +00002650
Chris Lattner68cd65e2005-01-22 23:04:37 +00002651 AllocSize = DAG.getNode(ISD::MUL, IntPtr, AllocSize,
Chris Lattner0bd48932008-01-17 07:00:52 +00002652 DAG.getIntPtrConstant(TySize));
Chris Lattner1c08c712005-01-07 07:47:53 +00002653
Evan Cheng45157792007-08-16 23:46:29 +00002654 // Handle alignment. If the requested alignment is less than or equal to
2655 // the stack alignment, ignore it. If the size is greater than or equal to
2656 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
Chris Lattner1c08c712005-01-07 07:47:53 +00002657 unsigned StackAlign =
2658 TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
Evan Cheng45157792007-08-16 23:46:29 +00002659 if (Align <= StackAlign)
Chris Lattner1c08c712005-01-07 07:47:53 +00002660 Align = 0;
Evan Cheng45157792007-08-16 23:46:29 +00002661
2662 // Round the size of the allocation up to the stack alignment size
2663 // by add SA-1 to the size.
2664 AllocSize = DAG.getNode(ISD::ADD, AllocSize.getValueType(), AllocSize,
Chris Lattner0bd48932008-01-17 07:00:52 +00002665 DAG.getIntPtrConstant(StackAlign-1));
Evan Cheng45157792007-08-16 23:46:29 +00002666 // Mask out the low bits for alignment purposes.
2667 AllocSize = DAG.getNode(ISD::AND, AllocSize.getValueType(), AllocSize,
Chris Lattner0bd48932008-01-17 07:00:52 +00002668 DAG.getIntPtrConstant(~(uint64_t)(StackAlign-1)));
Chris Lattner1c08c712005-01-07 07:47:53 +00002669
Chris Lattner0bd48932008-01-17 07:00:52 +00002670 SDOperand Ops[] = { getRoot(), AllocSize, DAG.getIntPtrConstant(Align) };
Duncan Sands83ec4b62008-06-06 12:08:01 +00002671 const MVT *VTs = DAG.getNodeValueTypes(AllocSize.getValueType(),
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00002672 MVT::Other);
2673 SDOperand DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, VTs, 2, Ops, 3);
Chris Lattner0da331f2007-02-04 01:31:47 +00002674 setValue(&I, DSA);
2675 DAG.setRoot(DSA.getValue(1));
Chris Lattner1c08c712005-01-07 07:47:53 +00002676
2677 // Inform the Frame Information that we have just allocated a variable-sized
2678 // object.
2679 CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
2680}
2681
Chris Lattner1c08c712005-01-07 07:47:53 +00002682void SelectionDAGLowering::visitLoad(LoadInst &I) {
2683 SDOperand Ptr = getValue(I.getOperand(0));
Misha Brukmanedf128a2005-04-21 22:36:52 +00002684
Chris Lattnerd3948112005-01-17 22:19:26 +00002685 SDOperand Root;
2686 if (I.isVolatile())
2687 Root = getRoot();
2688 else {
2689 // Do not serialize non-volatile loads against each other.
2690 Root = DAG.getRoot();
2691 }
Chris Lattner28b5b1c2006-03-15 22:19:46 +00002692
Evan Cheng466685d2006-10-09 20:57:25 +00002693 setValue(&I, getLoadFrom(I.getType(), Ptr, I.getOperand(0),
Christopher Lamb95c218a2007-04-22 23:15:30 +00002694 Root, I.isVolatile(), I.getAlignment()));
Chris Lattner28b5b1c2006-03-15 22:19:46 +00002695}
2696
2697SDOperand SelectionDAGLowering::getLoadFrom(const Type *Ty, SDOperand Ptr,
Evan Cheng466685d2006-10-09 20:57:25 +00002698 const Value *SV, SDOperand Root,
Christopher Lamb95c218a2007-04-22 23:15:30 +00002699 bool isVolatile,
2700 unsigned Alignment) {
Dan Gohman7f321562007-06-25 16:23:39 +00002701 SDOperand L =
2702 DAG.getLoad(TLI.getValueType(Ty), Root, Ptr, SV, 0,
2703 isVolatile, Alignment);
Chris Lattnerd3948112005-01-17 22:19:26 +00002704
Chris Lattner28b5b1c2006-03-15 22:19:46 +00002705 if (isVolatile)
Chris Lattnerd3948112005-01-17 22:19:26 +00002706 DAG.setRoot(L.getValue(1));
2707 else
2708 PendingLoads.push_back(L.getValue(1));
Chris Lattner28b5b1c2006-03-15 22:19:46 +00002709
2710 return L;
Chris Lattner1c08c712005-01-07 07:47:53 +00002711}
2712
2713
2714void SelectionDAGLowering::visitStore(StoreInst &I) {
2715 Value *SrcV = I.getOperand(0);
2716 SDOperand Src = getValue(SrcV);
2717 SDOperand Ptr = getValue(I.getOperand(1));
Evan Cheng0b4f80e2006-12-20 01:27:29 +00002718 DAG.setRoot(DAG.getStore(getRoot(), Src, Ptr, I.getOperand(1), 0,
Christopher Lamb95c218a2007-04-22 23:15:30 +00002719 I.isVolatile(), I.getAlignment()));
Chris Lattner1c08c712005-01-07 07:47:53 +00002720}
2721
Chris Lattner0eade312006-03-24 02:22:33 +00002722/// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
2723/// node.
2724void SelectionDAGLowering::visitTargetIntrinsic(CallInst &I,
2725 unsigned Intrinsic) {
Duncan Sandsa3355ff2007-12-03 20:06:50 +00002726 bool HasChain = !I.doesNotAccessMemory();
2727 bool OnlyLoad = HasChain && I.onlyReadsMemory();
2728
Chris Lattner0eade312006-03-24 02:22:33 +00002729 // Build the operand list.
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002730 SmallVector<SDOperand, 8> Ops;
Chris Lattnere58a7802006-04-02 03:41:14 +00002731 if (HasChain) { // If this intrinsic has side-effects, chainify it.
2732 if (OnlyLoad) {
2733 // We don't need to serialize loads against other loads.
2734 Ops.push_back(DAG.getRoot());
2735 } else {
2736 Ops.push_back(getRoot());
2737 }
2738 }
Chris Lattner0eade312006-03-24 02:22:33 +00002739
2740 // Add the intrinsic ID as an integer operand.
2741 Ops.push_back(DAG.getConstant(Intrinsic, TLI.getPointerTy()));
2742
2743 // Add all operands of the call to the operand list.
2744 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
2745 SDOperand Op = getValue(I.getOperand(i));
Chris Lattner0eade312006-03-24 02:22:33 +00002746 assert(TLI.isTypeLegal(Op.getValueType()) &&
2747 "Intrinsic uses a non-legal type?");
2748 Ops.push_back(Op);
2749 }
2750
Duncan Sands83ec4b62008-06-06 12:08:01 +00002751 std::vector<MVT> VTs;
Chris Lattner0eade312006-03-24 02:22:33 +00002752 if (I.getType() != Type::VoidTy) {
Duncan Sands83ec4b62008-06-06 12:08:01 +00002753 MVT VT = TLI.getValueType(I.getType());
2754 if (VT.isVector()) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00002755 const VectorType *DestTy = cast<VectorType>(I.getType());
Duncan Sands83ec4b62008-06-06 12:08:01 +00002756 MVT EltVT = TLI.getValueType(DestTy->getElementType());
Chris Lattner0eade312006-03-24 02:22:33 +00002757
Duncan Sands83ec4b62008-06-06 12:08:01 +00002758 VT = MVT::getVectorVT(EltVT, DestTy->getNumElements());
Chris Lattner0eade312006-03-24 02:22:33 +00002759 assert(VT != MVT::Other && "Intrinsic uses a non-legal type?");
2760 }
2761
2762 assert(TLI.isTypeLegal(VT) && "Intrinsic uses a non-legal type?");
2763 VTs.push_back(VT);
2764 }
2765 if (HasChain)
2766 VTs.push_back(MVT::Other);
2767
Duncan Sands83ec4b62008-06-06 12:08:01 +00002768 const MVT *VTList = DAG.getNodeValueTypes(VTs);
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00002769
Chris Lattner0eade312006-03-24 02:22:33 +00002770 // Create the node.
Chris Lattner48b61a72006-03-28 00:40:33 +00002771 SDOperand Result;
2772 if (!HasChain)
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00002773 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VTList, VTs.size(),
2774 &Ops[0], Ops.size());
Chris Lattner48b61a72006-03-28 00:40:33 +00002775 else if (I.getType() != Type::VoidTy)
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00002776 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, VTList, VTs.size(),
2777 &Ops[0], Ops.size());
Chris Lattner48b61a72006-03-28 00:40:33 +00002778 else
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00002779 Result = DAG.getNode(ISD::INTRINSIC_VOID, VTList, VTs.size(),
2780 &Ops[0], Ops.size());
Chris Lattner48b61a72006-03-28 00:40:33 +00002781
Chris Lattnere58a7802006-04-02 03:41:14 +00002782 if (HasChain) {
2783 SDOperand Chain = Result.getValue(Result.Val->getNumValues()-1);
2784 if (OnlyLoad)
2785 PendingLoads.push_back(Chain);
2786 else
2787 DAG.setRoot(Chain);
2788 }
Chris Lattner0eade312006-03-24 02:22:33 +00002789 if (I.getType() != Type::VoidTy) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00002790 if (const VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
Duncan Sands83ec4b62008-06-06 12:08:01 +00002791 MVT VT = TLI.getValueType(PTy);
Dan Gohman7f321562007-06-25 16:23:39 +00002792 Result = DAG.getNode(ISD::BIT_CONVERT, VT, Result);
Chris Lattner0eade312006-03-24 02:22:33 +00002793 }
2794 setValue(&I, Result);
2795 }
2796}
2797
Duncan Sandsb4fd45e2007-07-06 09:10:03 +00002798/// ExtractTypeInfo - Returns the type info, possibly bitcast, encoded in V.
Duncan Sandscf26d7c2007-07-04 20:52:51 +00002799static GlobalVariable *ExtractTypeInfo (Value *V) {
Anton Korobeynikov0b12ecf2008-05-07 22:54:15 +00002800 V = V->stripPointerCasts();
Duncan Sandsb4fd45e2007-07-06 09:10:03 +00002801 GlobalVariable *GV = dyn_cast<GlobalVariable>(V);
Anton Korobeynikov4c71dfe2008-02-20 11:10:28 +00002802 assert ((GV || isa<ConstantPointerNull>(V)) &&
Duncan Sandscf26d7c2007-07-04 20:52:51 +00002803 "TypeInfo must be a global variable or NULL");
2804 return GV;
2805}
2806
Duncan Sandsf4070822007-06-15 19:04:19 +00002807/// addCatchInfo - Extract the personality and type infos from an eh.selector
Duncan Sandscf26d7c2007-07-04 20:52:51 +00002808/// call, and add them to the specified machine basic block.
Duncan Sandsf4070822007-06-15 19:04:19 +00002809static void addCatchInfo(CallInst &I, MachineModuleInfo *MMI,
2810 MachineBasicBlock *MBB) {
2811 // Inform the MachineModuleInfo of the personality for this landing pad.
2812 ConstantExpr *CE = cast<ConstantExpr>(I.getOperand(2));
2813 assert(CE->getOpcode() == Instruction::BitCast &&
2814 isa<Function>(CE->getOperand(0)) &&
2815 "Personality should be a function");
2816 MMI->addPersonality(MBB, cast<Function>(CE->getOperand(0)));
2817
2818 // Gather all the type infos for this landing pad and pass them along to
2819 // MachineModuleInfo.
2820 std::vector<GlobalVariable *> TyInfo;
Duncan Sandscf26d7c2007-07-04 20:52:51 +00002821 unsigned N = I.getNumOperands();
2822
2823 for (unsigned i = N - 1; i > 2; --i) {
2824 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(i))) {
2825 unsigned FilterLength = CI->getZExtValue();
Duncan Sands6590b042007-08-27 15:47:50 +00002826 unsigned FirstCatch = i + FilterLength + !FilterLength;
Duncan Sandscf26d7c2007-07-04 20:52:51 +00002827 assert (FirstCatch <= N && "Invalid filter length");
2828
2829 if (FirstCatch < N) {
2830 TyInfo.reserve(N - FirstCatch);
2831 for (unsigned j = FirstCatch; j < N; ++j)
2832 TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
2833 MMI->addCatchTypeInfo(MBB, TyInfo);
2834 TyInfo.clear();
2835 }
2836
Duncan Sands6590b042007-08-27 15:47:50 +00002837 if (!FilterLength) {
2838 // Cleanup.
2839 MMI->addCleanup(MBB);
2840 } else {
2841 // Filter.
2842 TyInfo.reserve(FilterLength - 1);
2843 for (unsigned j = i + 1; j < FirstCatch; ++j)
2844 TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
2845 MMI->addFilterTypeInfo(MBB, TyInfo);
2846 TyInfo.clear();
2847 }
Duncan Sandscf26d7c2007-07-04 20:52:51 +00002848
2849 N = i;
2850 }
Duncan Sandsf4070822007-06-15 19:04:19 +00002851 }
Duncan Sandscf26d7c2007-07-04 20:52:51 +00002852
2853 if (N > 3) {
2854 TyInfo.reserve(N - 3);
2855 for (unsigned j = 3; j < N; ++j)
2856 TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
Duncan Sandsf4070822007-06-15 19:04:19 +00002857 MMI->addCatchTypeInfo(MBB, TyInfo);
Duncan Sandscf26d7c2007-07-04 20:52:51 +00002858 }
Duncan Sandsf4070822007-06-15 19:04:19 +00002859}
2860
Mon P Wang63307c32008-05-05 19:05:59 +00002861
2862/// Inlined utility function to implement binary input atomic intrinsics for
2863// visitIntrinsicCall: I is a call instruction
2864// Op is the associated NodeType for I
2865const char *
2866SelectionDAGLowering::implVisitBinaryAtomic(CallInst& I, ISD::NodeType Op) {
2867 SDOperand Root = getRoot();
2868 SDOperand O2 = getValue(I.getOperand(2));
2869 SDOperand L = DAG.getAtomic(Op, Root,
2870 getValue(I.getOperand(1)),
2871 O2, O2.getValueType());
2872 setValue(&I, L);
2873 DAG.setRoot(L.getValue(1));
2874 return 0;
2875}
2876
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002877/// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
2878/// we want to emit this as a call to a named external function, return the name
2879/// otherwise lower it and return null.
2880const char *
2881SelectionDAGLowering::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
2882 switch (Intrinsic) {
Chris Lattner0eade312006-03-24 02:22:33 +00002883 default:
2884 // By default, turn this into a target intrinsic node.
2885 visitTargetIntrinsic(I, Intrinsic);
2886 return 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002887 case Intrinsic::vastart: visitVAStart(I); return 0;
2888 case Intrinsic::vaend: visitVAEnd(I); return 0;
2889 case Intrinsic::vacopy: visitVACopy(I); return 0;
Nate Begemanbcc5f362007-01-29 22:58:52 +00002890 case Intrinsic::returnaddress:
2891 setValue(&I, DAG.getNode(ISD::RETURNADDR, TLI.getPointerTy(),
2892 getValue(I.getOperand(1))));
2893 return 0;
2894 case Intrinsic::frameaddress:
2895 setValue(&I, DAG.getNode(ISD::FRAMEADDR, TLI.getPointerTy(),
2896 getValue(I.getOperand(1))));
2897 return 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002898 case Intrinsic::setjmp:
Anton Korobeynikovd27a2582006-12-10 23:12:42 +00002899 return "_setjmp"+!TLI.usesUnderscoreSetJmp();
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002900 break;
2901 case Intrinsic::longjmp:
Anton Korobeynikovd27a2582006-12-10 23:12:42 +00002902 return "_longjmp"+!TLI.usesUnderscoreLongJmp();
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002903 break;
Chris Lattner03dd4652006-03-03 00:00:25 +00002904 case Intrinsic::memcpy_i32:
Dan Gohman707e0182008-04-12 04:36:06 +00002905 case Intrinsic::memcpy_i64: {
2906 SDOperand Op1 = getValue(I.getOperand(1));
2907 SDOperand Op2 = getValue(I.getOperand(2));
2908 SDOperand Op3 = getValue(I.getOperand(3));
2909 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
2910 DAG.setRoot(DAG.getMemcpy(getRoot(), Op1, Op2, Op3, Align, false,
2911 I.getOperand(1), 0, I.getOperand(2), 0));
Chris Lattner03dd4652006-03-03 00:00:25 +00002912 return 0;
Dan Gohman707e0182008-04-12 04:36:06 +00002913 }
Chris Lattner03dd4652006-03-03 00:00:25 +00002914 case Intrinsic::memset_i32:
Dan Gohman707e0182008-04-12 04:36:06 +00002915 case Intrinsic::memset_i64: {
2916 SDOperand Op1 = getValue(I.getOperand(1));
2917 SDOperand Op2 = getValue(I.getOperand(2));
2918 SDOperand Op3 = getValue(I.getOperand(3));
2919 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
2920 DAG.setRoot(DAG.getMemset(getRoot(), Op1, Op2, Op3, Align,
2921 I.getOperand(1), 0));
Chris Lattner03dd4652006-03-03 00:00:25 +00002922 return 0;
Dan Gohman707e0182008-04-12 04:36:06 +00002923 }
Chris Lattner03dd4652006-03-03 00:00:25 +00002924 case Intrinsic::memmove_i32:
Dan Gohman707e0182008-04-12 04:36:06 +00002925 case Intrinsic::memmove_i64: {
2926 SDOperand Op1 = getValue(I.getOperand(1));
2927 SDOperand Op2 = getValue(I.getOperand(2));
2928 SDOperand Op3 = getValue(I.getOperand(3));
2929 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
2930
2931 // If the source and destination are known to not be aliases, we can
2932 // lower memmove as memcpy.
2933 uint64_t Size = -1ULL;
2934 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op3))
2935 Size = C->getValue();
2936 if (AA.alias(I.getOperand(1), Size, I.getOperand(2), Size) ==
2937 AliasAnalysis::NoAlias) {
2938 DAG.setRoot(DAG.getMemcpy(getRoot(), Op1, Op2, Op3, Align, false,
2939 I.getOperand(1), 0, I.getOperand(2), 0));
2940 return 0;
2941 }
2942
2943 DAG.setRoot(DAG.getMemmove(getRoot(), Op1, Op2, Op3, Align,
2944 I.getOperand(1), 0, I.getOperand(2), 0));
Chris Lattner03dd4652006-03-03 00:00:25 +00002945 return 0;
Dan Gohman707e0182008-04-12 04:36:06 +00002946 }
Chris Lattner86cb6432005-12-13 17:40:33 +00002947 case Intrinsic::dbg_stoppoint: {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002948 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskey43970fe2006-03-23 18:06:46 +00002949 DbgStopPointInst &SPI = cast<DbgStopPointInst>(I);
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002950 if (MMI && SPI.getContext() && MMI->Verify(SPI.getContext())) {
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002951 SDOperand Ops[5];
Chris Lattner36ce6912005-11-29 06:21:05 +00002952
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002953 Ops[0] = getRoot();
2954 Ops[1] = getValue(SPI.getLineValue());
2955 Ops[2] = getValue(SPI.getColumnValue());
Chris Lattner36ce6912005-11-29 06:21:05 +00002956
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002957 DebugInfoDesc *DD = MMI->getDescFor(SPI.getContext());
Jim Laskeyce72b172006-02-11 01:01:30 +00002958 assert(DD && "Not a debug information descriptor");
Jim Laskey43970fe2006-03-23 18:06:46 +00002959 CompileUnitDesc *CompileUnit = cast<CompileUnitDesc>(DD);
2960
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002961 Ops[3] = DAG.getString(CompileUnit->getFileName());
2962 Ops[4] = DAG.getString(CompileUnit->getDirectory());
Jim Laskeyce72b172006-02-11 01:01:30 +00002963
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002964 DAG.setRoot(DAG.getNode(ISD::LOCATION, MVT::Other, Ops, 5));
Chris Lattner86cb6432005-12-13 17:40:33 +00002965 }
Jim Laskey43970fe2006-03-23 18:06:46 +00002966
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +00002967 return 0;
Chris Lattner36ce6912005-11-29 06:21:05 +00002968 }
Jim Laskey43970fe2006-03-23 18:06:46 +00002969 case Intrinsic::dbg_region_start: {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002970 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskey43970fe2006-03-23 18:06:46 +00002971 DbgRegionStartInst &RSI = cast<DbgRegionStartInst>(I);
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002972 if (MMI && RSI.getContext() && MMI->Verify(RSI.getContext())) {
2973 unsigned LabelID = MMI->RecordRegionStart(RSI.getContext());
Jim Laskey1ee29252007-01-26 14:34:52 +00002974 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, getRoot(),
Evan Chengbb81d972008-01-31 09:59:15 +00002975 DAG.getConstant(LabelID, MVT::i32),
2976 DAG.getConstant(0, MVT::i32)));
Jim Laskey43970fe2006-03-23 18:06:46 +00002977 }
2978
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +00002979 return 0;
Jim Laskey43970fe2006-03-23 18:06:46 +00002980 }
2981 case Intrinsic::dbg_region_end: {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002982 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskey43970fe2006-03-23 18:06:46 +00002983 DbgRegionEndInst &REI = cast<DbgRegionEndInst>(I);
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002984 if (MMI && REI.getContext() && MMI->Verify(REI.getContext())) {
2985 unsigned LabelID = MMI->RecordRegionEnd(REI.getContext());
Evan Chengbb81d972008-01-31 09:59:15 +00002986 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, getRoot(),
2987 DAG.getConstant(LabelID, MVT::i32),
2988 DAG.getConstant(0, MVT::i32)));
Jim Laskey43970fe2006-03-23 18:06:46 +00002989 }
2990
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +00002991 return 0;
Jim Laskey43970fe2006-03-23 18:06:46 +00002992 }
2993 case Intrinsic::dbg_func_start: {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002994 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Evan Cheng1b08bbc2008-02-01 09:10:45 +00002995 if (!MMI) return 0;
Jim Laskey43970fe2006-03-23 18:06:46 +00002996 DbgFuncStartInst &FSI = cast<DbgFuncStartInst>(I);
Evan Cheng1b08bbc2008-02-01 09:10:45 +00002997 Value *SP = FSI.getSubprogram();
2998 if (SP && MMI->Verify(SP)) {
2999 // llvm.dbg.func.start implicitly defines a dbg_stoppoint which is
3000 // what (most?) gdb expects.
3001 DebugInfoDesc *DD = MMI->getDescFor(SP);
3002 assert(DD && "Not a debug information descriptor");
3003 SubprogramDesc *Subprogram = cast<SubprogramDesc>(DD);
3004 const CompileUnitDesc *CompileUnit = Subprogram->getFile();
3005 unsigned SrcFile = MMI->RecordSource(CompileUnit->getDirectory(),
3006 CompileUnit->getFileName());
3007 // Record the source line but does create a label. It will be emitted
3008 // at asm emission time.
3009 MMI->RecordSourceLine(Subprogram->getLine(), 0, SrcFile);
Jim Laskey43970fe2006-03-23 18:06:46 +00003010 }
3011
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +00003012 return 0;
Jim Laskey43970fe2006-03-23 18:06:46 +00003013 }
3014 case Intrinsic::dbg_declare: {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00003015 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskey43970fe2006-03-23 18:06:46 +00003016 DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
Evan Chenga844bde2008-02-02 04:07:54 +00003017 Value *Variable = DI.getVariable();
3018 if (MMI && Variable && MMI->Verify(Variable))
3019 DAG.setRoot(DAG.getNode(ISD::DECLARE, MVT::Other, getRoot(),
3020 getValue(DI.getAddress()), getValue(Variable)));
Jim Laskey43970fe2006-03-23 18:06:46 +00003021 return 0;
3022 }
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003023
Jim Laskeyb180aa12007-02-21 22:53:45 +00003024 case Intrinsic::eh_exception: {
Dale Johannesen1532f3d2008-04-02 00:25:04 +00003025 if (!CurMBB->isLandingPad()) {
3026 // FIXME: Mark exception register as live in. Hack for PR1508.
3027 unsigned Reg = TLI.getExceptionAddressRegister();
3028 if (Reg) CurMBB->addLiveIn(Reg);
Jim Laskey735b6f82007-02-22 15:38:06 +00003029 }
Dale Johannesen1532f3d2008-04-02 00:25:04 +00003030 // Insert the EXCEPTIONADDR instruction.
3031 SDVTList VTs = DAG.getVTList(TLI.getPointerTy(), MVT::Other);
3032 SDOperand Ops[1];
3033 Ops[0] = DAG.getRoot();
3034 SDOperand Op = DAG.getNode(ISD::EXCEPTIONADDR, VTs, Ops, 1);
3035 setValue(&I, Op);
3036 DAG.setRoot(Op.getValue(1));
Jim Laskeyb180aa12007-02-21 22:53:45 +00003037 return 0;
3038 }
3039
Anton Korobeynikov8806c7b2007-09-07 11:39:35 +00003040 case Intrinsic::eh_selector_i32:
3041 case Intrinsic::eh_selector_i64: {
Jim Laskeyb180aa12007-02-21 22:53:45 +00003042 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Duncan Sands83ec4b62008-06-06 12:08:01 +00003043 MVT VT = (Intrinsic == Intrinsic::eh_selector_i32 ?
Anton Korobeynikov8806c7b2007-09-07 11:39:35 +00003044 MVT::i32 : MVT::i64);
3045
Dale Johannesen1532f3d2008-04-02 00:25:04 +00003046 if (MMI) {
Duncan Sandsf4070822007-06-15 19:04:19 +00003047 if (CurMBB->isLandingPad())
3048 addCatchInfo(I, MMI, CurMBB);
Evan Chenge47c3332007-06-27 18:45:32 +00003049 else {
Duncan Sandsf4070822007-06-15 19:04:19 +00003050#ifndef NDEBUG
Duncan Sandsf4070822007-06-15 19:04:19 +00003051 FuncInfo.CatchInfoLost.insert(&I);
3052#endif
Duncan Sands90291952007-07-06 09:18:59 +00003053 // FIXME: Mark exception selector register as live in. Hack for PR1508.
3054 unsigned Reg = TLI.getExceptionSelectorRegister();
3055 if (Reg) CurMBB->addLiveIn(Reg);
Evan Chenge47c3332007-06-27 18:45:32 +00003056 }
Jim Laskey735b6f82007-02-22 15:38:06 +00003057
3058 // Insert the EHSELECTION instruction.
Anton Korobeynikov8806c7b2007-09-07 11:39:35 +00003059 SDVTList VTs = DAG.getVTList(VT, MVT::Other);
Jim Laskey735b6f82007-02-22 15:38:06 +00003060 SDOperand Ops[2];
3061 Ops[0] = getValue(I.getOperand(1));
3062 Ops[1] = getRoot();
3063 SDOperand Op = DAG.getNode(ISD::EHSELECTION, VTs, Ops, 2);
3064 setValue(&I, Op);
3065 DAG.setRoot(Op.getValue(1));
Jim Laskey7a1de982007-02-24 09:45:44 +00003066 } else {
Anton Korobeynikov8806c7b2007-09-07 11:39:35 +00003067 setValue(&I, DAG.getConstant(0, VT));
Jim Laskey735b6f82007-02-22 15:38:06 +00003068 }
Jim Laskeyb180aa12007-02-21 22:53:45 +00003069
3070 return 0;
3071 }
Anton Korobeynikov8806c7b2007-09-07 11:39:35 +00003072
3073 case Intrinsic::eh_typeid_for_i32:
3074 case Intrinsic::eh_typeid_for_i64: {
Jim Laskeyb180aa12007-02-21 22:53:45 +00003075 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Duncan Sands83ec4b62008-06-06 12:08:01 +00003076 MVT VT = (Intrinsic == Intrinsic::eh_typeid_for_i32 ?
Anton Korobeynikov8806c7b2007-09-07 11:39:35 +00003077 MVT::i32 : MVT::i64);
Jim Laskeyb180aa12007-02-21 22:53:45 +00003078
Jim Laskey735b6f82007-02-22 15:38:06 +00003079 if (MMI) {
3080 // Find the type id for the given typeinfo.
Duncan Sandscf26d7c2007-07-04 20:52:51 +00003081 GlobalVariable *GV = ExtractTypeInfo(I.getOperand(1));
Duncan Sands3b346362007-05-04 17:12:26 +00003082
Jim Laskey735b6f82007-02-22 15:38:06 +00003083 unsigned TypeID = MMI->getTypeIDFor(GV);
Anton Korobeynikov8806c7b2007-09-07 11:39:35 +00003084 setValue(&I, DAG.getConstant(TypeID, VT));
Jim Laskey7a1de982007-02-24 09:45:44 +00003085 } else {
Duncan Sandsf664e412007-07-06 14:46:23 +00003086 // Return something different to eh_selector.
Anton Korobeynikov8806c7b2007-09-07 11:39:35 +00003087 setValue(&I, DAG.getConstant(1, VT));
Jim Laskey735b6f82007-02-22 15:38:06 +00003088 }
Jim Laskeyb180aa12007-02-21 22:53:45 +00003089
3090 return 0;
3091 }
3092
Anton Korobeynikov2365f512007-07-14 14:06:15 +00003093 case Intrinsic::eh_return: {
3094 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3095
Dale Johannesen1532f3d2008-04-02 00:25:04 +00003096 if (MMI) {
Anton Korobeynikov2365f512007-07-14 14:06:15 +00003097 MMI->setCallsEHReturn(true);
3098 DAG.setRoot(DAG.getNode(ISD::EH_RETURN,
3099 MVT::Other,
Dan Gohman86e1ebf2008-03-27 19:56:19 +00003100 getControlRoot(),
Anton Korobeynikov2365f512007-07-14 14:06:15 +00003101 getValue(I.getOperand(1)),
3102 getValue(I.getOperand(2))));
3103 } else {
3104 setValue(&I, DAG.getConstant(0, TLI.getPointerTy()));
3105 }
3106
3107 return 0;
3108 }
3109
3110 case Intrinsic::eh_unwind_init: {
3111 if (MachineModuleInfo *MMI = DAG.getMachineModuleInfo()) {
3112 MMI->setCallsUnwindInit(true);
3113 }
3114
3115 return 0;
3116 }
3117
3118 case Intrinsic::eh_dwarf_cfa: {
Duncan Sands83ec4b62008-06-06 12:08:01 +00003119 MVT VT = getValue(I.getOperand(1)).getValueType();
Dale Johannesen1532f3d2008-04-02 00:25:04 +00003120 SDOperand CfaArg;
Duncan Sands83ec4b62008-06-06 12:08:01 +00003121 if (VT.getSizeInBits() > TLI.getPointerTy().getSizeInBits())
Dale Johannesen1532f3d2008-04-02 00:25:04 +00003122 CfaArg = DAG.getNode(ISD::TRUNCATE,
3123 TLI.getPointerTy(), getValue(I.getOperand(1)));
3124 else
3125 CfaArg = DAG.getNode(ISD::SIGN_EXTEND,
3126 TLI.getPointerTy(), getValue(I.getOperand(1)));
Anton Korobeynikov2365f512007-07-14 14:06:15 +00003127
Dale Johannesen1532f3d2008-04-02 00:25:04 +00003128 SDOperand Offset = DAG.getNode(ISD::ADD,
3129 TLI.getPointerTy(),
3130 DAG.getNode(ISD::FRAME_TO_ARGS_OFFSET,
3131 TLI.getPointerTy()),
3132 CfaArg);
3133 setValue(&I, DAG.getNode(ISD::ADD,
3134 TLI.getPointerTy(),
3135 DAG.getNode(ISD::FRAMEADDR,
3136 TLI.getPointerTy(),
3137 DAG.getConstant(0,
3138 TLI.getPointerTy())),
3139 Offset));
Anton Korobeynikov2365f512007-07-14 14:06:15 +00003140 return 0;
3141 }
3142
Dale Johannesen9ab7fb32007-10-02 17:43:59 +00003143 case Intrinsic::sqrt:
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003144 setValue(&I, DAG.getNode(ISD::FSQRT,
3145 getValue(I.getOperand(1)).getValueType(),
3146 getValue(I.getOperand(1))));
3147 return 0;
Dale Johannesen9ab7fb32007-10-02 17:43:59 +00003148 case Intrinsic::powi:
Chris Lattner6ddf8ed2006-09-09 06:03:30 +00003149 setValue(&I, DAG.getNode(ISD::FPOWI,
3150 getValue(I.getOperand(1)).getValueType(),
3151 getValue(I.getOperand(1)),
3152 getValue(I.getOperand(2))));
3153 return 0;
Dan Gohmanac9385a2007-10-12 00:01:22 +00003154 case Intrinsic::sin:
3155 setValue(&I, DAG.getNode(ISD::FSIN,
3156 getValue(I.getOperand(1)).getValueType(),
3157 getValue(I.getOperand(1))));
3158 return 0;
3159 case Intrinsic::cos:
3160 setValue(&I, DAG.getNode(ISD::FCOS,
3161 getValue(I.getOperand(1)).getValueType(),
3162 getValue(I.getOperand(1))));
3163 return 0;
3164 case Intrinsic::pow:
3165 setValue(&I, DAG.getNode(ISD::FPOW,
3166 getValue(I.getOperand(1)).getValueType(),
3167 getValue(I.getOperand(1)),
3168 getValue(I.getOperand(2))));
3169 return 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003170 case Intrinsic::pcmarker: {
3171 SDOperand Tmp = getValue(I.getOperand(1));
3172 DAG.setRoot(DAG.getNode(ISD::PCMARKER, MVT::Other, getRoot(), Tmp));
3173 return 0;
3174 }
Andrew Lenharth8b91c772005-11-11 22:48:54 +00003175 case Intrinsic::readcyclecounter: {
Chris Lattnerbd564bf2006-08-08 02:23:42 +00003176 SDOperand Op = getRoot();
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00003177 SDOperand Tmp = DAG.getNode(ISD::READCYCLECOUNTER,
3178 DAG.getNodeValueTypes(MVT::i64, MVT::Other), 2,
3179 &Op, 1);
Andrew Lenharth8b91c772005-11-11 22:48:54 +00003180 setValue(&I, Tmp);
3181 DAG.setRoot(Tmp.getValue(1));
Andrew Lenharth51b8d542005-11-11 16:47:30 +00003182 return 0;
Andrew Lenharth8b91c772005-11-11 22:48:54 +00003183 }
Chris Lattnerc6eb6d72007-04-10 03:20:39 +00003184 case Intrinsic::part_select: {
Reid Spencer3f108cb2007-04-05 01:20:18 +00003185 // Currently not implemented: just abort
Reid Spencerf75b8742007-04-12 02:48:46 +00003186 assert(0 && "part_select intrinsic not implemented");
3187 abort();
3188 }
3189 case Intrinsic::part_set: {
3190 // Currently not implemented: just abort
3191 assert(0 && "part_set intrinsic not implemented");
Reid Spencer3f108cb2007-04-05 01:20:18 +00003192 abort();
Reid Spenceraddd11d2007-04-04 23:48:25 +00003193 }
Reid Spencera4f9c4d2007-04-01 07:34:11 +00003194 case Intrinsic::bswap:
Nate Begemand88fc032006-01-14 03:14:10 +00003195 setValue(&I, DAG.getNode(ISD::BSWAP,
3196 getValue(I.getOperand(1)).getValueType(),
3197 getValue(I.getOperand(1))));
3198 return 0;
Reid Spencera4f9c4d2007-04-01 07:34:11 +00003199 case Intrinsic::cttz: {
3200 SDOperand Arg = getValue(I.getOperand(1));
Duncan Sands83ec4b62008-06-06 12:08:01 +00003201 MVT Ty = Arg.getValueType();
Reid Spencera4f9c4d2007-04-01 07:34:11 +00003202 SDOperand result = DAG.getNode(ISD::CTTZ, Ty, Arg);
Reid Spencera4f9c4d2007-04-01 07:34:11 +00003203 setValue(&I, result);
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003204 return 0;
Reid Spencera4f9c4d2007-04-01 07:34:11 +00003205 }
3206 case Intrinsic::ctlz: {
3207 SDOperand Arg = getValue(I.getOperand(1));
Duncan Sands83ec4b62008-06-06 12:08:01 +00003208 MVT Ty = Arg.getValueType();
Reid Spencera4f9c4d2007-04-01 07:34:11 +00003209 SDOperand result = DAG.getNode(ISD::CTLZ, Ty, Arg);
Reid Spencera4f9c4d2007-04-01 07:34:11 +00003210 setValue(&I, result);
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003211 return 0;
Reid Spencera4f9c4d2007-04-01 07:34:11 +00003212 }
3213 case Intrinsic::ctpop: {
3214 SDOperand Arg = getValue(I.getOperand(1));
Duncan Sands83ec4b62008-06-06 12:08:01 +00003215 MVT Ty = Arg.getValueType();
Reid Spencera4f9c4d2007-04-01 07:34:11 +00003216 SDOperand result = DAG.getNode(ISD::CTPOP, Ty, Arg);
Reid Spencera4f9c4d2007-04-01 07:34:11 +00003217 setValue(&I, result);
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003218 return 0;
Reid Spencera4f9c4d2007-04-01 07:34:11 +00003219 }
Chris Lattner140d53c2006-01-13 02:50:02 +00003220 case Intrinsic::stacksave: {
Chris Lattnerbd564bf2006-08-08 02:23:42 +00003221 SDOperand Op = getRoot();
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00003222 SDOperand Tmp = DAG.getNode(ISD::STACKSAVE,
3223 DAG.getNodeValueTypes(TLI.getPointerTy(), MVT::Other), 2, &Op, 1);
Chris Lattner140d53c2006-01-13 02:50:02 +00003224 setValue(&I, Tmp);
3225 DAG.setRoot(Tmp.getValue(1));
3226 return 0;
3227 }
Chris Lattner39a17dd2006-01-23 05:22:07 +00003228 case Intrinsic::stackrestore: {
3229 SDOperand Tmp = getValue(I.getOperand(1));
3230 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, MVT::Other, getRoot(), Tmp));
Chris Lattner140d53c2006-01-13 02:50:02 +00003231 return 0;
Chris Lattner39a17dd2006-01-23 05:22:07 +00003232 }
Tanya Lattner24e5aad2007-06-15 22:26:58 +00003233 case Intrinsic::var_annotation:
3234 // Discard annotate attributes
3235 return 0;
Duncan Sands36397f52007-07-27 12:58:54 +00003236
Duncan Sands36397f52007-07-27 12:58:54 +00003237 case Intrinsic::init_trampoline: {
Anton Korobeynikov0b12ecf2008-05-07 22:54:15 +00003238 const Function *F = cast<Function>(I.getOperand(2)->stripPointerCasts());
Duncan Sands36397f52007-07-27 12:58:54 +00003239
3240 SDOperand Ops[6];
3241 Ops[0] = getRoot();
3242 Ops[1] = getValue(I.getOperand(1));
3243 Ops[2] = getValue(I.getOperand(2));
3244 Ops[3] = getValue(I.getOperand(3));
3245 Ops[4] = DAG.getSrcValue(I.getOperand(1));
3246 Ops[5] = DAG.getSrcValue(F);
3247
Duncan Sandsf7331b32007-09-11 14:10:23 +00003248 SDOperand Tmp = DAG.getNode(ISD::TRAMPOLINE,
3249 DAG.getNodeValueTypes(TLI.getPointerTy(),
3250 MVT::Other), 2,
3251 Ops, 6);
3252
3253 setValue(&I, Tmp);
3254 DAG.setRoot(Tmp.getValue(1));
Duncan Sands36397f52007-07-27 12:58:54 +00003255 return 0;
3256 }
Gordon Henriksence224772008-01-07 01:30:38 +00003257
3258 case Intrinsic::gcroot:
3259 if (GCI) {
3260 Value *Alloca = I.getOperand(1);
3261 Constant *TypeMap = cast<Constant>(I.getOperand(2));
3262
3263 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).Val);
3264 GCI->addStackRoot(FI->getIndex(), TypeMap);
3265 }
3266 return 0;
3267
3268 case Intrinsic::gcread:
3269 case Intrinsic::gcwrite:
3270 assert(0 && "Collector failed to lower gcread/gcwrite intrinsics!");
3271 return 0;
3272
Anton Korobeynikov917c2a62007-11-15 23:25:33 +00003273 case Intrinsic::flt_rounds: {
Dan Gohman1a024862008-01-31 00:41:03 +00003274 setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, MVT::i32));
Anton Korobeynikov917c2a62007-11-15 23:25:33 +00003275 return 0;
3276 }
Anton Korobeynikov66fac792008-01-15 07:02:33 +00003277
3278 case Intrinsic::trap: {
3279 DAG.setRoot(DAG.getNode(ISD::TRAP, MVT::Other, getRoot()));
3280 return 0;
3281 }
Evan Cheng27b7db52008-03-08 00:58:38 +00003282 case Intrinsic::prefetch: {
3283 SDOperand Ops[4];
3284 Ops[0] = getRoot();
3285 Ops[1] = getValue(I.getOperand(1));
3286 Ops[2] = getValue(I.getOperand(2));
3287 Ops[3] = getValue(I.getOperand(3));
3288 DAG.setRoot(DAG.getNode(ISD::PREFETCH, MVT::Other, &Ops[0], 4));
3289 return 0;
3290 }
3291
Andrew Lenharth22c5c1b2008-02-16 01:24:58 +00003292 case Intrinsic::memory_barrier: {
3293 SDOperand Ops[6];
3294 Ops[0] = getRoot();
3295 for (int x = 1; x < 6; ++x)
3296 Ops[x] = getValue(I.getOperand(x));
3297
3298 DAG.setRoot(DAG.getNode(ISD::MEMBARRIER, MVT::Other, &Ops[0], 6));
3299 return 0;
3300 }
Andrew Lenharthab0b9492008-02-21 06:45:13 +00003301 case Intrinsic::atomic_lcs: {
3302 SDOperand Root = getRoot();
3303 SDOperand O3 = getValue(I.getOperand(3));
3304 SDOperand L = DAG.getAtomic(ISD::ATOMIC_LCS, Root,
3305 getValue(I.getOperand(1)),
3306 getValue(I.getOperand(2)),
3307 O3, O3.getValueType());
3308 setValue(&I, L);
3309 DAG.setRoot(L.getValue(1));
3310 return 0;
3311 }
Mon P Wang63307c32008-05-05 19:05:59 +00003312 case Intrinsic::atomic_las:
3313 return implVisitBinaryAtomic(I, ISD::ATOMIC_LAS);
3314 case Intrinsic::atomic_lss:
3315 return implVisitBinaryAtomic(I, ISD::ATOMIC_LSS);
3316 case Intrinsic::atomic_load_and:
3317 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_AND);
3318 case Intrinsic::atomic_load_or:
3319 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_OR);
3320 case Intrinsic::atomic_load_xor:
3321 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_XOR);
3322 case Intrinsic::atomic_load_min:
3323 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MIN);
3324 case Intrinsic::atomic_load_max:
3325 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MAX);
3326 case Intrinsic::atomic_load_umin:
3327 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMIN);
3328 case Intrinsic::atomic_load_umax:
3329 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMAX);
3330 case Intrinsic::atomic_swap:
3331 return implVisitBinaryAtomic(I, ISD::ATOMIC_SWAP);
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003332 }
3333}
3334
3335
Duncan Sands6f74b482007-12-19 09:48:52 +00003336void SelectionDAGLowering::LowerCallTo(CallSite CS, SDOperand Callee,
Jim Laskey1da20a72007-02-23 21:45:01 +00003337 bool IsTailCall,
Anton Korobeynikov070280e2007-05-23 11:08:31 +00003338 MachineBasicBlock *LandingPad) {
Duncan Sands6f74b482007-12-19 09:48:52 +00003339 const PointerType *PT = cast<PointerType>(CS.getCalledValue()->getType());
Jim Laskey735b6f82007-02-22 15:38:06 +00003340 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
Anton Korobeynikov070280e2007-05-23 11:08:31 +00003341 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3342 unsigned BeginLabel = 0, EndLabel = 0;
Duncan Sands6f74b482007-12-19 09:48:52 +00003343
Jim Laskey735b6f82007-02-22 15:38:06 +00003344 TargetLowering::ArgListTy Args;
3345 TargetLowering::ArgListEntry Entry;
Duncan Sands6f74b482007-12-19 09:48:52 +00003346 Args.reserve(CS.arg_size());
3347 for (CallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
3348 i != e; ++i) {
3349 SDOperand ArgNode = getValue(*i);
3350 Entry.Node = ArgNode; Entry.Ty = (*i)->getType();
Duncan Sands4fee7032007-05-07 20:49:28 +00003351
Duncan Sands6f74b482007-12-19 09:48:52 +00003352 unsigned attrInd = i - CS.arg_begin() + 1;
3353 Entry.isSExt = CS.paramHasAttr(attrInd, ParamAttr::SExt);
3354 Entry.isZExt = CS.paramHasAttr(attrInd, ParamAttr::ZExt);
3355 Entry.isInReg = CS.paramHasAttr(attrInd, ParamAttr::InReg);
3356 Entry.isSRet = CS.paramHasAttr(attrInd, ParamAttr::StructRet);
3357 Entry.isNest = CS.paramHasAttr(attrInd, ParamAttr::Nest);
3358 Entry.isByVal = CS.paramHasAttr(attrInd, ParamAttr::ByVal);
Dale Johannesen08e78b12008-02-22 17:49:45 +00003359 Entry.Alignment = CS.getParamAlignment(attrInd);
Jim Laskey735b6f82007-02-22 15:38:06 +00003360 Args.push_back(Entry);
3361 }
3362
Dale Johannesen1532f3d2008-04-02 00:25:04 +00003363 if (LandingPad && MMI) {
Anton Korobeynikov070280e2007-05-23 11:08:31 +00003364 // Insert a label before the invoke call to mark the try range. This can be
3365 // used to detect deletion of the invoke via the MachineModuleInfo.
3366 BeginLabel = MMI->NextLabelID();
Dale Johannesena4091d32008-04-04 23:48:31 +00003367 // Both PendingLoads and PendingExports must be flushed here;
3368 // this call might not return.
3369 (void)getRoot();
3370 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, getControlRoot(),
Evan Chengbb81d972008-01-31 09:59:15 +00003371 DAG.getConstant(BeginLabel, MVT::i32),
3372 DAG.getConstant(1, MVT::i32)));
Anton Korobeynikov070280e2007-05-23 11:08:31 +00003373 }
Duncan Sands6f74b482007-12-19 09:48:52 +00003374
Jim Laskey735b6f82007-02-22 15:38:06 +00003375 std::pair<SDOperand,SDOperand> Result =
Duncan Sands6f74b482007-12-19 09:48:52 +00003376 TLI.LowerCallTo(getRoot(), CS.getType(),
3377 CS.paramHasAttr(0, ParamAttr::SExt),
Duncan Sands00fee652008-02-14 17:28:50 +00003378 CS.paramHasAttr(0, ParamAttr::ZExt),
Duncan Sands6f74b482007-12-19 09:48:52 +00003379 FTy->isVarArg(), CS.getCallingConv(), IsTailCall,
Jim Laskey735b6f82007-02-22 15:38:06 +00003380 Callee, Args, DAG);
Duncan Sands6f74b482007-12-19 09:48:52 +00003381 if (CS.getType() != Type::VoidTy)
3382 setValue(CS.getInstruction(), Result.first);
Jim Laskey735b6f82007-02-22 15:38:06 +00003383 DAG.setRoot(Result.second);
Anton Korobeynikov070280e2007-05-23 11:08:31 +00003384
Dale Johannesen1532f3d2008-04-02 00:25:04 +00003385 if (LandingPad && MMI) {
Anton Korobeynikov070280e2007-05-23 11:08:31 +00003386 // Insert a label at the end of the invoke call to mark the try range. This
3387 // can be used to detect deletion of the invoke via the MachineModuleInfo.
3388 EndLabel = MMI->NextLabelID();
3389 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, getRoot(),
Evan Chengbb81d972008-01-31 09:59:15 +00003390 DAG.getConstant(EndLabel, MVT::i32),
3391 DAG.getConstant(1, MVT::i32)));
Anton Korobeynikov070280e2007-05-23 11:08:31 +00003392
Duncan Sands6f74b482007-12-19 09:48:52 +00003393 // Inform MachineModuleInfo of range.
Anton Korobeynikov070280e2007-05-23 11:08:31 +00003394 MMI->addInvoke(LandingPad, BeginLabel, EndLabel);
3395 }
Jim Laskey735b6f82007-02-22 15:38:06 +00003396}
3397
3398
Chris Lattner1c08c712005-01-07 07:47:53 +00003399void SelectionDAGLowering::visitCall(CallInst &I) {
Chris Lattner64e14b12005-01-08 22:48:57 +00003400 const char *RenameFn = 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003401 if (Function *F = I.getCalledFunction()) {
Chris Lattner87b51bc2007-09-10 21:15:22 +00003402 if (F->isDeclaration()) {
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003403 if (unsigned IID = F->getIntrinsicID()) {
3404 RenameFn = visitIntrinsicCall(I, IID);
3405 if (!RenameFn)
3406 return;
Chris Lattner87b51bc2007-09-10 21:15:22 +00003407 }
3408 }
3409
3410 // Check for well-known libc/libm calls. If the function is internal, it
3411 // can't be a library call.
3412 unsigned NameLen = F->getNameLen();
3413 if (!F->hasInternalLinkage() && NameLen) {
3414 const char *NameStr = F->getNameStart();
3415 if (NameStr[0] == 'c' &&
3416 ((NameLen == 8 && !strcmp(NameStr, "copysign")) ||
3417 (NameLen == 9 && !strcmp(NameStr, "copysignf")))) {
3418 if (I.getNumOperands() == 3 && // Basic sanity checks.
3419 I.getOperand(1)->getType()->isFloatingPoint() &&
3420 I.getType() == I.getOperand(1)->getType() &&
3421 I.getType() == I.getOperand(2)->getType()) {
3422 SDOperand LHS = getValue(I.getOperand(1));
3423 SDOperand RHS = getValue(I.getOperand(2));
3424 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, LHS.getValueType(),
3425 LHS, RHS));
3426 return;
3427 }
3428 } else if (NameStr[0] == 'f' &&
3429 ((NameLen == 4 && !strcmp(NameStr, "fabs")) ||
Dale Johannesen2f429012007-09-26 21:10:55 +00003430 (NameLen == 5 && !strcmp(NameStr, "fabsf")) ||
3431 (NameLen == 5 && !strcmp(NameStr, "fabsl")))) {
Chris Lattner87b51bc2007-09-10 21:15:22 +00003432 if (I.getNumOperands() == 2 && // Basic sanity checks.
3433 I.getOperand(1)->getType()->isFloatingPoint() &&
3434 I.getType() == I.getOperand(1)->getType()) {
3435 SDOperand Tmp = getValue(I.getOperand(1));
3436 setValue(&I, DAG.getNode(ISD::FABS, Tmp.getValueType(), Tmp));
3437 return;
3438 }
3439 } else if (NameStr[0] == 's' &&
3440 ((NameLen == 3 && !strcmp(NameStr, "sin")) ||
Dale Johannesen2f429012007-09-26 21:10:55 +00003441 (NameLen == 4 && !strcmp(NameStr, "sinf")) ||
3442 (NameLen == 4 && !strcmp(NameStr, "sinl")))) {
Chris Lattner87b51bc2007-09-10 21:15:22 +00003443 if (I.getNumOperands() == 2 && // Basic sanity checks.
3444 I.getOperand(1)->getType()->isFloatingPoint() &&
3445 I.getType() == I.getOperand(1)->getType()) {
3446 SDOperand Tmp = getValue(I.getOperand(1));
3447 setValue(&I, DAG.getNode(ISD::FSIN, Tmp.getValueType(), Tmp));
3448 return;
3449 }
3450 } else if (NameStr[0] == 'c' &&
3451 ((NameLen == 3 && !strcmp(NameStr, "cos")) ||
Dale Johannesen2f429012007-09-26 21:10:55 +00003452 (NameLen == 4 && !strcmp(NameStr, "cosf")) ||
3453 (NameLen == 4 && !strcmp(NameStr, "cosl")))) {
Chris Lattner87b51bc2007-09-10 21:15:22 +00003454 if (I.getNumOperands() == 2 && // Basic sanity checks.
3455 I.getOperand(1)->getType()->isFloatingPoint() &&
3456 I.getType() == I.getOperand(1)->getType()) {
3457 SDOperand Tmp = getValue(I.getOperand(1));
3458 setValue(&I, DAG.getNode(ISD::FCOS, Tmp.getValueType(), Tmp));
3459 return;
Chris Lattnerf76e7dc2005-04-30 04:43:14 +00003460 }
Chris Lattner1ca85d52005-05-14 13:56:55 +00003461 }
Chris Lattner87b51bc2007-09-10 21:15:22 +00003462 }
Chris Lattnerce7518c2006-01-26 22:24:51 +00003463 } else if (isa<InlineAsm>(I.getOperand(0))) {
Duncan Sandsfd7b3262007-12-17 18:08:19 +00003464 visitInlineAsm(&I);
Chris Lattnerce7518c2006-01-26 22:24:51 +00003465 return;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003466 }
Misha Brukmanedf128a2005-04-21 22:36:52 +00003467
Chris Lattner64e14b12005-01-08 22:48:57 +00003468 SDOperand Callee;
3469 if (!RenameFn)
3470 Callee = getValue(I.getOperand(0));
3471 else
3472 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
Anton Korobeynikov070280e2007-05-23 11:08:31 +00003473
Duncan Sands6f74b482007-12-19 09:48:52 +00003474 LowerCallTo(&I, Callee, I.isTailCall());
Chris Lattner1c08c712005-01-07 07:47:53 +00003475}
3476
Jim Laskey735b6f82007-02-22 15:38:06 +00003477
Dan Gohmanef5d1942008-03-11 21:11:25 +00003478void SelectionDAGLowering::visitGetResult(GetResultInst &I) {
Dan Gohman67780f12008-04-23 20:25:16 +00003479 if (isa<UndefValue>(I.getOperand(0))) {
Dan Gohman3dc34f62008-04-23 20:21:29 +00003480 SDOperand Undef = DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType()));
3481 setValue(&I, Undef);
Chris Lattner6833b062008-04-28 07:16:35 +00003482 return;
Dan Gohman3dc34f62008-04-23 20:21:29 +00003483 }
Chris Lattner6833b062008-04-28 07:16:35 +00003484
3485 // To add support for individual return values with aggregate types,
3486 // we'd need a way to take a getresult index and determine which
3487 // values of the Call SDNode are associated with it.
3488 assert(TLI.getValueType(I.getType(), true) != MVT::Other &&
3489 "Individual return values must not be aggregates!");
3490
3491 SDOperand Call = getValue(I.getOperand(0));
3492 setValue(&I, SDOperand(Call.Val, I.getIndex()));
Dan Gohmanef5d1942008-03-11 21:11:25 +00003493}
3494
3495
Dan Gohmanb6f5b002007-06-28 23:29:44 +00003496/// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
3497/// this value and returns the result as a ValueVT value. This uses
3498/// Chain/Flag as the input and updates them for the output Chain/Flag.
3499/// If the Flag pointer is NULL, no flag is used.
3500SDOperand RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
Chris Lattner6833b062008-04-28 07:16:35 +00003501 SDOperand &Chain,
3502 SDOperand *Flag) const {
Dan Gohman23ce5022008-04-25 18:27:55 +00003503 // Assemble the legal parts into the final values.
3504 SmallVector<SDOperand, 4> Values(ValueVTs.size());
Chris Lattner6833b062008-04-28 07:16:35 +00003505 SmallVector<SDOperand, 8> Parts;
3506 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
Dan Gohman23ce5022008-04-25 18:27:55 +00003507 // Copy the legal parts from the registers.
Duncan Sands83ec4b62008-06-06 12:08:01 +00003508 MVT ValueVT = ValueVTs[Value];
Dan Gohman23ce5022008-04-25 18:27:55 +00003509 unsigned NumRegs = TLI->getNumRegisters(ValueVT);
Duncan Sands83ec4b62008-06-06 12:08:01 +00003510 MVT RegisterVT = RegVTs[Value];
Dan Gohman23ce5022008-04-25 18:27:55 +00003511
Chris Lattner6833b062008-04-28 07:16:35 +00003512 Parts.resize(NumRegs);
Dan Gohman23ce5022008-04-25 18:27:55 +00003513 for (unsigned i = 0; i != NumRegs; ++i) {
Chris Lattner6833b062008-04-28 07:16:35 +00003514 SDOperand P;
3515 if (Flag == 0)
3516 P = DAG.getCopyFromReg(Chain, Regs[Part+i], RegisterVT);
3517 else {
3518 P = DAG.getCopyFromReg(Chain, Regs[Part+i], RegisterVT, *Flag);
Dan Gohman23ce5022008-04-25 18:27:55 +00003519 *Flag = P.getValue(2);
Chris Lattner6833b062008-04-28 07:16:35 +00003520 }
3521 Chain = P.getValue(1);
Dan Gohman23ce5022008-04-25 18:27:55 +00003522 Parts[Part+i] = P;
3523 }
Chris Lattner5df99b32007-03-25 05:00:54 +00003524
Dan Gohman23ce5022008-04-25 18:27:55 +00003525 Values[Value] = getCopyFromParts(DAG, &Parts[Part], NumRegs, RegisterVT,
3526 ValueVT);
3527 Part += NumRegs;
3528 }
Chris Lattner6833b062008-04-28 07:16:35 +00003529
3530 if (ValueVTs.size() == 1)
3531 return Values[0];
3532
Dan Gohman23ce5022008-04-25 18:27:55 +00003533 return DAG.getNode(ISD::MERGE_VALUES,
3534 DAG.getVTList(&ValueVTs[0], ValueVTs.size()),
3535 &Values[0], ValueVTs.size());
Chris Lattner864635a2006-02-22 22:37:12 +00003536}
3537
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00003538/// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
3539/// specified value into the registers specified by this object. This uses
3540/// Chain/Flag as the input and updates them for the output Chain/Flag.
Dan Gohmanb6f5b002007-06-28 23:29:44 +00003541/// If the Flag pointer is NULL, no flag is used.
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00003542void RegsForValue::getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
Dan Gohmanb6f5b002007-06-28 23:29:44 +00003543 SDOperand &Chain, SDOperand *Flag) const {
Dan Gohmanb6f5b002007-06-28 23:29:44 +00003544 // Get the list of the values's legal parts.
Dan Gohman23ce5022008-04-25 18:27:55 +00003545 unsigned NumRegs = Regs.size();
3546 SmallVector<SDOperand, 8> Parts(NumRegs);
Chris Lattner6833b062008-04-28 07:16:35 +00003547 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
Duncan Sands83ec4b62008-06-06 12:08:01 +00003548 MVT ValueVT = ValueVTs[Value];
Dan Gohman23ce5022008-04-25 18:27:55 +00003549 unsigned NumParts = TLI->getNumRegisters(ValueVT);
Duncan Sands83ec4b62008-06-06 12:08:01 +00003550 MVT RegisterVT = RegVTs[Value];
Dan Gohman23ce5022008-04-25 18:27:55 +00003551
3552 getCopyToParts(DAG, Val.getValue(Val.ResNo + Value),
3553 &Parts[Part], NumParts, RegisterVT);
3554 Part += NumParts;
3555 }
Dan Gohmanb6f5b002007-06-28 23:29:44 +00003556
3557 // Copy the parts into the registers.
Dan Gohman23ce5022008-04-25 18:27:55 +00003558 SmallVector<SDOperand, 8> Chains(NumRegs);
3559 for (unsigned i = 0; i != NumRegs; ++i) {
Chris Lattner6833b062008-04-28 07:16:35 +00003560 SDOperand Part;
3561 if (Flag == 0)
3562 Part = DAG.getCopyToReg(Chain, Regs[i], Parts[i]);
3563 else {
3564 Part = DAG.getCopyToReg(Chain, Regs[i], Parts[i], *Flag);
Dan Gohmanb6f5b002007-06-28 23:29:44 +00003565 *Flag = Part.getValue(1);
Chris Lattner6833b062008-04-28 07:16:35 +00003566 }
3567 Chains[i] = Part.getValue(0);
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00003568 }
Chris Lattner6833b062008-04-28 07:16:35 +00003569
Evan Cheng33bf38a2008-04-28 22:07:13 +00003570 if (NumRegs == 1 || Flag)
3571 // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is
3572 // flagged to it. That is the CopyToReg nodes and the user are considered
3573 // a single scheduling unit. If we create a TokenFactor and return it as
3574 // chain, then the TokenFactor is both a predecessor (operand) of the
3575 // user as well as a successor (the TF operands are flagged to the user).
3576 // c1, f1 = CopyToReg
3577 // c2, f2 = CopyToReg
3578 // c3 = TokenFactor c1, c2
3579 // ...
3580 // = op c3, ..., f2
3581 Chain = Chains[NumRegs-1];
Chris Lattner6833b062008-04-28 07:16:35 +00003582 else
3583 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other, &Chains[0], NumRegs);
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00003584}
Chris Lattner864635a2006-02-22 22:37:12 +00003585
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00003586/// AddInlineAsmOperands - Add this value to the specified inlineasm node
3587/// operand list. This adds the code marker and includes the number of
3588/// values added into it.
3589void RegsForValue::AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
Chris Lattner9f6637d2006-02-23 20:06:57 +00003590 std::vector<SDOperand> &Ops) const {
Duncan Sands83ec4b62008-06-06 12:08:01 +00003591 MVT IntPtrTy = DAG.getTargetLoweringInfo().getPointerTy();
Chris Lattner4b993b12007-04-09 00:33:58 +00003592 Ops.push_back(DAG.getTargetConstant(Code | (Regs.size() << 3), IntPtrTy));
Chris Lattner6833b062008-04-28 07:16:35 +00003593 for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
3594 unsigned NumRegs = TLI->getNumRegisters(ValueVTs[Value]);
Duncan Sands83ec4b62008-06-06 12:08:01 +00003595 MVT RegisterVT = RegVTs[Value];
Chris Lattner6833b062008-04-28 07:16:35 +00003596 for (unsigned i = 0; i != NumRegs; ++i)
3597 Ops.push_back(DAG.getRegister(Regs[Reg++], RegisterVT));
Dan Gohman23ce5022008-04-25 18:27:55 +00003598 }
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00003599}
Chris Lattner864635a2006-02-22 22:37:12 +00003600
3601/// isAllocatableRegister - If the specified register is safe to allocate,
3602/// i.e. it isn't a stack pointer or some other special register, return the
3603/// register class for the register. Otherwise, return null.
3604static const TargetRegisterClass *
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00003605isAllocatableRegister(unsigned Reg, MachineFunction &MF,
Dan Gohman6f0d0242008-02-10 18:45:23 +00003606 const TargetLowering &TLI,
3607 const TargetRegisterInfo *TRI) {
Duncan Sands83ec4b62008-06-06 12:08:01 +00003608 MVT FoundVT = MVT::Other;
Chris Lattnerf8814cf2006-04-02 00:24:45 +00003609 const TargetRegisterClass *FoundRC = 0;
Dan Gohman6f0d0242008-02-10 18:45:23 +00003610 for (TargetRegisterInfo::regclass_iterator RCI = TRI->regclass_begin(),
3611 E = TRI->regclass_end(); RCI != E; ++RCI) {
Duncan Sands83ec4b62008-06-06 12:08:01 +00003612 MVT ThisVT = MVT::Other;
Chris Lattnerf8814cf2006-04-02 00:24:45 +00003613
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00003614 const TargetRegisterClass *RC = *RCI;
3615 // If none of the the value types for this register class are valid, we
3616 // can't use it. For example, 64-bit reg classes on 32-bit targets.
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00003617 for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
3618 I != E; ++I) {
3619 if (TLI.isTypeLegal(*I)) {
Chris Lattnerf8814cf2006-04-02 00:24:45 +00003620 // If we have already found this register in a different register class,
3621 // choose the one with the largest VT specified. For example, on
3622 // PowerPC, we favor f64 register classes over f32.
3623 if (FoundVT == MVT::Other ||
Duncan Sands83ec4b62008-06-06 12:08:01 +00003624 FoundVT.getSizeInBits() < (*I).getSizeInBits()) {
Chris Lattnerf8814cf2006-04-02 00:24:45 +00003625 ThisVT = *I;
3626 break;
3627 }
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00003628 }
3629 }
3630
Chris Lattnerf8814cf2006-04-02 00:24:45 +00003631 if (ThisVT == MVT::Other) continue;
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00003632
Chris Lattner864635a2006-02-22 22:37:12 +00003633 // NOTE: This isn't ideal. In particular, this might allocate the
3634 // frame pointer in functions that need it (due to them not being taken
3635 // out of allocation, because a variable sized allocation hasn't been seen
3636 // yet). This is a slight code pessimization, but should still work.
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00003637 for (TargetRegisterClass::iterator I = RC->allocation_order_begin(MF),
3638 E = RC->allocation_order_end(MF); I != E; ++I)
Chris Lattnerf8814cf2006-04-02 00:24:45 +00003639 if (*I == Reg) {
3640 // We found a matching register class. Keep looking at others in case
3641 // we find one with larger registers that this physreg is also in.
3642 FoundRC = RC;
3643 FoundVT = ThisVT;
3644 break;
3645 }
Chris Lattner4e4b5762006-02-01 18:59:47 +00003646 }
Chris Lattnerf8814cf2006-04-02 00:24:45 +00003647 return FoundRC;
Chris Lattner864635a2006-02-22 22:37:12 +00003648}
3649
Chris Lattner4e4b5762006-02-01 18:59:47 +00003650
Chris Lattner0c583402007-04-28 20:49:53 +00003651namespace {
3652/// AsmOperandInfo - This contains information for each constraint that we are
3653/// lowering.
Evan Cheng5c807602008-02-26 02:33:44 +00003654struct SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo {
3655 /// CallOperand - If this is the result output operand or a clobber
3656 /// this is null, otherwise it is the incoming operand to the CallInst.
3657 /// This gets modified as the asm is processed.
Chris Lattner0c583402007-04-28 20:49:53 +00003658 SDOperand CallOperand;
Evan Cheng5c807602008-02-26 02:33:44 +00003659
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003660 /// AssignedRegs - If this is a register or register class operand, this
3661 /// contains the set of register corresponding to the operand.
3662 RegsForValue AssignedRegs;
3663
Dan Gohman23ce5022008-04-25 18:27:55 +00003664 explicit SDISelAsmOperandInfo(const InlineAsm::ConstraintInfo &info)
Evan Cheng5c807602008-02-26 02:33:44 +00003665 : TargetLowering::AsmOperandInfo(info), CallOperand(0,0) {
Chris Lattner0c583402007-04-28 20:49:53 +00003666 }
Chris Lattner3ff90dc2007-04-30 17:16:27 +00003667
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003668 /// MarkAllocatedRegs - Once AssignedRegs is set, mark the assigned registers
3669 /// busy in OutputRegs/InputRegs.
3670 void MarkAllocatedRegs(bool isOutReg, bool isInReg,
3671 std::set<unsigned> &OutputRegs,
Chris Lattner7cbeb242008-02-21 04:55:52 +00003672 std::set<unsigned> &InputRegs,
3673 const TargetRegisterInfo &TRI) const {
3674 if (isOutReg) {
3675 for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i)
3676 MarkRegAndAliases(AssignedRegs.Regs[i], OutputRegs, TRI);
3677 }
3678 if (isInReg) {
3679 for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i)
3680 MarkRegAndAliases(AssignedRegs.Regs[i], InputRegs, TRI);
3681 }
3682 }
3683
3684private:
3685 /// MarkRegAndAliases - Mark the specified register and all aliases in the
3686 /// specified set.
3687 static void MarkRegAndAliases(unsigned Reg, std::set<unsigned> &Regs,
3688 const TargetRegisterInfo &TRI) {
3689 assert(TargetRegisterInfo::isPhysicalRegister(Reg) && "Isn't a physreg");
3690 Regs.insert(Reg);
3691 if (const unsigned *Aliases = TRI.getAliasSet(Reg))
3692 for (; *Aliases; ++Aliases)
3693 Regs.insert(*Aliases);
3694 }
Chris Lattner0c583402007-04-28 20:49:53 +00003695};
3696} // end anon namespace.
Chris Lattner864635a2006-02-22 22:37:12 +00003697
Chris Lattner3ff90dc2007-04-30 17:16:27 +00003698
Chris Lattner0fe71e92008-02-21 19:43:13 +00003699/// GetRegistersForValue - Assign registers (virtual or physical) for the
3700/// specified operand. We prefer to assign virtual registers, to allow the
3701/// register allocator handle the assignment process. However, if the asm uses
3702/// features that we can't model on machineinstrs, we have SDISel do the
3703/// allocation. This produces generally horrible, but correct, code.
3704///
3705/// OpInfo describes the operand.
3706/// HasEarlyClobber is true if there are any early clobber constraints (=&r)
3707/// or any explicitly clobbered registers.
3708/// Input and OutputRegs are the set of already allocated physical registers.
3709///
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003710void SelectionDAGLowering::
Evan Cheng5c807602008-02-26 02:33:44 +00003711GetRegistersForValue(SDISelAsmOperandInfo &OpInfo, bool HasEarlyClobber,
Chris Lattnerbf996f12007-04-30 17:29:31 +00003712 std::set<unsigned> &OutputRegs,
3713 std::set<unsigned> &InputRegs) {
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003714 // Compute whether this value requires an input register, an output register,
3715 // or both.
3716 bool isOutReg = false;
3717 bool isInReg = false;
3718 switch (OpInfo.Type) {
3719 case InlineAsm::isOutput:
3720 isOutReg = true;
3721
3722 // If this is an early-clobber output, or if there is an input
3723 // constraint that matches this, we need to reserve the input register
3724 // so no other inputs allocate to it.
3725 isInReg = OpInfo.isEarlyClobber || OpInfo.hasMatchingInput;
3726 break;
3727 case InlineAsm::isInput:
3728 isInReg = true;
3729 isOutReg = false;
3730 break;
3731 case InlineAsm::isClobber:
3732 isOutReg = true;
3733 isInReg = true;
3734 break;
3735 }
3736
3737
3738 MachineFunction &MF = DAG.getMachineFunction();
Chris Lattnerb606dba2008-04-28 06:44:42 +00003739 SmallVector<unsigned, 4> Regs;
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003740
3741 // If this is a constraint for a single physreg, or a constraint for a
3742 // register class, find it.
3743 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
3744 TLI.getRegForInlineAsmConstraint(OpInfo.ConstraintCode,
3745 OpInfo.ConstraintVT);
Chris Lattnerbf996f12007-04-30 17:29:31 +00003746
3747 unsigned NumRegs = 1;
3748 if (OpInfo.ConstraintVT != MVT::Other)
Dan Gohmanb9f10192007-06-21 14:42:22 +00003749 NumRegs = TLI.getNumRegisters(OpInfo.ConstraintVT);
Duncan Sands83ec4b62008-06-06 12:08:01 +00003750 MVT RegVT;
3751 MVT ValueVT = OpInfo.ConstraintVT;
Chris Lattnerbf996f12007-04-30 17:29:31 +00003752
Chris Lattnerbf996f12007-04-30 17:29:31 +00003753
3754 // If this is a constraint for a specific physical register, like {r17},
3755 // assign it now.
3756 if (PhysReg.first) {
3757 if (OpInfo.ConstraintVT == MVT::Other)
3758 ValueVT = *PhysReg.second->vt_begin();
3759
3760 // Get the actual register value type. This is important, because the user
3761 // may have asked for (e.g.) the AX register in i32 type. We need to
3762 // remember that AX is actually i16 to get the right extension.
3763 RegVT = *PhysReg.second->vt_begin();
3764
3765 // This is a explicit reference to a physical register.
3766 Regs.push_back(PhysReg.first);
3767
3768 // If this is an expanded reference, add the rest of the regs to Regs.
3769 if (NumRegs != 1) {
3770 TargetRegisterClass::iterator I = PhysReg.second->begin();
Chris Lattnerbf996f12007-04-30 17:29:31 +00003771 for (; *I != PhysReg.first; ++I)
Evan Cheng50871242008-05-14 20:07:51 +00003772 assert(I != PhysReg.second->end() && "Didn't find reg!");
Chris Lattnerbf996f12007-04-30 17:29:31 +00003773
3774 // Already added the first reg.
3775 --NumRegs; ++I;
3776 for (; NumRegs; --NumRegs, ++I) {
Evan Cheng50871242008-05-14 20:07:51 +00003777 assert(I != PhysReg.second->end() && "Ran out of registers to allocate!");
Chris Lattnerbf996f12007-04-30 17:29:31 +00003778 Regs.push_back(*I);
3779 }
3780 }
Dan Gohman23ce5022008-04-25 18:27:55 +00003781 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, RegVT, ValueVT);
Chris Lattner7cbeb242008-02-21 04:55:52 +00003782 const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
3783 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TRI);
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003784 return;
Chris Lattnerbf996f12007-04-30 17:29:31 +00003785 }
3786
3787 // Otherwise, if this was a reference to an LLVM register class, create vregs
3788 // for this reference.
3789 std::vector<unsigned> RegClassRegs;
Chris Lattnerc2c28fc2007-06-15 19:11:01 +00003790 const TargetRegisterClass *RC = PhysReg.second;
3791 if (RC) {
Chris Lattnerbf996f12007-04-30 17:29:31 +00003792 // If this is an early clobber or tied register, our regalloc doesn't know
3793 // how to maintain the constraint. If it isn't, go ahead and create vreg
3794 // and let the regalloc do the right thing.
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003795 if (!OpInfo.hasMatchingInput && !OpInfo.isEarlyClobber &&
3796 // If there is some other early clobber and this is an input register,
3797 // then we are forced to pre-allocate the input reg so it doesn't
3798 // conflict with the earlyclobber.
3799 !(OpInfo.Type == InlineAsm::isInput && HasEarlyClobber)) {
Chris Lattnerbf996f12007-04-30 17:29:31 +00003800 RegVT = *PhysReg.second->vt_begin();
3801
3802 if (OpInfo.ConstraintVT == MVT::Other)
3803 ValueVT = RegVT;
3804
3805 // Create the appropriate number of virtual registers.
Chris Lattner84bc5422007-12-31 04:13:23 +00003806 MachineRegisterInfo &RegInfo = MF.getRegInfo();
Chris Lattnerbf996f12007-04-30 17:29:31 +00003807 for (; NumRegs; --NumRegs)
Chris Lattner84bc5422007-12-31 04:13:23 +00003808 Regs.push_back(RegInfo.createVirtualRegister(PhysReg.second));
Chris Lattnerbf996f12007-04-30 17:29:31 +00003809
Dan Gohman23ce5022008-04-25 18:27:55 +00003810 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, RegVT, ValueVT);
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003811 return;
Chris Lattnerbf996f12007-04-30 17:29:31 +00003812 }
3813
3814 // Otherwise, we can't allocate it. Let the code below figure out how to
3815 // maintain these constraints.
3816 RegClassRegs.assign(PhysReg.second->begin(), PhysReg.second->end());
3817
3818 } else {
3819 // This is a reference to a register class that doesn't directly correspond
3820 // to an LLVM register class. Allocate NumRegs consecutive, available,
3821 // registers from the class.
3822 RegClassRegs = TLI.getRegClassForInlineAsmConstraint(OpInfo.ConstraintCode,
3823 OpInfo.ConstraintVT);
3824 }
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003825
Dan Gohman6f0d0242008-02-10 18:45:23 +00003826 const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
Chris Lattnerbf996f12007-04-30 17:29:31 +00003827 unsigned NumAllocated = 0;
3828 for (unsigned i = 0, e = RegClassRegs.size(); i != e; ++i) {
3829 unsigned Reg = RegClassRegs[i];
3830 // See if this register is available.
3831 if ((isOutReg && OutputRegs.count(Reg)) || // Already used.
3832 (isInReg && InputRegs.count(Reg))) { // Already used.
3833 // Make sure we find consecutive registers.
3834 NumAllocated = 0;
3835 continue;
3836 }
3837
3838 // Check to see if this register is allocatable (i.e. don't give out the
3839 // stack pointer).
Chris Lattnerc2c28fc2007-06-15 19:11:01 +00003840 if (RC == 0) {
Dan Gohman6f0d0242008-02-10 18:45:23 +00003841 RC = isAllocatableRegister(Reg, MF, TLI, TRI);
Chris Lattnerc2c28fc2007-06-15 19:11:01 +00003842 if (!RC) { // Couldn't allocate this register.
3843 // Reset NumAllocated to make sure we return consecutive registers.
3844 NumAllocated = 0;
3845 continue;
3846 }
Chris Lattnerbf996f12007-04-30 17:29:31 +00003847 }
3848
3849 // Okay, this register is good, we can use it.
3850 ++NumAllocated;
3851
3852 // If we allocated enough consecutive registers, succeed.
3853 if (NumAllocated == NumRegs) {
3854 unsigned RegStart = (i-NumAllocated)+1;
3855 unsigned RegEnd = i+1;
3856 // Mark all of the allocated registers used.
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003857 for (unsigned i = RegStart; i != RegEnd; ++i)
3858 Regs.push_back(RegClassRegs[i]);
Chris Lattnerbf996f12007-04-30 17:29:31 +00003859
Dan Gohman23ce5022008-04-25 18:27:55 +00003860 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, *RC->vt_begin(),
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003861 OpInfo.ConstraintVT);
Chris Lattner7cbeb242008-02-21 04:55:52 +00003862 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TRI);
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003863 return;
Chris Lattnerbf996f12007-04-30 17:29:31 +00003864 }
3865 }
3866
3867 // Otherwise, we couldn't allocate enough registers for this.
Chris Lattnerbf996f12007-04-30 17:29:31 +00003868}
3869
3870
Chris Lattnerce7518c2006-01-26 22:24:51 +00003871/// visitInlineAsm - Handle a call to an InlineAsm object.
3872///
Duncan Sandsfd7b3262007-12-17 18:08:19 +00003873void SelectionDAGLowering::visitInlineAsm(CallSite CS) {
3874 InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
Chris Lattnerce7518c2006-01-26 22:24:51 +00003875
Chris Lattner0c583402007-04-28 20:49:53 +00003876 /// ConstraintOperands - Information about all of the constraints.
Evan Cheng5c807602008-02-26 02:33:44 +00003877 std::vector<SDISelAsmOperandInfo> ConstraintOperands;
Chris Lattnerce7518c2006-01-26 22:24:51 +00003878
3879 SDOperand Chain = getRoot();
3880 SDOperand Flag;
3881
Chris Lattner4e4b5762006-02-01 18:59:47 +00003882 std::set<unsigned> OutputRegs, InputRegs;
Chris Lattner1efa40f2006-02-22 00:56:39 +00003883
Chris Lattner0c583402007-04-28 20:49:53 +00003884 // Do a prepass over the constraints, canonicalizing them, and building up the
3885 // ConstraintOperands list.
3886 std::vector<InlineAsm::ConstraintInfo>
3887 ConstraintInfos = IA->ParseConstraints();
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003888
3889 // SawEarlyClobber - Keep track of whether we saw an earlyclobber output
3890 // constraint. If so, we can't let the register allocator allocate any input
3891 // registers, because it will not know to avoid the earlyclobbered output reg.
3892 bool SawEarlyClobber = false;
3893
Duncan Sandsfd7b3262007-12-17 18:08:19 +00003894 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst.
Chris Lattneracf8b012008-04-27 23:44:28 +00003895 unsigned ResNo = 0; // ResNo - The result number of the next output.
Chris Lattner0c583402007-04-28 20:49:53 +00003896 for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) {
Evan Cheng5c807602008-02-26 02:33:44 +00003897 ConstraintOperands.push_back(SDISelAsmOperandInfo(ConstraintInfos[i]));
3898 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
Chris Lattner0c583402007-04-28 20:49:53 +00003899
Duncan Sands83ec4b62008-06-06 12:08:01 +00003900 MVT OpVT = MVT::Other;
Chris Lattner0c583402007-04-28 20:49:53 +00003901
3902 // Compute the value type for each operand.
3903 switch (OpInfo.Type) {
Chris Lattner1efa40f2006-02-22 00:56:39 +00003904 case InlineAsm::isOutput:
Chris Lattneracf8b012008-04-27 23:44:28 +00003905 // Indirect outputs just consume an argument.
3906 if (OpInfo.isIndirect) {
Duncan Sandsfd7b3262007-12-17 18:08:19 +00003907 OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
Chris Lattneracf8b012008-04-27 23:44:28 +00003908 break;
Chris Lattner1efa40f2006-02-22 00:56:39 +00003909 }
Chris Lattneracf8b012008-04-27 23:44:28 +00003910 // The return value of the call is this value. As such, there is no
3911 // corresponding argument.
3912 assert(CS.getType() != Type::VoidTy && "Bad inline asm!");
3913 if (const StructType *STy = dyn_cast<StructType>(CS.getType())) {
3914 OpVT = TLI.getValueType(STy->getElementType(ResNo));
3915 } else {
3916 assert(ResNo == 0 && "Asm only has one result!");
3917 OpVT = TLI.getValueType(CS.getType());
3918 }
3919 ++ResNo;
Chris Lattner1efa40f2006-02-22 00:56:39 +00003920 break;
3921 case InlineAsm::isInput:
Duncan Sandsfd7b3262007-12-17 18:08:19 +00003922 OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
Chris Lattner1efa40f2006-02-22 00:56:39 +00003923 break;
3924 case InlineAsm::isClobber:
Chris Lattner0c583402007-04-28 20:49:53 +00003925 // Nothing to do.
Chris Lattner1efa40f2006-02-22 00:56:39 +00003926 break;
3927 }
Chris Lattner1efa40f2006-02-22 00:56:39 +00003928
Chris Lattner0c583402007-04-28 20:49:53 +00003929 // If this is an input or an indirect output, process the call argument.
Dale Johanneseneb57ea72007-11-05 21:20:28 +00003930 // BasicBlocks are labels, currently appearing only in asm's.
Chris Lattner0c583402007-04-28 20:49:53 +00003931 if (OpInfo.CallOperandVal) {
Chris Lattner507ffd22008-04-27 00:16:18 +00003932 if (BasicBlock *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal))
3933 OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
Dale Johanneseneb57ea72007-11-05 21:20:28 +00003934 else {
3935 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
3936 const Type *OpTy = OpInfo.CallOperandVal->getType();
3937 // If this is an indirect operand, the operand is a pointer to the
3938 // accessed type.
3939 if (OpInfo.isIndirect)
3940 OpTy = cast<PointerType>(OpTy)->getElementType();
3941
Dan Gohman4fa2a3f2008-05-23 00:34:04 +00003942 // If OpTy is not a single value, it may be a struct/union that we
Dale Johanneseneb57ea72007-11-05 21:20:28 +00003943 // can tile with integers.
Dan Gohman4fa2a3f2008-05-23 00:34:04 +00003944 if (!OpTy->isSingleValueType() && OpTy->isSized()) {
Dale Johanneseneb57ea72007-11-05 21:20:28 +00003945 unsigned BitSize = TD->getTypeSizeInBits(OpTy);
3946 switch (BitSize) {
3947 default: break;
3948 case 1:
3949 case 8:
3950 case 16:
3951 case 32:
3952 case 64:
3953 OpTy = IntegerType::get(BitSize);
3954 break;
3955 }
Chris Lattner6995cf62007-04-29 18:58:03 +00003956 }
Dale Johanneseneb57ea72007-11-05 21:20:28 +00003957
3958 OpVT = TLI.getValueType(OpTy, true);
Chris Lattner0c583402007-04-28 20:49:53 +00003959 }
3960 }
3961
3962 OpInfo.ConstraintVT = OpVT;
Chris Lattner2a600be2007-04-28 21:01:43 +00003963
Chris Lattner3ff90dc2007-04-30 17:16:27 +00003964 // Compute the constraint code and ConstraintType to use.
Chris Lattner5a096902008-04-27 00:37:18 +00003965 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
Chris Lattner0c583402007-04-28 20:49:53 +00003966
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003967 // Keep track of whether we see an earlyclobber.
3968 SawEarlyClobber |= OpInfo.isEarlyClobber;
Chris Lattner09e4b7e2007-04-28 21:12:06 +00003969
Chris Lattner0fe71e92008-02-21 19:43:13 +00003970 // If we see a clobber of a register, it is an early clobber.
Chris Lattner69e6a8d2008-02-21 20:54:31 +00003971 if (!SawEarlyClobber &&
3972 OpInfo.Type == InlineAsm::isClobber &&
3973 OpInfo.ConstraintType == TargetLowering::C_Register) {
3974 // Note that we want to ignore things that we don't trick here, like
3975 // dirflag, fpsr, flags, etc.
3976 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
3977 TLI.getRegForInlineAsmConstraint(OpInfo.ConstraintCode,
3978 OpInfo.ConstraintVT);
3979 if (PhysReg.first || PhysReg.second) {
3980 // This is a register we know of.
3981 SawEarlyClobber = true;
3982 }
3983 }
Chris Lattner0fe71e92008-02-21 19:43:13 +00003984
Chris Lattner09e4b7e2007-04-28 21:12:06 +00003985 // If this is a memory input, and if the operand is not indirect, do what we
3986 // need to to provide an address for the memory input.
3987 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
3988 !OpInfo.isIndirect) {
3989 assert(OpInfo.Type == InlineAsm::isInput &&
3990 "Can only indirectify direct input operands!");
3991
3992 // Memory operands really want the address of the value. If we don't have
3993 // an indirect input, put it in the constpool if we can, otherwise spill
3994 // it to a stack slot.
3995
3996 // If the operand is a float, integer, or vector constant, spill to a
3997 // constant pool entry to get its address.
3998 Value *OpVal = OpInfo.CallOperandVal;
3999 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
4000 isa<ConstantVector>(OpVal)) {
4001 OpInfo.CallOperand = DAG.getConstantPool(cast<Constant>(OpVal),
4002 TLI.getPointerTy());
4003 } else {
4004 // Otherwise, create a stack slot and emit a store to it before the
4005 // asm.
4006 const Type *Ty = OpVal->getType();
Duncan Sands514ab342007-11-01 20:53:16 +00004007 uint64_t TySize = TLI.getTargetData()->getABITypeSize(Ty);
Chris Lattner09e4b7e2007-04-28 21:12:06 +00004008 unsigned Align = TLI.getTargetData()->getPrefTypeAlignment(Ty);
4009 MachineFunction &MF = DAG.getMachineFunction();
4010 int SSFI = MF.getFrameInfo()->CreateStackObject(TySize, Align);
4011 SDOperand StackSlot = DAG.getFrameIndex(SSFI, TLI.getPointerTy());
4012 Chain = DAG.getStore(Chain, OpInfo.CallOperand, StackSlot, NULL, 0);
4013 OpInfo.CallOperand = StackSlot;
4014 }
4015
4016 // There is no longer a Value* corresponding to this operand.
4017 OpInfo.CallOperandVal = 0;
4018 // It is now an indirect operand.
4019 OpInfo.isIndirect = true;
4020 }
4021
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004022 // If this constraint is for a specific register, allocate it before
4023 // anything else.
4024 if (OpInfo.ConstraintType == TargetLowering::C_Register)
4025 GetRegistersForValue(OpInfo, SawEarlyClobber, OutputRegs, InputRegs);
Chris Lattner0c583402007-04-28 20:49:53 +00004026 }
Chris Lattner0c583402007-04-28 20:49:53 +00004027 ConstraintInfos.clear();
4028
4029
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004030 // Second pass - Loop over all of the operands, assigning virtual or physregs
4031 // to registerclass operands.
4032 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
Evan Cheng5c807602008-02-26 02:33:44 +00004033 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004034
4035 // C_Register operands have already been allocated, Other/Memory don't need
4036 // to be.
4037 if (OpInfo.ConstraintType == TargetLowering::C_RegisterClass)
4038 GetRegistersForValue(OpInfo, SawEarlyClobber, OutputRegs, InputRegs);
4039 }
4040
Chris Lattner0c583402007-04-28 20:49:53 +00004041 // AsmNodeOperands - The operands for the ISD::INLINEASM node.
4042 std::vector<SDOperand> AsmNodeOperands;
4043 AsmNodeOperands.push_back(SDOperand()); // reserve space for input chain
4044 AsmNodeOperands.push_back(
4045 DAG.getTargetExternalSymbol(IA->getAsmString().c_str(), MVT::Other));
4046
Chris Lattner2cc2f662006-02-01 01:28:23 +00004047
Chris Lattner0f0b7d42006-02-21 23:12:12 +00004048 // Loop over all of the inputs, copying the operand values into the
4049 // appropriate registers and processing the output regs.
Chris Lattner864635a2006-02-22 22:37:12 +00004050 RegsForValue RetValRegs;
Chris Lattner41f62592008-04-29 04:29:54 +00004051
Chris Lattner0c583402007-04-28 20:49:53 +00004052 // IndirectStoresToEmit - The set of stores to emit after the inline asm node.
4053 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
4054
4055 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
Evan Cheng5c807602008-02-26 02:33:44 +00004056 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
Chris Lattner1efa40f2006-02-22 00:56:39 +00004057
Chris Lattner0c583402007-04-28 20:49:53 +00004058 switch (OpInfo.Type) {
Chris Lattner2cc2f662006-02-01 01:28:23 +00004059 case InlineAsm::isOutput: {
Chris Lattnerc83994e2007-04-28 21:03:16 +00004060 if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass &&
4061 OpInfo.ConstraintType != TargetLowering::C_Register) {
Chris Lattnerf2f3cd52007-04-28 06:08:13 +00004062 // Memory output, or 'other' output (e.g. 'X' constraint).
Chris Lattner09e4b7e2007-04-28 21:12:06 +00004063 assert(OpInfo.isIndirect && "Memory output must be indirect operand");
Chris Lattner22873462006-02-27 23:45:39 +00004064
Chris Lattner22873462006-02-27 23:45:39 +00004065 // Add information to the INLINEASM node to know about this output.
4066 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
Chris Lattnerc90233b2007-05-15 01:33:58 +00004067 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
4068 TLI.getPointerTy()));
Chris Lattner09e4b7e2007-04-28 21:12:06 +00004069 AsmNodeOperands.push_back(OpInfo.CallOperand);
Chris Lattner22873462006-02-27 23:45:39 +00004070 break;
4071 }
4072
Chris Lattner2a600be2007-04-28 21:01:43 +00004073 // Otherwise, this is a register or register class output.
Chris Lattner22873462006-02-27 23:45:39 +00004074
Chris Lattner864635a2006-02-22 22:37:12 +00004075 // Copy the output from the appropriate register. Find a register that
Chris Lattner1efa40f2006-02-22 00:56:39 +00004076 // we can use.
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004077 if (OpInfo.AssignedRegs.Regs.empty()) {
Bill Wendling832171c2006-12-07 20:04:42 +00004078 cerr << "Couldn't allocate output reg for contraint '"
Chris Lattner0c583402007-04-28 20:49:53 +00004079 << OpInfo.ConstraintCode << "'!\n";
Chris Lattnerd03f1582006-10-31 07:33:13 +00004080 exit(1);
4081 }
Chris Lattner1efa40f2006-02-22 00:56:39 +00004082
Chris Lattner41f62592008-04-29 04:29:54 +00004083 // If this is an indirect operand, store through the pointer after the
4084 // asm.
4085 if (OpInfo.isIndirect) {
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004086 IndirectStoresToEmit.push_back(std::make_pair(OpInfo.AssignedRegs,
Chris Lattner0c583402007-04-28 20:49:53 +00004087 OpInfo.CallOperandVal));
Chris Lattner41f62592008-04-29 04:29:54 +00004088 } else {
4089 // This is the result value of the call.
4090 assert(CS.getType() != Type::VoidTy && "Bad inline asm!");
4091 // Concatenate this output onto the outputs list.
4092 RetValRegs.append(OpInfo.AssignedRegs);
Chris Lattner2cc2f662006-02-01 01:28:23 +00004093 }
Chris Lattner6656dd12006-01-31 02:03:41 +00004094
4095 // Add information to the INLINEASM node to know that this register is
4096 // set.
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004097 OpInfo.AssignedRegs.AddInlineAsmOperands(2 /*REGDEF*/, DAG,
4098 AsmNodeOperands);
Chris Lattner6656dd12006-01-31 02:03:41 +00004099 break;
4100 }
4101 case InlineAsm::isInput: {
Chris Lattner0c583402007-04-28 20:49:53 +00004102 SDOperand InOperandVal = OpInfo.CallOperand;
Chris Lattner3d81fee2006-02-04 02:16:44 +00004103
Chris Lattner0c583402007-04-28 20:49:53 +00004104 if (isdigit(OpInfo.ConstraintCode[0])) { // Matching constraint?
Chris Lattner2223aea2006-02-02 00:25:23 +00004105 // If this is required to match an output register we have already set,
4106 // just use its register.
Chris Lattner0c583402007-04-28 20:49:53 +00004107 unsigned OperandNo = atoi(OpInfo.ConstraintCode.c_str());
Chris Lattner3d81fee2006-02-04 02:16:44 +00004108
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00004109 // Scan until we find the definition we already emitted of this operand.
4110 // When we find it, create a RegsForValue operand.
4111 unsigned CurOp = 2; // The first operand.
4112 for (; OperandNo; --OperandNo) {
4113 // Advance to the next operand.
4114 unsigned NumOps =
4115 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
Chris Lattnera15cf702006-07-20 19:02:21 +00004116 assert(((NumOps & 7) == 2 /*REGDEF*/ ||
4117 (NumOps & 7) == 4 /*MEM*/) &&
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00004118 "Skipped past definitions?");
4119 CurOp += (NumOps>>3)+1;
4120 }
4121
4122 unsigned NumOps =
4123 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
Chris Lattner527fae12007-02-01 01:21:12 +00004124 if ((NumOps & 7) == 2 /*REGDEF*/) {
4125 // Add NumOps>>3 registers to MatchedRegs.
4126 RegsForValue MatchedRegs;
Dan Gohman23ce5022008-04-25 18:27:55 +00004127 MatchedRegs.TLI = &TLI;
Dan Gohman1fa850b2008-05-02 00:03:54 +00004128 MatchedRegs.ValueVTs.push_back(InOperandVal.getValueType());
4129 MatchedRegs.RegVTs.push_back(AsmNodeOperands[CurOp+1].getValueType());
Chris Lattner527fae12007-02-01 01:21:12 +00004130 for (unsigned i = 0, e = NumOps>>3; i != e; ++i) {
4131 unsigned Reg =
4132 cast<RegisterSDNode>(AsmNodeOperands[++CurOp])->getReg();
4133 MatchedRegs.Regs.push_back(Reg);
4134 }
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00004135
Chris Lattner527fae12007-02-01 01:21:12 +00004136 // Use the produced MatchedRegs object to
Dan Gohmanb6f5b002007-06-28 23:29:44 +00004137 MatchedRegs.getCopyToRegs(InOperandVal, DAG, Chain, &Flag);
Chris Lattner527fae12007-02-01 01:21:12 +00004138 MatchedRegs.AddInlineAsmOperands(1 /*REGUSE*/, DAG, AsmNodeOperands);
4139 break;
4140 } else {
4141 assert((NumOps & 7) == 4/*MEM*/ && "Unknown matching constraint!");
Chris Lattnerf9853bc2008-02-21 05:27:19 +00004142 assert((NumOps >> 3) == 1 && "Unexpected number of operands");
4143 // Add information to the INLINEASM node to know about this input.
4144 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
4145 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
4146 TLI.getPointerTy()));
4147 AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
4148 break;
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00004149 }
Chris Lattner2223aea2006-02-02 00:25:23 +00004150 }
Chris Lattner87bc3bd2006-02-24 01:11:24 +00004151
Chris Lattner2a600be2007-04-28 21:01:43 +00004152 if (OpInfo.ConstraintType == TargetLowering::C_Other) {
Chris Lattner0c583402007-04-28 20:49:53 +00004153 assert(!OpInfo.isIndirect &&
Chris Lattner44b2c502007-04-28 06:42:38 +00004154 "Don't know how to handle indirect other inputs yet!");
4155
Chris Lattner48884cd2007-08-25 00:47:38 +00004156 std::vector<SDOperand> Ops;
4157 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode[0],
4158 Ops, DAG);
4159 if (Ops.empty()) {
Bill Wendling832171c2006-12-07 20:04:42 +00004160 cerr << "Invalid operand for inline asm constraint '"
Chris Lattner0c583402007-04-28 20:49:53 +00004161 << OpInfo.ConstraintCode << "'!\n";
Chris Lattner53069fb2006-10-31 19:41:18 +00004162 exit(1);
4163 }
Chris Lattner87bc3bd2006-02-24 01:11:24 +00004164
4165 // Add information to the INLINEASM node to know about this input.
Chris Lattner48884cd2007-08-25 00:47:38 +00004166 unsigned ResOpType = 3 /*IMM*/ | (Ops.size() << 3);
Chris Lattnerc90233b2007-05-15 01:33:58 +00004167 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
4168 TLI.getPointerTy()));
Chris Lattner48884cd2007-08-25 00:47:38 +00004169 AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end());
Chris Lattner87bc3bd2006-02-24 01:11:24 +00004170 break;
Chris Lattner2a600be2007-04-28 21:01:43 +00004171 } else if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
Chris Lattner09e4b7e2007-04-28 21:12:06 +00004172 assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
Chris Lattner44b2c502007-04-28 06:42:38 +00004173 assert(InOperandVal.getValueType() == TLI.getPointerTy() &&
4174 "Memory operands expect pointer values");
4175
Chris Lattner87bc3bd2006-02-24 01:11:24 +00004176 // Add information to the INLINEASM node to know about this input.
4177 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
Chris Lattnerc90233b2007-05-15 01:33:58 +00004178 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
4179 TLI.getPointerTy()));
Chris Lattner87bc3bd2006-02-24 01:11:24 +00004180 AsmNodeOperands.push_back(InOperandVal);
4181 break;
4182 }
4183
Chris Lattner2a600be2007-04-28 21:01:43 +00004184 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
4185 OpInfo.ConstraintType == TargetLowering::C_Register) &&
4186 "Unknown constraint type!");
Chris Lattner0c583402007-04-28 20:49:53 +00004187 assert(!OpInfo.isIndirect &&
Chris Lattner44b2c502007-04-28 06:42:38 +00004188 "Don't know how to handle indirect register inputs yet!");
Chris Lattner87bc3bd2006-02-24 01:11:24 +00004189
4190 // Copy the input into the appropriate registers.
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004191 assert(!OpInfo.AssignedRegs.Regs.empty() &&
4192 "Couldn't allocate input reg!");
Chris Lattner87bc3bd2006-02-24 01:11:24 +00004193
Dan Gohmanb6f5b002007-06-28 23:29:44 +00004194 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, Chain, &Flag);
Chris Lattner87bc3bd2006-02-24 01:11:24 +00004195
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004196 OpInfo.AssignedRegs.AddInlineAsmOperands(1/*REGUSE*/, DAG,
4197 AsmNodeOperands);
Chris Lattner6656dd12006-01-31 02:03:41 +00004198 break;
4199 }
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00004200 case InlineAsm::isClobber: {
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00004201 // Add the clobbered value to the operand list, so that the register
4202 // allocator is aware that the physreg got clobbered.
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004203 if (!OpInfo.AssignedRegs.Regs.empty())
4204 OpInfo.AssignedRegs.AddInlineAsmOperands(2/*REGDEF*/, DAG,
4205 AsmNodeOperands);
Chris Lattner6656dd12006-01-31 02:03:41 +00004206 break;
4207 }
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00004208 }
Chris Lattner6656dd12006-01-31 02:03:41 +00004209 }
Chris Lattnerce7518c2006-01-26 22:24:51 +00004210
4211 // Finish up input operands.
4212 AsmNodeOperands[0] = Chain;
4213 if (Flag.Val) AsmNodeOperands.push_back(Flag);
4214
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00004215 Chain = DAG.getNode(ISD::INLINEASM,
4216 DAG.getNodeValueTypes(MVT::Other, MVT::Flag), 2,
Chris Lattnerbd564bf2006-08-08 02:23:42 +00004217 &AsmNodeOperands[0], AsmNodeOperands.size());
Chris Lattnerce7518c2006-01-26 22:24:51 +00004218 Flag = Chain.getValue(1);
4219
Chris Lattner6656dd12006-01-31 02:03:41 +00004220 // If this asm returns a register value, copy the result from that register
4221 // and set it as the value of the call.
Chris Lattner3a508c92007-04-12 06:00:20 +00004222 if (!RetValRegs.Regs.empty()) {
Dan Gohmanb6f5b002007-06-28 23:29:44 +00004223 SDOperand Val = RetValRegs.getCopyFromRegs(DAG, Chain, &Flag);
Chris Lattner3fb29682008-04-29 04:48:56 +00004224
4225 // If any of the results of the inline asm is a vector, it may have the
4226 // wrong width/num elts. This can happen for register classes that can
4227 // contain multiple different value types. The preg or vreg allocated may
4228 // not have the same VT as was expected. Convert it to the right type with
Dan Gohman7f321562007-06-25 16:23:39 +00004229 // bit_convert.
Chris Lattner3fb29682008-04-29 04:48:56 +00004230 if (const StructType *ResSTy = dyn_cast<StructType>(CS.getType())) {
4231 for (unsigned i = 0, e = ResSTy->getNumElements(); i != e; ++i) {
Duncan Sands83ec4b62008-06-06 12:08:01 +00004232 if (Val.Val->getValueType(i).isVector())
Chris Lattner3fb29682008-04-29 04:48:56 +00004233 Val = DAG.getNode(ISD::BIT_CONVERT,
4234 TLI.getValueType(ResSTy->getElementType(i)), Val);
4235 }
4236 } else {
Duncan Sands83ec4b62008-06-06 12:08:01 +00004237 if (Val.getValueType().isVector())
Chris Lattner3fb29682008-04-29 04:48:56 +00004238 Val = DAG.getNode(ISD::BIT_CONVERT, TLI.getValueType(CS.getType()),
4239 Val);
Chris Lattner3a508c92007-04-12 06:00:20 +00004240 }
Chris Lattner3fb29682008-04-29 04:48:56 +00004241
Duncan Sandsfd7b3262007-12-17 18:08:19 +00004242 setValue(CS.getInstruction(), Val);
Chris Lattner3a508c92007-04-12 06:00:20 +00004243 }
Chris Lattnerce7518c2006-01-26 22:24:51 +00004244
Chris Lattner6656dd12006-01-31 02:03:41 +00004245 std::vector<std::pair<SDOperand, Value*> > StoresToEmit;
4246
4247 // Process indirect outputs, first output all of the flagged copies out of
4248 // physregs.
4249 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
Chris Lattner864635a2006-02-22 22:37:12 +00004250 RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
Chris Lattner6656dd12006-01-31 02:03:41 +00004251 Value *Ptr = IndirectStoresToEmit[i].second;
Dan Gohmanb6f5b002007-06-28 23:29:44 +00004252 SDOperand OutVal = OutRegs.getCopyFromRegs(DAG, Chain, &Flag);
Chris Lattner864635a2006-02-22 22:37:12 +00004253 StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
Chris Lattner6656dd12006-01-31 02:03:41 +00004254 }
4255
4256 // Emit the non-flagged stores from the physregs.
Chris Lattnerbd564bf2006-08-08 02:23:42 +00004257 SmallVector<SDOperand, 8> OutChains;
Chris Lattner6656dd12006-01-31 02:03:41 +00004258 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i)
Chris Lattner0c583402007-04-28 20:49:53 +00004259 OutChains.push_back(DAG.getStore(Chain, StoresToEmit[i].first,
Chris Lattner6656dd12006-01-31 02:03:41 +00004260 getValue(StoresToEmit[i].second),
Evan Cheng8b2794a2006-10-13 21:14:26 +00004261 StoresToEmit[i].second, 0));
Chris Lattner6656dd12006-01-31 02:03:41 +00004262 if (!OutChains.empty())
Chris Lattnerbd564bf2006-08-08 02:23:42 +00004263 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
4264 &OutChains[0], OutChains.size());
Chris Lattnerce7518c2006-01-26 22:24:51 +00004265 DAG.setRoot(Chain);
4266}
4267
4268
Chris Lattner1c08c712005-01-07 07:47:53 +00004269void SelectionDAGLowering::visitMalloc(MallocInst &I) {
4270 SDOperand Src = getValue(I.getOperand(0));
4271
Duncan Sands83ec4b62008-06-06 12:08:01 +00004272 MVT IntPtr = TLI.getPointerTy();
Chris Lattner68cd65e2005-01-22 23:04:37 +00004273
4274 if (IntPtr < Src.getValueType())
4275 Src = DAG.getNode(ISD::TRUNCATE, IntPtr, Src);
4276 else if (IntPtr > Src.getValueType())
4277 Src = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, Src);
Chris Lattner1c08c712005-01-07 07:47:53 +00004278
4279 // Scale the source by the type size.
Duncan Sands514ab342007-11-01 20:53:16 +00004280 uint64_t ElementSize = TD->getABITypeSize(I.getType()->getElementType());
Chris Lattner1c08c712005-01-07 07:47:53 +00004281 Src = DAG.getNode(ISD::MUL, Src.getValueType(),
Chris Lattner0bd48932008-01-17 07:00:52 +00004282 Src, DAG.getIntPtrConstant(ElementSize));
Chris Lattner1c08c712005-01-07 07:47:53 +00004283
Reid Spencer47857812006-12-31 05:55:36 +00004284 TargetLowering::ArgListTy Args;
4285 TargetLowering::ArgListEntry Entry;
4286 Entry.Node = Src;
4287 Entry.Ty = TLI.getTargetData()->getIntPtrType();
Reid Spencer47857812006-12-31 05:55:36 +00004288 Args.push_back(Entry);
Chris Lattnercf5734d2005-01-08 19:26:18 +00004289
4290 std::pair<SDOperand,SDOperand> Result =
Duncan Sands00fee652008-02-14 17:28:50 +00004291 TLI.LowerCallTo(getRoot(), I.getType(), false, false, false, CallingConv::C,
4292 true, DAG.getExternalSymbol("malloc", IntPtr), Args, DAG);
Chris Lattnercf5734d2005-01-08 19:26:18 +00004293 setValue(&I, Result.first); // Pointers always fit in registers
4294 DAG.setRoot(Result.second);
Chris Lattner1c08c712005-01-07 07:47:53 +00004295}
4296
4297void SelectionDAGLowering::visitFree(FreeInst &I) {
Reid Spencer47857812006-12-31 05:55:36 +00004298 TargetLowering::ArgListTy Args;
4299 TargetLowering::ArgListEntry Entry;
4300 Entry.Node = getValue(I.getOperand(0));
4301 Entry.Ty = TLI.getTargetData()->getIntPtrType();
Reid Spencer47857812006-12-31 05:55:36 +00004302 Args.push_back(Entry);
Duncan Sands83ec4b62008-06-06 12:08:01 +00004303 MVT IntPtr = TLI.getPointerTy();
Chris Lattnercf5734d2005-01-08 19:26:18 +00004304 std::pair<SDOperand,SDOperand> Result =
Duncan Sands00fee652008-02-14 17:28:50 +00004305 TLI.LowerCallTo(getRoot(), Type::VoidTy, false, false, false,
4306 CallingConv::C, true,
Chris Lattnercf5734d2005-01-08 19:26:18 +00004307 DAG.getExternalSymbol("free", IntPtr), Args, DAG);
4308 DAG.setRoot(Result.second);
Chris Lattner1c08c712005-01-07 07:47:53 +00004309}
4310
Evan Chengff9b3732008-01-30 18:18:23 +00004311// EmitInstrWithCustomInserter - This method should be implemented by targets
4312// that mark instructions with the 'usesCustomDAGSchedInserter' flag. These
Chris Lattner025c39b2005-08-26 20:54:47 +00004313// instructions are special in various ways, which require special support to
4314// insert. The specified MachineInstr is created but not inserted into any
4315// basic blocks, and the scheduler passes ownership of it to this method.
Evan Chengff9b3732008-01-30 18:18:23 +00004316MachineBasicBlock *TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
Chris Lattner025c39b2005-08-26 20:54:47 +00004317 MachineBasicBlock *MBB) {
Bill Wendling832171c2006-12-07 20:04:42 +00004318 cerr << "If a target marks an instruction with "
4319 << "'usesCustomDAGSchedInserter', it must implement "
Evan Chengff9b3732008-01-30 18:18:23 +00004320 << "TargetLowering::EmitInstrWithCustomInserter!\n";
Chris Lattner025c39b2005-08-26 20:54:47 +00004321 abort();
4322 return 0;
4323}
4324
Chris Lattner39ae3622005-01-09 00:00:49 +00004325void SelectionDAGLowering::visitVAStart(CallInst &I) {
Nate Begemanacc398c2006-01-25 18:21:52 +00004326 DAG.setRoot(DAG.getNode(ISD::VASTART, MVT::Other, getRoot(),
4327 getValue(I.getOperand(1)),
4328 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner39ae3622005-01-09 00:00:49 +00004329}
4330
4331void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
Nate Begemanacc398c2006-01-25 18:21:52 +00004332 SDOperand V = DAG.getVAArg(TLI.getValueType(I.getType()), getRoot(),
4333 getValue(I.getOperand(0)),
4334 DAG.getSrcValue(I.getOperand(0)));
4335 setValue(&I, V);
4336 DAG.setRoot(V.getValue(1));
Chris Lattner1c08c712005-01-07 07:47:53 +00004337}
4338
4339void SelectionDAGLowering::visitVAEnd(CallInst &I) {
Nate Begemanacc398c2006-01-25 18:21:52 +00004340 DAG.setRoot(DAG.getNode(ISD::VAEND, MVT::Other, getRoot(),
4341 getValue(I.getOperand(1)),
4342 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner1c08c712005-01-07 07:47:53 +00004343}
4344
4345void SelectionDAGLowering::visitVACopy(CallInst &I) {
Nate Begemanacc398c2006-01-25 18:21:52 +00004346 DAG.setRoot(DAG.getNode(ISD::VACOPY, MVT::Other, getRoot(),
4347 getValue(I.getOperand(1)),
4348 getValue(I.getOperand(2)),
4349 DAG.getSrcValue(I.getOperand(1)),
4350 DAG.getSrcValue(I.getOperand(2))));
Chris Lattner1c08c712005-01-07 07:47:53 +00004351}
4352
Chris Lattnerfdfded52006-04-12 16:20:43 +00004353/// TargetLowering::LowerArguments - This is the default LowerArguments
4354/// implementation, which just inserts a FORMAL_ARGUMENTS node. FIXME: When all
Chris Lattnerf4ec8172006-05-16 22:53:20 +00004355/// targets are migrated to using FORMAL_ARGUMENTS, this hook should be
4356/// integrated into SDISel.
Chris Lattnerfdfded52006-04-12 16:20:43 +00004357std::vector<SDOperand>
4358TargetLowering::LowerArguments(Function &F, SelectionDAG &DAG) {
4359 // Add CC# and isVararg as operands to the FORMAL_ARGUMENTS node.
4360 std::vector<SDOperand> Ops;
Chris Lattner8c0c10c2006-05-16 06:45:34 +00004361 Ops.push_back(DAG.getRoot());
Chris Lattnerfdfded52006-04-12 16:20:43 +00004362 Ops.push_back(DAG.getConstant(F.getCallingConv(), getPointerTy()));
4363 Ops.push_back(DAG.getConstant(F.isVarArg(), getPointerTy()));
4364
4365 // Add one result value for each formal argument.
Duncan Sands83ec4b62008-06-06 12:08:01 +00004366 std::vector<MVT> RetVals;
Anton Korobeynikov6aa279d2007-01-28 18:01:49 +00004367 unsigned j = 1;
Anton Korobeynikovac2b2cf2007-01-28 16:04:40 +00004368 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end();
4369 I != E; ++I, ++j) {
Duncan Sands83ec4b62008-06-06 12:08:01 +00004370 MVT VT = getValueType(I->getType());
Duncan Sands276dcbd2008-03-21 09:14:45 +00004371 ISD::ArgFlagsTy Flags;
Lauro Ramos Venancio7aa47b62007-02-13 13:50:08 +00004372 unsigned OriginalAlignment =
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00004373 getTargetData()->getABITypeAlignment(I->getType());
Lauro Ramos Venancio7aa47b62007-02-13 13:50:08 +00004374
Duncan Sandsafa3b6d2007-11-28 17:07:01 +00004375 if (F.paramHasAttr(j, ParamAttr::ZExt))
Duncan Sands276dcbd2008-03-21 09:14:45 +00004376 Flags.setZExt();
Duncan Sandsafa3b6d2007-11-28 17:07:01 +00004377 if (F.paramHasAttr(j, ParamAttr::SExt))
Duncan Sands276dcbd2008-03-21 09:14:45 +00004378 Flags.setSExt();
Duncan Sandsafa3b6d2007-11-28 17:07:01 +00004379 if (F.paramHasAttr(j, ParamAttr::InReg))
Duncan Sands276dcbd2008-03-21 09:14:45 +00004380 Flags.setInReg();
Duncan Sandsafa3b6d2007-11-28 17:07:01 +00004381 if (F.paramHasAttr(j, ParamAttr::StructRet))
Duncan Sands276dcbd2008-03-21 09:14:45 +00004382 Flags.setSRet();
Duncan Sandsafa3b6d2007-11-28 17:07:01 +00004383 if (F.paramHasAttr(j, ParamAttr::ByVal)) {
Duncan Sands276dcbd2008-03-21 09:14:45 +00004384 Flags.setByVal();
Rafael Espindola594d37e2007-08-10 14:44:42 +00004385 const PointerType *Ty = cast<PointerType>(I->getType());
Duncan Sandsa41d7192008-01-13 21:19:59 +00004386 const Type *ElementTy = Ty->getElementType();
Duncan Sands276dcbd2008-03-21 09:14:45 +00004387 unsigned FrameAlign = getByValTypeAlignment(ElementTy);
Duncan Sandsa41d7192008-01-13 21:19:59 +00004388 unsigned FrameSize = getTargetData()->getABITypeSize(ElementTy);
Dale Johannesen08e78b12008-02-22 17:49:45 +00004389 // For ByVal, alignment should be passed from FE. BE will guess if
4390 // this info is not there but there are cases it cannot get right.
4391 if (F.getParamAlignment(j))
Duncan Sands276dcbd2008-03-21 09:14:45 +00004392 FrameAlign = F.getParamAlignment(j);
4393 Flags.setByValAlign(FrameAlign);
4394 Flags.setByValSize(FrameSize);
Rafael Espindola594d37e2007-08-10 14:44:42 +00004395 }
Duncan Sandsafa3b6d2007-11-28 17:07:01 +00004396 if (F.paramHasAttr(j, ParamAttr::Nest))
Duncan Sands276dcbd2008-03-21 09:14:45 +00004397 Flags.setNest();
4398 Flags.setOrigAlign(OriginalAlignment);
Duncan Sandsb988bac2008-02-11 20:58:28 +00004399
Duncan Sands83ec4b62008-06-06 12:08:01 +00004400 MVT RegisterVT = getRegisterType(VT);
Duncan Sandsb988bac2008-02-11 20:58:28 +00004401 unsigned NumRegs = getNumRegisters(VT);
4402 for (unsigned i = 0; i != NumRegs; ++i) {
4403 RetVals.push_back(RegisterVT);
Nicolas Geoffray9701c8a2008-04-14 17:17:14 +00004404 ISD::ArgFlagsTy MyFlags = Flags;
Nicolas Geoffrayc0cb28f2008-04-13 13:40:22 +00004405 if (NumRegs > 1 && i == 0)
Nicolas Geoffray6ccbbd82008-04-15 08:08:50 +00004406 MyFlags.setSplit();
Duncan Sandsb988bac2008-02-11 20:58:28 +00004407 // if it isn't first piece, alignment must be 1
Nicolas Geoffrayc0cb28f2008-04-13 13:40:22 +00004408 else if (i > 0)
Nicolas Geoffray9701c8a2008-04-14 17:17:14 +00004409 MyFlags.setOrigAlign(1);
4410 Ops.push_back(DAG.getArgFlags(MyFlags));
Dan Gohmanb6f5b002007-06-28 23:29:44 +00004411 }
Chris Lattnerfdfded52006-04-12 16:20:43 +00004412 }
Evan Cheng3b0d2862006-04-25 23:03:35 +00004413
Chris Lattner8c0c10c2006-05-16 06:45:34 +00004414 RetVals.push_back(MVT::Other);
Chris Lattnerfdfded52006-04-12 16:20:43 +00004415
4416 // Create the node.
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00004417 SDNode *Result = DAG.getNode(ISD::FORMAL_ARGUMENTS,
Chris Lattner86ca3ca2008-02-13 07:39:09 +00004418 DAG.getVTList(&RetVals[0], RetVals.size()),
Chris Lattnerbd564bf2006-08-08 02:23:42 +00004419 &Ops[0], Ops.size()).Val;
Chris Lattner86ca3ca2008-02-13 07:39:09 +00004420
4421 // Prelower FORMAL_ARGUMENTS. This isn't required for functionality, but
4422 // allows exposing the loads that may be part of the argument access to the
4423 // first DAGCombiner pass.
4424 SDOperand TmpRes = LowerOperation(SDOperand(Result, 0), DAG);
4425
4426 // The number of results should match up, except that the lowered one may have
4427 // an extra flag result.
4428 assert((Result->getNumValues() == TmpRes.Val->getNumValues() ||
4429 (Result->getNumValues()+1 == TmpRes.Val->getNumValues() &&
4430 TmpRes.getValue(Result->getNumValues()).getValueType() == MVT::Flag))
4431 && "Lowering produced unexpected number of results!");
4432 Result = TmpRes.Val;
4433
Dan Gohman27a70be2007-07-02 16:18:06 +00004434 unsigned NumArgRegs = Result->getNumValues() - 1;
4435 DAG.setRoot(SDOperand(Result, NumArgRegs));
Chris Lattnerfdfded52006-04-12 16:20:43 +00004436
4437 // Set up the return result vector.
4438 Ops.clear();
4439 unsigned i = 0;
Reid Spencer47857812006-12-31 05:55:36 +00004440 unsigned Idx = 1;
4441 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E;
4442 ++I, ++Idx) {
Duncan Sands83ec4b62008-06-06 12:08:01 +00004443 MVT VT = getValueType(I->getType());
4444 MVT PartVT = getRegisterType(VT);
Duncan Sandsb988bac2008-02-11 20:58:28 +00004445
4446 unsigned NumParts = getNumRegisters(VT);
4447 SmallVector<SDOperand, 4> Parts(NumParts);
4448 for (unsigned j = 0; j != NumParts; ++j)
4449 Parts[j] = SDOperand(Result, i++);
4450
4451 ISD::NodeType AssertOp = ISD::DELETED_NODE;
4452 if (F.paramHasAttr(Idx, ParamAttr::SExt))
4453 AssertOp = ISD::AssertSext;
4454 else if (F.paramHasAttr(Idx, ParamAttr::ZExt))
4455 AssertOp = ISD::AssertZext;
4456
4457 Ops.push_back(getCopyFromParts(DAG, &Parts[0], NumParts, PartVT, VT,
Chris Lattner4468c1f2008-03-09 09:38:46 +00004458 AssertOp));
Chris Lattnerfdfded52006-04-12 16:20:43 +00004459 }
Dan Gohman27a70be2007-07-02 16:18:06 +00004460 assert(i == NumArgRegs && "Argument register count mismatch!");
Chris Lattnerfdfded52006-04-12 16:20:43 +00004461 return Ops;
4462}
4463
Chris Lattnerf4ec8172006-05-16 22:53:20 +00004464
4465/// TargetLowering::LowerCallTo - This is the default LowerCallTo
4466/// implementation, which just inserts an ISD::CALL node, which is later custom
4467/// lowered by the target to something concrete. FIXME: When all targets are
4468/// migrated to using ISD::CALL, this hook should be integrated into SDISel.
4469std::pair<SDOperand, SDOperand>
Duncan Sands00fee652008-02-14 17:28:50 +00004470TargetLowering::LowerCallTo(SDOperand Chain, const Type *RetTy,
4471 bool RetSExt, bool RetZExt, bool isVarArg,
4472 unsigned CallingConv, bool isTailCall,
Chris Lattnerf4ec8172006-05-16 22:53:20 +00004473 SDOperand Callee,
4474 ArgListTy &Args, SelectionDAG &DAG) {
Chris Lattnerbe384162006-08-16 22:57:46 +00004475 SmallVector<SDOperand, 32> Ops;
Chris Lattnerf4ec8172006-05-16 22:53:20 +00004476 Ops.push_back(Chain); // Op#0 - Chain
4477 Ops.push_back(DAG.getConstant(CallingConv, getPointerTy())); // Op#1 - CC
4478 Ops.push_back(DAG.getConstant(isVarArg, getPointerTy())); // Op#2 - VarArg
4479 Ops.push_back(DAG.getConstant(isTailCall, getPointerTy())); // Op#3 - Tail
4480 Ops.push_back(Callee);
4481
4482 // Handle all of the outgoing arguments.
4483 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
Duncan Sands83ec4b62008-06-06 12:08:01 +00004484 MVT VT = getValueType(Args[i].Ty);
Reid Spencer47857812006-12-31 05:55:36 +00004485 SDOperand Op = Args[i].Node;
Duncan Sands276dcbd2008-03-21 09:14:45 +00004486 ISD::ArgFlagsTy Flags;
Lauro Ramos Venancio7aa47b62007-02-13 13:50:08 +00004487 unsigned OriginalAlignment =
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00004488 getTargetData()->getABITypeAlignment(Args[i].Ty);
Duncan Sands276dcbd2008-03-21 09:14:45 +00004489
Anton Korobeynikovd0b82b32007-03-07 16:25:09 +00004490 if (Args[i].isZExt)
Duncan Sands276dcbd2008-03-21 09:14:45 +00004491 Flags.setZExt();
4492 if (Args[i].isSExt)
4493 Flags.setSExt();
Anton Korobeynikov0db79d82007-03-06 06:10:33 +00004494 if (Args[i].isInReg)
Duncan Sands276dcbd2008-03-21 09:14:45 +00004495 Flags.setInReg();
Anton Korobeynikov0db79d82007-03-06 06:10:33 +00004496 if (Args[i].isSRet)
Duncan Sands276dcbd2008-03-21 09:14:45 +00004497 Flags.setSRet();
Rafael Espindola21485be2007-08-20 15:18:24 +00004498 if (Args[i].isByVal) {
Duncan Sands276dcbd2008-03-21 09:14:45 +00004499 Flags.setByVal();
Rafael Espindola21485be2007-08-20 15:18:24 +00004500 const PointerType *Ty = cast<PointerType>(Args[i].Ty);
Duncan Sandsa41d7192008-01-13 21:19:59 +00004501 const Type *ElementTy = Ty->getElementType();
Duncan Sands276dcbd2008-03-21 09:14:45 +00004502 unsigned FrameAlign = getByValTypeAlignment(ElementTy);
Duncan Sandsa41d7192008-01-13 21:19:59 +00004503 unsigned FrameSize = getTargetData()->getABITypeSize(ElementTy);
Dale Johannesen08e78b12008-02-22 17:49:45 +00004504 // For ByVal, alignment should come from FE. BE will guess if this
4505 // info is not there but there are cases it cannot get right.
4506 if (Args[i].Alignment)
Duncan Sands276dcbd2008-03-21 09:14:45 +00004507 FrameAlign = Args[i].Alignment;
4508 Flags.setByValAlign(FrameAlign);
4509 Flags.setByValSize(FrameSize);
Rafael Espindola21485be2007-08-20 15:18:24 +00004510 }
Duncan Sands36397f52007-07-27 12:58:54 +00004511 if (Args[i].isNest)
Duncan Sands276dcbd2008-03-21 09:14:45 +00004512 Flags.setNest();
4513 Flags.setOrigAlign(OriginalAlignment);
Dan Gohman27a70be2007-07-02 16:18:06 +00004514
Duncan Sands83ec4b62008-06-06 12:08:01 +00004515 MVT PartVT = getRegisterType(VT);
Duncan Sandsb988bac2008-02-11 20:58:28 +00004516 unsigned NumParts = getNumRegisters(VT);
4517 SmallVector<SDOperand, 4> Parts(NumParts);
4518 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
4519
4520 if (Args[i].isSExt)
4521 ExtendKind = ISD::SIGN_EXTEND;
4522 else if (Args[i].isZExt)
4523 ExtendKind = ISD::ZERO_EXTEND;
4524
4525 getCopyToParts(DAG, Op, &Parts[0], NumParts, PartVT, ExtendKind);
4526
4527 for (unsigned i = 0; i != NumParts; ++i) {
4528 // if it isn't first piece, alignment must be 1
Duncan Sands276dcbd2008-03-21 09:14:45 +00004529 ISD::ArgFlagsTy MyFlags = Flags;
Nicolas Geoffrayc0cb28f2008-04-13 13:40:22 +00004530 if (NumParts > 1 && i == 0)
Nicolas Geoffray6ccbbd82008-04-15 08:08:50 +00004531 MyFlags.setSplit();
Nicolas Geoffrayc0cb28f2008-04-13 13:40:22 +00004532 else if (i != 0)
Duncan Sands276dcbd2008-03-21 09:14:45 +00004533 MyFlags.setOrigAlign(1);
Duncan Sandsb988bac2008-02-11 20:58:28 +00004534
4535 Ops.push_back(Parts[i]);
Duncan Sands276dcbd2008-03-21 09:14:45 +00004536 Ops.push_back(DAG.getArgFlags(MyFlags));
Dan Gohman27a70be2007-07-02 16:18:06 +00004537 }
Chris Lattnerf4ec8172006-05-16 22:53:20 +00004538 }
4539
Dan Gohmanef5d1942008-03-11 21:11:25 +00004540 // Figure out the result value types. We start by making a list of
Dan Gohman23ce5022008-04-25 18:27:55 +00004541 // the potentially illegal return value types.
Duncan Sands83ec4b62008-06-06 12:08:01 +00004542 SmallVector<MVT, 4> LoweredRetTys;
4543 SmallVector<MVT, 4> RetTys;
Dan Gohman23ce5022008-04-25 18:27:55 +00004544 ComputeValueVTs(*this, RetTy, RetTys);
Dan Gohmanef5d1942008-03-11 21:11:25 +00004545
Dan Gohman23ce5022008-04-25 18:27:55 +00004546 // Then we translate that to a list of legal types.
4547 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
Duncan Sands83ec4b62008-06-06 12:08:01 +00004548 MVT VT = RetTys[I];
4549 MVT RegisterVT = getRegisterType(VT);
Dan Gohmanef5d1942008-03-11 21:11:25 +00004550 unsigned NumRegs = getNumRegisters(VT);
4551 for (unsigned i = 0; i != NumRegs; ++i)
4552 LoweredRetTys.push_back(RegisterVT);
4553 }
Chris Lattnerf4ec8172006-05-16 22:53:20 +00004554
Dan Gohmanef5d1942008-03-11 21:11:25 +00004555 LoweredRetTys.push_back(MVT::Other); // Always has a chain.
Chris Lattnerf4ec8172006-05-16 22:53:20 +00004556
Dan Gohmanb6f5b002007-06-28 23:29:44 +00004557 // Create the CALL node.
Chris Lattnerbe384162006-08-16 22:57:46 +00004558 SDOperand Res = DAG.getNode(ISD::CALL,
Dan Gohmanef5d1942008-03-11 21:11:25 +00004559 DAG.getVTList(&LoweredRetTys[0],
4560 LoweredRetTys.size()),
Chris Lattnerbe384162006-08-16 22:57:46 +00004561 &Ops[0], Ops.size());
Dan Gohmanef5d1942008-03-11 21:11:25 +00004562 Chain = Res.getValue(LoweredRetTys.size() - 1);
Dan Gohmanb6f5b002007-06-28 23:29:44 +00004563
4564 // Gather up the call result into a single value.
4565 if (RetTy != Type::VoidTy) {
Duncan Sands00fee652008-02-14 17:28:50 +00004566 ISD::NodeType AssertOp = ISD::DELETED_NODE;
4567
4568 if (RetSExt)
4569 AssertOp = ISD::AssertSext;
4570 else if (RetZExt)
Dan Gohmanb6f5b002007-06-28 23:29:44 +00004571 AssertOp = ISD::AssertZext;
Duncan Sands00fee652008-02-14 17:28:50 +00004572
Dan Gohmanef5d1942008-03-11 21:11:25 +00004573 SmallVector<SDOperand, 4> ReturnValues;
4574 unsigned RegNo = 0;
Dan Gohman23ce5022008-04-25 18:27:55 +00004575 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
Duncan Sands83ec4b62008-06-06 12:08:01 +00004576 MVT VT = RetTys[I];
4577 MVT RegisterVT = getRegisterType(VT);
Dan Gohmanef5d1942008-03-11 21:11:25 +00004578 unsigned NumRegs = getNumRegisters(VT);
4579 unsigned RegNoEnd = NumRegs + RegNo;
4580 SmallVector<SDOperand, 4> Results;
4581 for (; RegNo != RegNoEnd; ++RegNo)
4582 Results.push_back(Res.getValue(RegNo));
4583 SDOperand ReturnValue =
4584 getCopyFromParts(DAG, &Results[0], NumRegs, RegisterVT, VT,
4585 AssertOp);
4586 ReturnValues.push_back(ReturnValue);
4587 }
4588 Res = ReturnValues.size() == 1 ? ReturnValues.front() :
4589 DAG.getNode(ISD::MERGE_VALUES,
4590 DAG.getVTList(&RetTys[0], RetTys.size()),
4591 &ReturnValues[0], ReturnValues.size());
Chris Lattnerf4ec8172006-05-16 22:53:20 +00004592 }
Dan Gohmanb6f5b002007-06-28 23:29:44 +00004593
4594 return std::make_pair(Res, Chain);
Chris Lattnerf4ec8172006-05-16 22:53:20 +00004595}
4596
Chris Lattner50381b62005-05-14 05:50:48 +00004597SDOperand TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
Chris Lattner171453a2005-01-16 07:28:41 +00004598 assert(0 && "LowerOperation not implemented for this target!");
4599 abort();
Misha Brukmand3f03e42005-02-17 21:39:27 +00004600 return SDOperand();
Chris Lattner171453a2005-01-16 07:28:41 +00004601}
4602
Nate Begeman0aed7842006-01-28 03:14:31 +00004603SDOperand TargetLowering::CustomPromoteOperation(SDOperand Op,
4604 SelectionDAG &DAG) {
4605 assert(0 && "CustomPromoteOperation not implemented for this target!");
4606 abort();
4607 return SDOperand();
4608}
4609
Chris Lattner7041ee32005-01-11 05:56:49 +00004610//===----------------------------------------------------------------------===//
4611// SelectionDAGISel code
4612//===----------------------------------------------------------------------===//
Chris Lattner1c08c712005-01-07 07:47:53 +00004613
Duncan Sands83ec4b62008-06-06 12:08:01 +00004614unsigned SelectionDAGISel::MakeReg(MVT VT) {
Chris Lattner84bc5422007-12-31 04:13:23 +00004615 return RegInfo->createVirtualRegister(TLI.getRegClassFor(VT));
Chris Lattner1c08c712005-01-07 07:47:53 +00004616}
4617
Chris Lattner495a0b52005-08-17 06:37:43 +00004618void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const {
Jim Laskeyc7c3f112006-10-16 20:52:31 +00004619 AU.addRequired<AliasAnalysis>();
Gordon Henriksence224772008-01-07 01:30:38 +00004620 AU.addRequired<CollectorModuleMetadata>();
Chris Lattnerc8d288f2007-03-31 04:18:03 +00004621 AU.setPreservesAll();
Chris Lattner495a0b52005-08-17 06:37:43 +00004622}
Chris Lattner1c08c712005-01-07 07:47:53 +00004623
Chris Lattner1c08c712005-01-07 07:47:53 +00004624bool SelectionDAGISel::runOnFunction(Function &Fn) {
Dan Gohman5f43f922007-08-27 16:26:13 +00004625 // Get alias analysis for load/store combining.
4626 AA = &getAnalysis<AliasAnalysis>();
4627
Chris Lattner1c08c712005-01-07 07:47:53 +00004628 MachineFunction &MF = MachineFunction::construct(&Fn, TLI.getTargetMachine());
Gordon Henriksence224772008-01-07 01:30:38 +00004629 if (MF.getFunction()->hasCollector())
4630 GCI = &getAnalysis<CollectorModuleMetadata>().get(*MF.getFunction());
4631 else
4632 GCI = 0;
Chris Lattner84bc5422007-12-31 04:13:23 +00004633 RegInfo = &MF.getRegInfo();
Bill Wendling832171c2006-12-07 20:04:42 +00004634 DOUT << "\n\n\n=== " << Fn.getName() << "\n";
Chris Lattner1c08c712005-01-07 07:47:53 +00004635
4636 FunctionLoweringInfo FuncInfo(TLI, Fn, MF);
4637
Dale Johannesen1532f3d2008-04-02 00:25:04 +00004638 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
4639 if (InvokeInst *Invoke = dyn_cast<InvokeInst>(I->getTerminator()))
4640 // Mark landing pad.
4641 FuncInfo.MBBMap[Invoke->getSuccessor(1)]->setIsLandingPad();
Duncan Sands9fac0b52007-06-06 10:05:18 +00004642
4643 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
Chris Lattner1c08c712005-01-07 07:47:53 +00004644 SelectBasicBlock(I, MF, FuncInfo);
Misha Brukmanedf128a2005-04-21 22:36:52 +00004645
Evan Chengad2070c2007-02-10 02:43:39 +00004646 // Add function live-ins to entry block live-in set.
4647 BasicBlock *EntryBB = &Fn.getEntryBlock();
4648 BB = FuncInfo.MBBMap[EntryBB];
Chris Lattner84bc5422007-12-31 04:13:23 +00004649 if (!RegInfo->livein_empty())
4650 for (MachineRegisterInfo::livein_iterator I = RegInfo->livein_begin(),
4651 E = RegInfo->livein_end(); I != E; ++I)
Evan Chengad2070c2007-02-10 02:43:39 +00004652 BB->addLiveIn(I->first);
4653
Duncan Sandsf4070822007-06-15 19:04:19 +00004654#ifndef NDEBUG
4655 assert(FuncInfo.CatchInfoFound.size() == FuncInfo.CatchInfoLost.size() &&
4656 "Not all catch info was assigned to a landing pad!");
4657#endif
4658
Chris Lattner1c08c712005-01-07 07:47:53 +00004659 return true;
4660}
4661
Chris Lattner6833b062008-04-28 07:16:35 +00004662void SelectionDAGLowering::CopyValueToVirtualRegister(Value *V, unsigned Reg) {
Chris Lattner571e4342006-10-27 21:36:01 +00004663 SDOperand Op = getValue(V);
Chris Lattner18c2f132005-01-13 20:50:02 +00004664 assert((Op.getOpcode() != ISD::CopyFromReg ||
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00004665 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
Chris Lattner18c2f132005-01-13 20:50:02 +00004666 "Copy from a reg to the same reg!");
Dan Gohman86e1ebf2008-03-27 19:56:19 +00004667 assert(!TargetRegisterInfo::isPhysicalRegister(Reg) && "Is a physreg");
Dan Gohmanb6f5b002007-06-28 23:29:44 +00004668
Dan Gohman23ce5022008-04-25 18:27:55 +00004669 RegsForValue RFV(TLI, Reg, V->getType());
4670 SDOperand Chain = DAG.getEntryNode();
4671 RFV.getCopyToRegs(Op, DAG, Chain, 0);
4672 PendingExports.push_back(Chain);
Chris Lattner1c08c712005-01-07 07:47:53 +00004673}
4674
Chris Lattner068a81e2005-01-17 17:15:02 +00004675void SelectionDAGISel::
Dan Gohman86e1ebf2008-03-27 19:56:19 +00004676LowerArguments(BasicBlock *LLVMBB, SelectionDAGLowering &SDL) {
Chris Lattner068a81e2005-01-17 17:15:02 +00004677 // If this is the entry block, emit arguments.
Evan Cheng15699fc2007-02-10 01:08:18 +00004678 Function &F = *LLVMBB->getParent();
Chris Lattner0afa8e32005-01-17 17:55:19 +00004679 FunctionLoweringInfo &FuncInfo = SDL.FuncInfo;
Chris Lattnerbf209482005-10-30 19:42:35 +00004680 SDOperand OldRoot = SDL.DAG.getRoot();
4681 std::vector<SDOperand> Args = TLI.LowerArguments(F, SDL.DAG);
Chris Lattner068a81e2005-01-17 17:15:02 +00004682
Chris Lattnerbf209482005-10-30 19:42:35 +00004683 unsigned a = 0;
4684 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
4685 AI != E; ++AI, ++a)
4686 if (!AI->use_empty()) {
4687 SDL.setValue(AI, Args[a]);
Evan Chengf7179bb2006-04-27 08:29:42 +00004688
Chris Lattnerbf209482005-10-30 19:42:35 +00004689 // If this argument is live outside of the entry block, insert a copy from
4690 // whereever we got it to the vreg that other BB's will reference it as.
Chris Lattner251db182007-02-25 18:40:32 +00004691 DenseMap<const Value*, unsigned>::iterator VMI=FuncInfo.ValueMap.find(AI);
4692 if (VMI != FuncInfo.ValueMap.end()) {
Dan Gohman86e1ebf2008-03-27 19:56:19 +00004693 SDL.CopyValueToVirtualRegister(AI, VMI->second);
Chris Lattnerbf209482005-10-30 19:42:35 +00004694 }
Chris Lattner0afa8e32005-01-17 17:55:19 +00004695 }
Chris Lattnerbf209482005-10-30 19:42:35 +00004696
Chris Lattnerbf209482005-10-30 19:42:35 +00004697 // Finally, if the target has anything special to do, allow it to do so.
Chris Lattner96645412006-05-16 06:10:58 +00004698 // FIXME: this should insert code into the DAG!
Chris Lattnerbf209482005-10-30 19:42:35 +00004699 EmitFunctionEntryCode(F, SDL.DAG.getMachineFunction());
Chris Lattner068a81e2005-01-17 17:15:02 +00004700}
4701
Duncan Sandsf4070822007-06-15 19:04:19 +00004702static void copyCatchInfo(BasicBlock *SrcBB, BasicBlock *DestBB,
4703 MachineModuleInfo *MMI, FunctionLoweringInfo &FLI) {
Duncan Sandsf4070822007-06-15 19:04:19 +00004704 for (BasicBlock::iterator I = SrcBB->begin(), E = --SrcBB->end(); I != E; ++I)
Duncan Sandscf26d7c2007-07-04 20:52:51 +00004705 if (isSelector(I)) {
Duncan Sandsf4070822007-06-15 19:04:19 +00004706 // Apply the catch info to DestBB.
4707 addCatchInfo(cast<CallInst>(*I), MMI, FLI.MBBMap[DestBB]);
4708#ifndef NDEBUG
Duncan Sands560a7372007-11-15 09:54:37 +00004709 if (!FLI.MBBMap[SrcBB]->isLandingPad())
4710 FLI.CatchInfoFound.insert(I);
Duncan Sandsf4070822007-06-15 19:04:19 +00004711#endif
4712 }
4713}
4714
Arnold Schwaighofer30e62c02008-04-30 09:16:33 +00004715/// IsFixedFrameObjectWithPosOffset - Check if object is a fixed frame object and
4716/// whether object offset >= 0.
4717static bool
4718IsFixedFrameObjectWithPosOffset(MachineFrameInfo * MFI, SDOperand Op) {
4719 if (!isa<FrameIndexSDNode>(Op)) return false;
4720
4721 FrameIndexSDNode * FrameIdxNode = dyn_cast<FrameIndexSDNode>(Op);
4722 int FrameIdx = FrameIdxNode->getIndex();
4723 return MFI->isFixedObjectIndex(FrameIdx) &&
4724 MFI->getObjectOffset(FrameIdx) >= 0;
4725}
4726
4727/// IsPossiblyOverwrittenArgumentOfTailCall - Check if the operand could
4728/// possibly be overwritten when lowering the outgoing arguments in a tail
4729/// call. Currently the implementation of this call is very conservative and
4730/// assumes all arguments sourcing from FORMAL_ARGUMENTS or a CopyFromReg with
4731/// virtual registers would be overwritten by direct lowering.
4732static bool IsPossiblyOverwrittenArgumentOfTailCall(SDOperand Op,
4733 MachineFrameInfo * MFI) {
4734 RegisterSDNode * OpReg = NULL;
4735 if (Op.getOpcode() == ISD::FORMAL_ARGUMENTS ||
4736 (Op.getOpcode()== ISD::CopyFromReg &&
4737 (OpReg = dyn_cast<RegisterSDNode>(Op.getOperand(1))) &&
4738 (OpReg->getReg() >= TargetRegisterInfo::FirstVirtualRegister)) ||
4739 (Op.getOpcode() == ISD::LOAD &&
4740 IsFixedFrameObjectWithPosOffset(MFI, Op.getOperand(1))) ||
4741 (Op.getOpcode() == ISD::MERGE_VALUES &&
4742 Op.getOperand(Op.ResNo).getOpcode() == ISD::LOAD &&
4743 IsFixedFrameObjectWithPosOffset(MFI, Op.getOperand(Op.ResNo).
4744 getOperand(1))))
4745 return true;
4746 return false;
4747}
4748
Arnold Schwaighoferc85e1712007-10-11 19:40:01 +00004749/// CheckDAGForTailCallsAndFixThem - This Function looks for CALL nodes in the
Arnold Schwaighofer48abc5c2007-10-12 21:30:57 +00004750/// DAG and fixes their tailcall attribute operand.
Arnold Schwaighoferc85e1712007-10-11 19:40:01 +00004751static void CheckDAGForTailCallsAndFixThem(SelectionDAG &DAG,
4752 TargetLowering& TLI) {
4753 SDNode * Ret = NULL;
4754 SDOperand Terminator = DAG.getRoot();
4755
4756 // Find RET node.
4757 if (Terminator.getOpcode() == ISD::RET) {
4758 Ret = Terminator.Val;
4759 }
4760
4761 // Fix tail call attribute of CALL nodes.
4762 for (SelectionDAG::allnodes_iterator BE = DAG.allnodes_begin(),
4763 BI = prior(DAG.allnodes_end()); BI != BE; --BI) {
4764 if (BI->getOpcode() == ISD::CALL) {
4765 SDOperand OpRet(Ret, 0);
4766 SDOperand OpCall(static_cast<SDNode*>(BI), 0);
4767 bool isMarkedTailCall =
4768 cast<ConstantSDNode>(OpCall.getOperand(3))->getValue() != 0;
4769 // If CALL node has tail call attribute set to true and the call is not
4770 // eligible (no RET or the target rejects) the attribute is fixed to
Arnold Schwaighofer48abc5c2007-10-12 21:30:57 +00004771 // false. The TargetLowering::IsEligibleForTailCallOptimization function
Arnold Schwaighoferc85e1712007-10-11 19:40:01 +00004772 // must correctly identify tail call optimizable calls.
Arnold Schwaighofer30e62c02008-04-30 09:16:33 +00004773 if (!isMarkedTailCall) continue;
4774 if (Ret==NULL ||
4775 !TLI.IsEligibleForTailCallOptimization(OpCall, OpRet, DAG)) {
4776 // Not eligible. Mark CALL node as non tail call.
Arnold Schwaighoferc85e1712007-10-11 19:40:01 +00004777 SmallVector<SDOperand, 32> Ops;
4778 unsigned idx=0;
Arnold Schwaighofer30e62c02008-04-30 09:16:33 +00004779 for(SDNode::op_iterator I =OpCall.Val->op_begin(),
4780 E = OpCall.Val->op_end(); I != E; I++, idx++) {
Arnold Schwaighoferc85e1712007-10-11 19:40:01 +00004781 if (idx!=3)
4782 Ops.push_back(*I);
Arnold Schwaighofer30e62c02008-04-30 09:16:33 +00004783 else
Arnold Schwaighoferc85e1712007-10-11 19:40:01 +00004784 Ops.push_back(DAG.getConstant(false, TLI.getPointerTy()));
4785 }
4786 DAG.UpdateNodeOperands(OpCall, Ops.begin(), Ops.size());
Arnold Schwaighofer30e62c02008-04-30 09:16:33 +00004787 } else {
4788 // Look for tail call clobbered arguments. Emit a series of
4789 // copyto/copyfrom virtual register nodes to protect them.
4790 SmallVector<SDOperand, 32> Ops;
4791 SDOperand Chain = OpCall.getOperand(0), InFlag;
4792 unsigned idx=0;
4793 for(SDNode::op_iterator I = OpCall.Val->op_begin(),
4794 E = OpCall.Val->op_end(); I != E; I++, idx++) {
4795 SDOperand Arg = *I;
4796 if (idx > 4 && (idx % 2)) {
4797 bool isByVal = cast<ARG_FLAGSSDNode>(OpCall.getOperand(idx+1))->
4798 getArgFlags().isByVal();
4799 MachineFunction &MF = DAG.getMachineFunction();
4800 MachineFrameInfo *MFI = MF.getFrameInfo();
4801 if (!isByVal &&
4802 IsPossiblyOverwrittenArgumentOfTailCall(Arg, MFI)) {
Duncan Sands83ec4b62008-06-06 12:08:01 +00004803 MVT VT = Arg.getValueType();
Arnold Schwaighofer30e62c02008-04-30 09:16:33 +00004804 unsigned VReg = MF.getRegInfo().
4805 createVirtualRegister(TLI.getRegClassFor(VT));
4806 Chain = DAG.getCopyToReg(Chain, VReg, Arg, InFlag);
4807 InFlag = Chain.getValue(1);
4808 Arg = DAG.getCopyFromReg(Chain, VReg, VT, InFlag);
4809 Chain = Arg.getValue(1);
4810 InFlag = Arg.getValue(2);
4811 }
4812 }
4813 Ops.push_back(Arg);
4814 }
4815 // Link in chain of CopyTo/CopyFromReg.
4816 Ops[0] = Chain;
4817 DAG.UpdateNodeOperands(OpCall, Ops.begin(), Ops.size());
Arnold Schwaighoferc85e1712007-10-11 19:40:01 +00004818 }
4819 }
4820 }
4821}
4822
Chris Lattner1c08c712005-01-07 07:47:53 +00004823void SelectionDAGISel::BuildSelectionDAG(SelectionDAG &DAG, BasicBlock *LLVMBB,
4824 std::vector<std::pair<MachineInstr*, unsigned> > &PHINodesToUpdate,
Nate Begemanf15485a2006-03-27 01:32:24 +00004825 FunctionLoweringInfo &FuncInfo) {
Gordon Henriksence224772008-01-07 01:30:38 +00004826 SelectionDAGLowering SDL(DAG, TLI, *AA, FuncInfo, GCI);
Chris Lattnerddb870b2005-01-13 17:59:43 +00004827
Chris Lattnerbf209482005-10-30 19:42:35 +00004828 // Lower any arguments needed in this block if this is the entry block.
Dan Gohmanecb7a772007-03-22 16:38:57 +00004829 if (LLVMBB == &LLVMBB->getParent()->getEntryBlock())
Dan Gohman86e1ebf2008-03-27 19:56:19 +00004830 LowerArguments(LLVMBB, SDL);
Chris Lattner1c08c712005-01-07 07:47:53 +00004831
4832 BB = FuncInfo.MBBMap[LLVMBB];
4833 SDL.setCurrentBasicBlock(BB);
4834
Duncan Sandsf4070822007-06-15 19:04:19 +00004835 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Duncan Sands9fac0b52007-06-06 10:05:18 +00004836
Dale Johannesen1532f3d2008-04-02 00:25:04 +00004837 if (MMI && BB->isLandingPad()) {
Duncan Sandsf4070822007-06-15 19:04:19 +00004838 // Add a label to mark the beginning of the landing pad. Deletion of the
4839 // landing pad can thus be detected via the MachineModuleInfo.
4840 unsigned LabelID = MMI->addLandingPad(BB);
4841 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, DAG.getEntryNode(),
Evan Chengbb81d972008-01-31 09:59:15 +00004842 DAG.getConstant(LabelID, MVT::i32),
4843 DAG.getConstant(1, MVT::i32)));
Duncan Sandsf4070822007-06-15 19:04:19 +00004844
Evan Chenge47c3332007-06-27 18:45:32 +00004845 // Mark exception register as live in.
4846 unsigned Reg = TLI.getExceptionAddressRegister();
4847 if (Reg) BB->addLiveIn(Reg);
4848
4849 // Mark exception selector register as live in.
4850 Reg = TLI.getExceptionSelectorRegister();
4851 if (Reg) BB->addLiveIn(Reg);
4852
Duncan Sandsf4070822007-06-15 19:04:19 +00004853 // FIXME: Hack around an exception handling flaw (PR1508): the personality
4854 // function and list of typeids logically belong to the invoke (or, if you
4855 // like, the basic block containing the invoke), and need to be associated
4856 // with it in the dwarf exception handling tables. Currently however the
Duncan Sandscf26d7c2007-07-04 20:52:51 +00004857 // information is provided by an intrinsic (eh.selector) that can be moved
4858 // to unexpected places by the optimizers: if the unwind edge is critical,
4859 // then breaking it can result in the intrinsics being in the successor of
4860 // the landing pad, not the landing pad itself. This results in exceptions
4861 // not being caught because no typeids are associated with the invoke.
4862 // This may not be the only way things can go wrong, but it is the only way
4863 // we try to work around for the moment.
Duncan Sandsf4070822007-06-15 19:04:19 +00004864 BranchInst *Br = dyn_cast<BranchInst>(LLVMBB->getTerminator());
4865
4866 if (Br && Br->isUnconditional()) { // Critical edge?
4867 BasicBlock::iterator I, E;
4868 for (I = LLVMBB->begin(), E = --LLVMBB->end(); I != E; ++I)
Duncan Sandscf26d7c2007-07-04 20:52:51 +00004869 if (isSelector(I))
Duncan Sandsf4070822007-06-15 19:04:19 +00004870 break;
4871
4872 if (I == E)
4873 // No catch info found - try to extract some from the successor.
4874 copyCatchInfo(Br->getSuccessor(0), LLVMBB, MMI, FuncInfo);
Duncan Sands9fac0b52007-06-06 10:05:18 +00004875 }
4876 }
4877
Chris Lattner1c08c712005-01-07 07:47:53 +00004878 // Lower all of the non-terminator instructions.
4879 for (BasicBlock::iterator I = LLVMBB->begin(), E = --LLVMBB->end();
4880 I != E; ++I)
4881 SDL.visit(*I);
Duncan Sandsf19f6bb2007-06-13 05:51:31 +00004882
Chris Lattner1c08c712005-01-07 07:47:53 +00004883 // Ensure that all instructions which are used outside of their defining
Duncan Sandsf19f6bb2007-06-13 05:51:31 +00004884 // blocks are available as virtual registers. Invoke is handled elsewhere.
Chris Lattner1c08c712005-01-07 07:47:53 +00004885 for (BasicBlock::iterator I = LLVMBB->begin(), E = LLVMBB->end(); I != E;++I)
Duncan Sandsf19f6bb2007-06-13 05:51:31 +00004886 if (!I->use_empty() && !isa<PHINode>(I) && !isa<InvokeInst>(I)) {
Chris Lattner9f24ad72007-02-04 01:35:11 +00004887 DenseMap<const Value*, unsigned>::iterator VMI =FuncInfo.ValueMap.find(I);
Chris Lattner1c08c712005-01-07 07:47:53 +00004888 if (VMI != FuncInfo.ValueMap.end())
Dan Gohman86e1ebf2008-03-27 19:56:19 +00004889 SDL.CopyValueToVirtualRegister(I, VMI->second);
Chris Lattner1c08c712005-01-07 07:47:53 +00004890 }
4891
4892 // Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
4893 // ensure constants are generated when needed. Remember the virtual registers
4894 // that need to be added to the Machine PHI nodes as input. We cannot just
4895 // directly add them, because expansion might result in multiple MBB's for one
4896 // BB. As such, the start of the BB might correspond to a different MBB than
4897 // the end.
Misha Brukmanedf128a2005-04-21 22:36:52 +00004898 //
Chris Lattner8c494ab2006-10-27 23:50:33 +00004899 TerminatorInst *TI = LLVMBB->getTerminator();
Chris Lattner1c08c712005-01-07 07:47:53 +00004900
4901 // Emit constants only once even if used by multiple PHI nodes.
4902 std::map<Constant*, unsigned> ConstantsOut;
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004903
Chris Lattner8c494ab2006-10-27 23:50:33 +00004904 // Vector bool would be better, but vector<bool> is really slow.
4905 std::vector<unsigned char> SuccsHandled;
4906 if (TI->getNumSuccessors())
4907 SuccsHandled.resize(BB->getParent()->getNumBlockIDs());
4908
Dan Gohman532dc2e2007-07-09 20:59:04 +00004909 // Check successor nodes' PHI nodes that expect a constant to be available
4910 // from this block.
Chris Lattner1c08c712005-01-07 07:47:53 +00004911 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
4912 BasicBlock *SuccBB = TI->getSuccessor(succ);
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004913 if (!isa<PHINode>(SuccBB->begin())) continue;
Chris Lattner8c494ab2006-10-27 23:50:33 +00004914 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004915
Chris Lattner8c494ab2006-10-27 23:50:33 +00004916 // If this terminator has multiple identical successors (common for
4917 // switches), only handle each succ once.
4918 unsigned SuccMBBNo = SuccMBB->getNumber();
4919 if (SuccsHandled[SuccMBBNo]) continue;
4920 SuccsHandled[SuccMBBNo] = true;
4921
4922 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
Chris Lattner1c08c712005-01-07 07:47:53 +00004923 PHINode *PN;
4924
4925 // At this point we know that there is a 1-1 correspondence between LLVM PHI
4926 // nodes and Machine PHI nodes, but the incoming operands have not been
4927 // emitted yet.
4928 for (BasicBlock::iterator I = SuccBB->begin();
Chris Lattner8c494ab2006-10-27 23:50:33 +00004929 (PN = dyn_cast<PHINode>(I)); ++I) {
4930 // Ignore dead phi's.
4931 if (PN->use_empty()) continue;
4932
4933 unsigned Reg;
4934 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
Chris Lattner3f7927c2006-11-29 01:12:32 +00004935
Chris Lattner8c494ab2006-10-27 23:50:33 +00004936 if (Constant *C = dyn_cast<Constant>(PHIOp)) {
4937 unsigned &RegOut = ConstantsOut[C];
4938 if (RegOut == 0) {
4939 RegOut = FuncInfo.CreateRegForValue(C);
Dan Gohman86e1ebf2008-03-27 19:56:19 +00004940 SDL.CopyValueToVirtualRegister(C, RegOut);
Chris Lattner1c08c712005-01-07 07:47:53 +00004941 }
Chris Lattner8c494ab2006-10-27 23:50:33 +00004942 Reg = RegOut;
4943 } else {
4944 Reg = FuncInfo.ValueMap[PHIOp];
4945 if (Reg == 0) {
4946 assert(isa<AllocaInst>(PHIOp) &&
4947 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
4948 "Didn't codegen value into a register!??");
4949 Reg = FuncInfo.CreateRegForValue(PHIOp);
Dan Gohman86e1ebf2008-03-27 19:56:19 +00004950 SDL.CopyValueToVirtualRegister(PHIOp, Reg);
Chris Lattner7e021512006-03-31 02:12:18 +00004951 }
Chris Lattner1c08c712005-01-07 07:47:53 +00004952 }
Chris Lattner8c494ab2006-10-27 23:50:33 +00004953
4954 // Remember that this register needs to added to the machine PHI node as
4955 // the input for this MBB.
Duncan Sands83ec4b62008-06-06 12:08:01 +00004956 MVT VT = TLI.getValueType(PN->getType());
Dan Gohman7f321562007-06-25 16:23:39 +00004957 unsigned NumRegisters = TLI.getNumRegisters(VT);
Dan Gohmanb9f10192007-06-21 14:42:22 +00004958 for (unsigned i = 0, e = NumRegisters; i != e; ++i)
Chris Lattner8c494ab2006-10-27 23:50:33 +00004959 PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
4960 }
Chris Lattner1c08c712005-01-07 07:47:53 +00004961 }
4962 ConstantsOut.clear();
4963
4964 // Lower the terminator after the copies are emitted.
Duncan Sandsf19f6bb2007-06-13 05:51:31 +00004965 SDL.visit(*LLVMBB->getTerminator());
Chris Lattnera651cf62005-01-17 19:43:36 +00004966
Nate Begemanf15485a2006-03-27 01:32:24 +00004967 // Copy over any CaseBlock records that may now exist due to SwitchInst
Nate Begeman37efe672006-04-22 18:53:45 +00004968 // lowering, as well as any jump table information.
Nate Begemanf15485a2006-03-27 01:32:24 +00004969 SwitchCases.clear();
4970 SwitchCases = SDL.SwitchCases;
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00004971 JTCases.clear();
4972 JTCases = SDL.JTCases;
Anton Korobeynikov4198c582007-04-09 12:31:58 +00004973 BitTestCases.clear();
4974 BitTestCases = SDL.BitTestCases;
4975
Chris Lattnera651cf62005-01-17 19:43:36 +00004976 // Make sure the root of the DAG is up-to-date.
Dan Gohman86e1ebf2008-03-27 19:56:19 +00004977 DAG.setRoot(SDL.getControlRoot());
Arnold Schwaighoferc85e1712007-10-11 19:40:01 +00004978
4979 // Check whether calls in this block are real tail calls. Fix up CALL nodes
4980 // with correct tailcall attribute so that the target can rely on the tailcall
4981 // attribute indicating whether the call is really eligible for tail call
4982 // optimization.
4983 CheckDAGForTailCallsAndFixThem(DAG, TLI);
Chris Lattner1c08c712005-01-07 07:47:53 +00004984}
4985
Nate Begemanf15485a2006-03-27 01:32:24 +00004986void SelectionDAGISel::CodeGenAndEmitDAG(SelectionDAG &DAG) {
Dan Gohman417e11b2007-10-08 15:12:17 +00004987 DOUT << "Lowered selection DAG:\n";
4988 DEBUG(DAG.dump());
4989
Chris Lattneraf21d552005-10-10 16:47:10 +00004990 // Run the DAG combiner in pre-legalize mode.
Dan Gohman5f43f922007-08-27 16:26:13 +00004991 DAG.Combine(false, *AA);
Nate Begeman2300f552005-09-07 00:15:36 +00004992
Dan Gohman417e11b2007-10-08 15:12:17 +00004993 DOUT << "Optimized lowered selection DAG:\n";
Chris Lattner1c08c712005-01-07 07:47:53 +00004994 DEBUG(DAG.dump());
Nate Begemanf15485a2006-03-27 01:32:24 +00004995
Chris Lattner1c08c712005-01-07 07:47:53 +00004996 // Second step, hack on the DAG until it only uses operations and types that
4997 // the target supports.
Chris Lattner01d029b2007-10-15 06:10:22 +00004998#if 0 // Enable this some day.
4999 DAG.LegalizeTypes();
5000 // Someday even later, enable a dag combine pass here.
5001#endif
Chris Lattnerac9dc082005-01-23 04:36:26 +00005002 DAG.Legalize();
Nate Begemanf15485a2006-03-27 01:32:24 +00005003
Bill Wendling832171c2006-12-07 20:04:42 +00005004 DOUT << "Legalized selection DAG:\n";
Chris Lattner1c08c712005-01-07 07:47:53 +00005005 DEBUG(DAG.dump());
Nate Begemanf15485a2006-03-27 01:32:24 +00005006
Chris Lattneraf21d552005-10-10 16:47:10 +00005007 // Run the DAG combiner in post-legalize mode.
Dan Gohman5f43f922007-08-27 16:26:13 +00005008 DAG.Combine(true, *AA);
Nate Begeman2300f552005-09-07 00:15:36 +00005009
Dan Gohman417e11b2007-10-08 15:12:17 +00005010 DOUT << "Optimized legalized selection DAG:\n";
5011 DEBUG(DAG.dump());
5012
Evan Chenga9c20912006-01-21 02:32:06 +00005013 if (ViewISelDAGs) DAG.viewGraph();
Evan Cheng552c4a82006-04-28 02:09:19 +00005014
Chris Lattnera33ef482005-03-30 01:10:47 +00005015 // Third, instruction select all of the operations to machine code, adding the
5016 // code to the MachineBasicBlock.
Chris Lattner1c08c712005-01-07 07:47:53 +00005017 InstructionSelectBasicBlock(DAG);
Nate Begemanf15485a2006-03-27 01:32:24 +00005018
Bill Wendling832171c2006-12-07 20:04:42 +00005019 DOUT << "Selected machine code:\n";
Chris Lattner1c08c712005-01-07 07:47:53 +00005020 DEBUG(BB->dump());
Nate Begemanf15485a2006-03-27 01:32:24 +00005021}
Chris Lattner1c08c712005-01-07 07:47:53 +00005022
Nate Begemanf15485a2006-03-27 01:32:24 +00005023void SelectionDAGISel::SelectBasicBlock(BasicBlock *LLVMBB, MachineFunction &MF,
5024 FunctionLoweringInfo &FuncInfo) {
5025 std::vector<std::pair<MachineInstr*, unsigned> > PHINodesToUpdate;
5026 {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00005027 SelectionDAG DAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
Nate Begemanf15485a2006-03-27 01:32:24 +00005028 CurDAG = &DAG;
5029
5030 // First step, lower LLVM code to some DAG. This DAG may use operations and
5031 // types that are not supported by the target.
5032 BuildSelectionDAG(DAG, LLVMBB, PHINodesToUpdate, FuncInfo);
5033
5034 // Second step, emit the lowered DAG as machine code.
5035 CodeGenAndEmitDAG(DAG);
5036 }
Anton Korobeynikov4198c582007-04-09 12:31:58 +00005037
5038 DOUT << "Total amount of phi nodes to update: "
5039 << PHINodesToUpdate.size() << "\n";
5040 DEBUG(for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i)
5041 DOUT << "Node " << i << " : (" << PHINodesToUpdate[i].first
5042 << ", " << PHINodesToUpdate[i].second << ")\n";);
Nate Begemanf15485a2006-03-27 01:32:24 +00005043
Chris Lattnera33ef482005-03-30 01:10:47 +00005044 // Next, now that we know what the last MBB the LLVM BB expanded is, update
Chris Lattner1c08c712005-01-07 07:47:53 +00005045 // PHI nodes in successors.
Anton Korobeynikov4198c582007-04-09 12:31:58 +00005046 if (SwitchCases.empty() && JTCases.empty() && BitTestCases.empty()) {
Nate Begemanf15485a2006-03-27 01:32:24 +00005047 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
5048 MachineInstr *PHI = PHINodesToUpdate[i].first;
5049 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
5050 "This is not a machine PHI node that we are updating!");
Chris Lattner9ce2e9d2007-12-30 00:57:42 +00005051 PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[i].second,
5052 false));
5053 PHI->addOperand(MachineOperand::CreateMBB(BB));
Nate Begemanf15485a2006-03-27 01:32:24 +00005054 }
5055 return;
Chris Lattner1c08c712005-01-07 07:47:53 +00005056 }
Anton Korobeynikov4198c582007-04-09 12:31:58 +00005057
5058 for (unsigned i = 0, e = BitTestCases.size(); i != e; ++i) {
5059 // Lower header first, if it wasn't already lowered
5060 if (!BitTestCases[i].Emitted) {
5061 SelectionDAG HSDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
5062 CurDAG = &HSDAG;
Gordon Henriksence224772008-01-07 01:30:38 +00005063 SelectionDAGLowering HSDL(HSDAG, TLI, *AA, FuncInfo, GCI);
Anton Korobeynikov4198c582007-04-09 12:31:58 +00005064 // Set the current basic block to the mbb we wish to insert the code into
5065 BB = BitTestCases[i].Parent;
5066 HSDL.setCurrentBasicBlock(BB);
5067 // Emit the code
5068 HSDL.visitBitTestHeader(BitTestCases[i]);
5069 HSDAG.setRoot(HSDL.getRoot());
5070 CodeGenAndEmitDAG(HSDAG);
5071 }
5072
5073 for (unsigned j = 0, ej = BitTestCases[i].Cases.size(); j != ej; ++j) {
5074 SelectionDAG BSDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
5075 CurDAG = &BSDAG;
Gordon Henriksence224772008-01-07 01:30:38 +00005076 SelectionDAGLowering BSDL(BSDAG, TLI, *AA, FuncInfo, GCI);
Anton Korobeynikov4198c582007-04-09 12:31:58 +00005077 // Set the current basic block to the mbb we wish to insert the code into
5078 BB = BitTestCases[i].Cases[j].ThisBB;
5079 BSDL.setCurrentBasicBlock(BB);
5080 // Emit the code
5081 if (j+1 != ej)
5082 BSDL.visitBitTestCase(BitTestCases[i].Cases[j+1].ThisBB,
5083 BitTestCases[i].Reg,
5084 BitTestCases[i].Cases[j]);
5085 else
5086 BSDL.visitBitTestCase(BitTestCases[i].Default,
5087 BitTestCases[i].Reg,
5088 BitTestCases[i].Cases[j]);
5089
5090
5091 BSDAG.setRoot(BSDL.getRoot());
5092 CodeGenAndEmitDAG(BSDAG);
5093 }
5094
5095 // Update PHI Nodes
5096 for (unsigned pi = 0, pe = PHINodesToUpdate.size(); pi != pe; ++pi) {
5097 MachineInstr *PHI = PHINodesToUpdate[pi].first;
5098 MachineBasicBlock *PHIBB = PHI->getParent();
5099 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
5100 "This is not a machine PHI node that we are updating!");
5101 // This is "default" BB. We have two jumps to it. From "header" BB and
5102 // from last "case" BB.
5103 if (PHIBB == BitTestCases[i].Default) {
Chris Lattner9ce2e9d2007-12-30 00:57:42 +00005104 PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[pi].second,
5105 false));
5106 PHI->addOperand(MachineOperand::CreateMBB(BitTestCases[i].Parent));
5107 PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[pi].second,
5108 false));
5109 PHI->addOperand(MachineOperand::CreateMBB(BitTestCases[i].Cases.
5110 back().ThisBB));
Anton Korobeynikov4198c582007-04-09 12:31:58 +00005111 }
5112 // One of "cases" BB.
5113 for (unsigned j = 0, ej = BitTestCases[i].Cases.size(); j != ej; ++j) {
5114 MachineBasicBlock* cBB = BitTestCases[i].Cases[j].ThisBB;
5115 if (cBB->succ_end() !=
5116 std::find(cBB->succ_begin(),cBB->succ_end(), PHIBB)) {
Chris Lattner9ce2e9d2007-12-30 00:57:42 +00005117 PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[pi].second,
5118 false));
5119 PHI->addOperand(MachineOperand::CreateMBB(cBB));
Anton Korobeynikov4198c582007-04-09 12:31:58 +00005120 }
5121 }
5122 }
5123 }
5124
Nate Begeman9453eea2006-04-23 06:26:20 +00005125 // If the JumpTable record is filled in, then we need to emit a jump table.
5126 // Updating the PHI nodes is tricky in this case, since we need to determine
5127 // whether the PHI is a successor of the range check MBB or the jump table MBB
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00005128 for (unsigned i = 0, e = JTCases.size(); i != e; ++i) {
5129 // Lower header first, if it wasn't already lowered
5130 if (!JTCases[i].first.Emitted) {
5131 SelectionDAG HSDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
5132 CurDAG = &HSDAG;
Gordon Henriksence224772008-01-07 01:30:38 +00005133 SelectionDAGLowering HSDL(HSDAG, TLI, *AA, FuncInfo, GCI);
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00005134 // Set the current basic block to the mbb we wish to insert the code into
5135 BB = JTCases[i].first.HeaderBB;
5136 HSDL.setCurrentBasicBlock(BB);
5137 // Emit the code
5138 HSDL.visitJumpTableHeader(JTCases[i].second, JTCases[i].first);
5139 HSDAG.setRoot(HSDL.getRoot());
5140 CodeGenAndEmitDAG(HSDAG);
Anton Korobeynikov4198c582007-04-09 12:31:58 +00005141 }
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00005142
5143 SelectionDAG JSDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
5144 CurDAG = &JSDAG;
Gordon Henriksence224772008-01-07 01:30:38 +00005145 SelectionDAGLowering JSDL(JSDAG, TLI, *AA, FuncInfo, GCI);
Nate Begeman37efe672006-04-22 18:53:45 +00005146 // Set the current basic block to the mbb we wish to insert the code into
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00005147 BB = JTCases[i].second.MBB;
5148 JSDL.setCurrentBasicBlock(BB);
Nate Begeman37efe672006-04-22 18:53:45 +00005149 // Emit the code
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00005150 JSDL.visitJumpTable(JTCases[i].second);
5151 JSDAG.setRoot(JSDL.getRoot());
5152 CodeGenAndEmitDAG(JSDAG);
5153
Nate Begeman37efe672006-04-22 18:53:45 +00005154 // Update PHI Nodes
5155 for (unsigned pi = 0, pe = PHINodesToUpdate.size(); pi != pe; ++pi) {
5156 MachineInstr *PHI = PHINodesToUpdate[pi].first;
5157 MachineBasicBlock *PHIBB = PHI->getParent();
5158 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
5159 "This is not a machine PHI node that we are updating!");
Anton Korobeynikov4198c582007-04-09 12:31:58 +00005160 // "default" BB. We can go there only from header BB.
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00005161 if (PHIBB == JTCases[i].second.Default) {
Chris Lattner9ce2e9d2007-12-30 00:57:42 +00005162 PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[pi].second,
5163 false));
5164 PHI->addOperand(MachineOperand::CreateMBB(JTCases[i].first.HeaderBB));
Nate Begemanf4360a42006-05-03 03:48:02 +00005165 }
Anton Korobeynikov4198c582007-04-09 12:31:58 +00005166 // JT BB. Just iterate over successors here
Nate Begemanf4360a42006-05-03 03:48:02 +00005167 if (BB->succ_end() != std::find(BB->succ_begin(),BB->succ_end(), PHIBB)) {
Chris Lattner9ce2e9d2007-12-30 00:57:42 +00005168 PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[pi].second,
5169 false));
5170 PHI->addOperand(MachineOperand::CreateMBB(BB));
Nate Begeman37efe672006-04-22 18:53:45 +00005171 }
5172 }
Nate Begeman37efe672006-04-22 18:53:45 +00005173 }
5174
Chris Lattnerb2e806e2006-10-22 23:00:53 +00005175 // If the switch block involved a branch to one of the actual successors, we
5176 // need to update PHI nodes in that block.
5177 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
5178 MachineInstr *PHI = PHINodesToUpdate[i].first;
5179 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
5180 "This is not a machine PHI node that we are updating!");
5181 if (BB->isSuccessor(PHI->getParent())) {
Chris Lattner9ce2e9d2007-12-30 00:57:42 +00005182 PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[i].second,
5183 false));
5184 PHI->addOperand(MachineOperand::CreateMBB(BB));
Chris Lattnerb2e806e2006-10-22 23:00:53 +00005185 }
5186 }
5187
Nate Begemanf15485a2006-03-27 01:32:24 +00005188 // If we generated any switch lowering information, build and codegen any
5189 // additional DAGs necessary.
Chris Lattnerd5e93c02006-09-07 01:59:34 +00005190 for (unsigned i = 0, e = SwitchCases.size(); i != e; ++i) {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00005191 SelectionDAG SDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
Nate Begemanf15485a2006-03-27 01:32:24 +00005192 CurDAG = &SDAG;
Gordon Henriksence224772008-01-07 01:30:38 +00005193 SelectionDAGLowering SDL(SDAG, TLI, *AA, FuncInfo, GCI);
Chris Lattnerd5e93c02006-09-07 01:59:34 +00005194
Nate Begemanf15485a2006-03-27 01:32:24 +00005195 // Set the current basic block to the mbb we wish to insert the code into
5196 BB = SwitchCases[i].ThisBB;
5197 SDL.setCurrentBasicBlock(BB);
Chris Lattnerd5e93c02006-09-07 01:59:34 +00005198
Nate Begemanf15485a2006-03-27 01:32:24 +00005199 // Emit the code
5200 SDL.visitSwitchCase(SwitchCases[i]);
5201 SDAG.setRoot(SDL.getRoot());
5202 CodeGenAndEmitDAG(SDAG);
Chris Lattnerd5e93c02006-09-07 01:59:34 +00005203
5204 // Handle any PHI nodes in successors of this chunk, as if we were coming
5205 // from the original BB before switch expansion. Note that PHI nodes can
5206 // occur multiple times in PHINodesToUpdate. We have to be very careful to
5207 // handle them the right number of times.
Chris Lattner57ab6592006-10-24 17:57:59 +00005208 while ((BB = SwitchCases[i].TrueBB)) { // Handle LHS and RHS.
Chris Lattnerd5e93c02006-09-07 01:59:34 +00005209 for (MachineBasicBlock::iterator Phi = BB->begin();
5210 Phi != BB->end() && Phi->getOpcode() == TargetInstrInfo::PHI; ++Phi){
5211 // This value for this PHI node is recorded in PHINodesToUpdate, get it.
5212 for (unsigned pn = 0; ; ++pn) {
5213 assert(pn != PHINodesToUpdate.size() && "Didn't find PHI entry!");
5214 if (PHINodesToUpdate[pn].first == Phi) {
Chris Lattner9ce2e9d2007-12-30 00:57:42 +00005215 Phi->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[pn].
5216 second, false));
5217 Phi->addOperand(MachineOperand::CreateMBB(SwitchCases[i].ThisBB));
Chris Lattnerd5e93c02006-09-07 01:59:34 +00005218 break;
5219 }
5220 }
Nate Begemanf15485a2006-03-27 01:32:24 +00005221 }
Chris Lattnerd5e93c02006-09-07 01:59:34 +00005222
5223 // Don't process RHS if same block as LHS.
Chris Lattner57ab6592006-10-24 17:57:59 +00005224 if (BB == SwitchCases[i].FalseBB)
5225 SwitchCases[i].FalseBB = 0;
Chris Lattnerd5e93c02006-09-07 01:59:34 +00005226
5227 // If we haven't handled the RHS, do so now. Otherwise, we're done.
Chris Lattner24525952006-10-24 18:07:37 +00005228 SwitchCases[i].TrueBB = SwitchCases[i].FalseBB;
Chris Lattner57ab6592006-10-24 17:57:59 +00005229 SwitchCases[i].FalseBB = 0;
Nate Begemanf15485a2006-03-27 01:32:24 +00005230 }
Chris Lattner57ab6592006-10-24 17:57:59 +00005231 assert(SwitchCases[i].TrueBB == 0 && SwitchCases[i].FalseBB == 0);
Chris Lattnera33ef482005-03-30 01:10:47 +00005232 }
Chris Lattner1c08c712005-01-07 07:47:53 +00005233}
Evan Chenga9c20912006-01-21 02:32:06 +00005234
Jim Laskey13ec7022006-08-01 14:21:23 +00005235
Evan Chenga9c20912006-01-21 02:32:06 +00005236//===----------------------------------------------------------------------===//
5237/// ScheduleAndEmitDAG - Pick a safe ordering and emit instructions for each
5238/// target node in the graph.
5239void SelectionDAGISel::ScheduleAndEmitDAG(SelectionDAG &DAG) {
5240 if (ViewSchedDAGs) DAG.viewGraph();
Evan Cheng4ef10862006-01-23 07:01:07 +00005241
Jim Laskeyeb577ba2006-08-02 12:30:23 +00005242 RegisterScheduler::FunctionPassCtor Ctor = RegisterScheduler::getDefault();
Jim Laskey13ec7022006-08-01 14:21:23 +00005243
5244 if (!Ctor) {
Jim Laskeyeb577ba2006-08-02 12:30:23 +00005245 Ctor = ISHeuristic;
Jim Laskey9373beb2006-08-01 19:14:14 +00005246 RegisterScheduler::setDefault(Ctor);
Evan Cheng4ef10862006-01-23 07:01:07 +00005247 }
Jim Laskey13ec7022006-08-01 14:21:23 +00005248
Jim Laskey9ff542f2006-08-01 18:29:48 +00005249 ScheduleDAG *SL = Ctor(this, &DAG, BB);
Chris Lattnera3818e62006-01-21 19:12:11 +00005250 BB = SL->Run();
Dan Gohman3e1a7ae2007-08-28 20:32:58 +00005251
5252 if (ViewSUnitDAGs) SL->viewGraph();
5253
Evan Chengcccf1232006-02-04 06:49:00 +00005254 delete SL;
Evan Chenga9c20912006-01-21 02:32:06 +00005255}
Chris Lattner0e43f2b2006-02-24 02:13:54 +00005256
Chris Lattner03fc53c2006-03-06 00:22:00 +00005257
Jim Laskey9ff542f2006-08-01 18:29:48 +00005258HazardRecognizer *SelectionDAGISel::CreateTargetHazardRecognizer() {
5259 return new HazardRecognizer();
5260}
5261
Chris Lattner75548062006-10-11 03:58:02 +00005262//===----------------------------------------------------------------------===//
5263// Helper functions used by the generated instruction selector.
5264//===----------------------------------------------------------------------===//
5265// Calls to these methods are generated by tblgen.
5266
5267/// CheckAndMask - The isel is trying to match something like (and X, 255). If
5268/// the dag combiner simplified the 255, we still want to match. RHS is the
5269/// actual value in the DAG on the RHS of an AND, and DesiredMaskS is the value
5270/// specified in the .td file (e.g. 255).
5271bool SelectionDAGISel::CheckAndMask(SDOperand LHS, ConstantSDNode *RHS,
Dan Gohmandc9b3d02007-07-24 23:00:27 +00005272 int64_t DesiredMaskS) const {
Dan Gohman2e68b6f2008-02-25 21:11:39 +00005273 const APInt &ActualMask = RHS->getAPIntValue();
5274 const APInt &DesiredMask = APInt(LHS.getValueSizeInBits(), DesiredMaskS);
Chris Lattner75548062006-10-11 03:58:02 +00005275
5276 // If the actual mask exactly matches, success!
5277 if (ActualMask == DesiredMask)
5278 return true;
5279
5280 // If the actual AND mask is allowing unallowed bits, this doesn't match.
Dan Gohman2e68b6f2008-02-25 21:11:39 +00005281 if (ActualMask.intersects(~DesiredMask))
Chris Lattner75548062006-10-11 03:58:02 +00005282 return false;
5283
5284 // Otherwise, the DAG Combiner may have proven that the value coming in is
5285 // either already zero or is not demanded. Check for known zero input bits.
Dan Gohman2e68b6f2008-02-25 21:11:39 +00005286 APInt NeededMask = DesiredMask & ~ActualMask;
Dan Gohmanea859be2007-06-22 14:59:07 +00005287 if (CurDAG->MaskedValueIsZero(LHS, NeededMask))
Chris Lattner75548062006-10-11 03:58:02 +00005288 return true;
5289
5290 // TODO: check to see if missing bits are just not demanded.
5291
5292 // Otherwise, this pattern doesn't match.
5293 return false;
5294}
5295
5296/// CheckOrMask - The isel is trying to match something like (or X, 255). If
5297/// the dag combiner simplified the 255, we still want to match. RHS is the
5298/// actual value in the DAG on the RHS of an OR, and DesiredMaskS is the value
5299/// specified in the .td file (e.g. 255).
5300bool SelectionDAGISel::CheckOrMask(SDOperand LHS, ConstantSDNode *RHS,
Dan Gohman2e68b6f2008-02-25 21:11:39 +00005301 int64_t DesiredMaskS) const {
5302 const APInt &ActualMask = RHS->getAPIntValue();
5303 const APInt &DesiredMask = APInt(LHS.getValueSizeInBits(), DesiredMaskS);
Chris Lattner75548062006-10-11 03:58:02 +00005304
5305 // If the actual mask exactly matches, success!
5306 if (ActualMask == DesiredMask)
5307 return true;
5308
5309 // If the actual AND mask is allowing unallowed bits, this doesn't match.
Dan Gohman2e68b6f2008-02-25 21:11:39 +00005310 if (ActualMask.intersects(~DesiredMask))
Chris Lattner75548062006-10-11 03:58:02 +00005311 return false;
5312
5313 // Otherwise, the DAG Combiner may have proven that the value coming in is
5314 // either already zero or is not demanded. Check for known zero input bits.
Dan Gohman2e68b6f2008-02-25 21:11:39 +00005315 APInt NeededMask = DesiredMask & ~ActualMask;
Chris Lattner75548062006-10-11 03:58:02 +00005316
Dan Gohman2e68b6f2008-02-25 21:11:39 +00005317 APInt KnownZero, KnownOne;
Dan Gohmanea859be2007-06-22 14:59:07 +00005318 CurDAG->ComputeMaskedBits(LHS, NeededMask, KnownZero, KnownOne);
Chris Lattner75548062006-10-11 03:58:02 +00005319
5320 // If all the missing bits in the or are already known to be set, match!
5321 if ((NeededMask & KnownOne) == NeededMask)
5322 return true;
5323
5324 // TODO: check to see if missing bits are just not demanded.
5325
5326 // Otherwise, this pattern doesn't match.
5327 return false;
5328}
5329
Jim Laskey9ff542f2006-08-01 18:29:48 +00005330
Chris Lattner0e43f2b2006-02-24 02:13:54 +00005331/// SelectInlineAsmMemoryOperands - Calls to this are automatically generated
5332/// by tblgen. Others should not call it.
5333void SelectionDAGISel::
5334SelectInlineAsmMemoryOperands(std::vector<SDOperand> &Ops, SelectionDAG &DAG) {
5335 std::vector<SDOperand> InOps;
5336 std::swap(InOps, Ops);
5337
5338 Ops.push_back(InOps[0]); // input chain.
5339 Ops.push_back(InOps[1]); // input asm string.
5340
Chris Lattner0e43f2b2006-02-24 02:13:54 +00005341 unsigned i = 2, e = InOps.size();
5342 if (InOps[e-1].getValueType() == MVT::Flag)
5343 --e; // Don't process a flag operand if it is here.
5344
5345 while (i != e) {
5346 unsigned Flags = cast<ConstantSDNode>(InOps[i])->getValue();
5347 if ((Flags & 7) != 4 /*MEM*/) {
5348 // Just skip over this operand, copying the operands verbatim.
5349 Ops.insert(Ops.end(), InOps.begin()+i, InOps.begin()+i+(Flags >> 3) + 1);
5350 i += (Flags >> 3) + 1;
5351 } else {
5352 assert((Flags >> 3) == 1 && "Memory operand with multiple values?");
5353 // Otherwise, this is a memory operand. Ask the target to select it.
5354 std::vector<SDOperand> SelOps;
5355 if (SelectInlineAsmMemoryOperand(InOps[i+1], 'm', SelOps, DAG)) {
Bill Wendling832171c2006-12-07 20:04:42 +00005356 cerr << "Could not match memory address. Inline asm failure!\n";
Chris Lattner0e43f2b2006-02-24 02:13:54 +00005357 exit(1);
5358 }
5359
5360 // Add this to the output node.
Duncan Sands83ec4b62008-06-06 12:08:01 +00005361 MVT IntPtrTy = DAG.getTargetLoweringInfo().getPointerTy();
Chris Lattner36d43962006-12-16 21:14:48 +00005362 Ops.push_back(DAG.getTargetConstant(4/*MEM*/ | (SelOps.size() << 3),
Chris Lattner4b993b12007-04-09 00:33:58 +00005363 IntPtrTy));
Chris Lattner0e43f2b2006-02-24 02:13:54 +00005364 Ops.insert(Ops.end(), SelOps.begin(), SelOps.end());
5365 i += 2;
5366 }
5367 }
5368
5369 // Add the flag input back if present.
5370 if (e != InOps.size())
5371 Ops.push_back(InOps.back());
5372}
Devang Patel794fd752007-05-01 21:15:47 +00005373
Devang Patel19974732007-05-03 01:11:54 +00005374char SelectionDAGISel::ID = 0;