blob: dc335f8ef783ff663f2bcc873e19b7bde5f3f939 [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//===---------------------------------------------------------------------===//
Evan Cheng4ef10862006-01-23 07:01:07 +000077namespace {
Jim Laskeyeb577ba2006-08-02 12:30:23 +000078 cl::opt<RegisterScheduler::FunctionPassCtor, false,
79 RegisterPassParser<RegisterScheduler> >
Dale Johannesene7e7d0d2007-07-13 17:13:54 +000080 ISHeuristic("pre-RA-sched",
Chris Lattner3700f902006-08-03 00:18:59 +000081 cl::init(&createDefaultScheduler),
Chris Lattner5bab7852008-01-25 17:24:52 +000082 cl::desc("Instruction schedulers available (before register"
83 " allocation):"));
Jim Laskey13ec7022006-08-01 14:21:23 +000084
Jim Laskey9ff542f2006-08-01 18:29:48 +000085 static RegisterScheduler
Jim Laskey9373beb2006-08-01 19:14:14 +000086 defaultListDAGScheduler("default", " Best scheduler for the target",
87 createDefaultScheduler);
Evan Cheng4ef10862006-01-23 07:01:07 +000088} // namespace
89
Evan Cheng5c807602008-02-26 02:33:44 +000090namespace { struct SDISelAsmOperandInfo; }
Chris Lattnerbf996f12007-04-30 17:29:31 +000091
Chris Lattnerf899fce2008-04-27 23:48:12 +000092/// ComputeValueVTs - Given an LLVM IR type, compute a sequence of
93/// MVT::ValueTypes that represent all the individual underlying
94/// non-aggregate types that comprise it.
95static void ComputeValueVTs(const TargetLowering &TLI, const Type *Ty,
96 SmallVectorImpl<MVT::ValueType> &ValueVTs) {
97 // Given a struct type, recursively traverse the elements.
98 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
99 for (StructType::element_iterator EI = STy->element_begin(),
100 EB = STy->element_end();
101 EI != EB; ++EI)
102 ComputeValueVTs(TLI, *EI, ValueVTs);
103 return;
Dan Gohman23ce5022008-04-25 18:27:55 +0000104 }
Chris Lattnerf899fce2008-04-27 23:48:12 +0000105 // Given an array type, recursively traverse the elements.
106 if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
107 const Type *EltTy = ATy->getElementType();
108 for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i)
109 ComputeValueVTs(TLI, EltTy, ValueVTs);
110 return;
111 }
112 // Base case: we can get an MVT::ValueType for this LLVM IR type.
113 ValueVTs.push_back(TLI.getValueType(Ty));
114}
Dan Gohman23ce5022008-04-25 18:27:55 +0000115
Chris Lattnerf899fce2008-04-27 23:48:12 +0000116namespace {
Chris Lattner864635a2006-02-22 22:37:12 +0000117 /// RegsForValue - This struct represents the physical registers that a
118 /// particular value is assigned and the type information about the value.
119 /// This is needed because values can be promoted into larger registers and
120 /// expanded into multiple smaller registers than the value.
Chris Lattner95255282006-06-28 23:17:24 +0000121 struct VISIBILITY_HIDDEN RegsForValue {
Dan Gohman23ce5022008-04-25 18:27:55 +0000122 /// TLI - The TargetLowering object.
123 const TargetLowering *TLI;
124
Dan Gohmanb6f5b002007-06-28 23:29:44 +0000125 /// Regs - This list holds the register (for legal and promoted values)
Chris Lattner864635a2006-02-22 22:37:12 +0000126 /// or register set (for expanded values) that the value should be assigned
127 /// to.
Chris Lattner8eaff042008-04-28 06:02:19 +0000128 SmallVector<unsigned, 4> Regs;
Chris Lattner864635a2006-02-22 22:37:12 +0000129
Dan Gohman23ce5022008-04-25 18:27:55 +0000130 /// RegVTs - The value types of the registers. This is the same size
131 /// as ValueVTs; every register contributing to a given value must
132 /// have the same type. When Regs contains all virtual registers, the
133 /// contents of RegVTs is redundant with TLI's getRegisterType member
134 /// function, however when Regs contains physical registers, it is
135 /// necessary to have a separate record of the types.
Chris Lattner864635a2006-02-22 22:37:12 +0000136 ///
Dan Gohman23ce5022008-04-25 18:27:55 +0000137 SmallVector<MVT::ValueType, 4> RegVTs;
Chris Lattner864635a2006-02-22 22:37:12 +0000138
Dan Gohman23ce5022008-04-25 18:27:55 +0000139 /// ValueVTs - The value types of the values, which may be promoted
140 /// or synthesized from one or more registers.
141 SmallVector<MVT::ValueType, 4> ValueVTs;
Chris Lattner864635a2006-02-22 22:37:12 +0000142
Dan Gohman23ce5022008-04-25 18:27:55 +0000143 RegsForValue() : TLI(0) {}
Chris Lattner864635a2006-02-22 22:37:12 +0000144
Dan Gohman23ce5022008-04-25 18:27:55 +0000145 RegsForValue(const TargetLowering &tli,
146 unsigned Reg, MVT::ValueType regvt, MVT::ValueType valuevt)
147 : TLI(&tli), Regs(1, Reg), RegVTs(1, regvt), ValueVTs(1, valuevt) {}
148 RegsForValue(const TargetLowering &tli,
Chris Lattnerb606dba2008-04-28 06:44:42 +0000149 const SmallVector<unsigned, 4> &regs,
Chris Lattner864635a2006-02-22 22:37:12 +0000150 MVT::ValueType regvt, MVT::ValueType valuevt)
Dan Gohman23ce5022008-04-25 18:27:55 +0000151 : TLI(&tli), Regs(regs), RegVTs(1, regvt), ValueVTs(1, valuevt) {}
152 RegsForValue(const TargetLowering &tli,
Chris Lattnerb606dba2008-04-28 06:44:42 +0000153 const SmallVector<unsigned, 4> &regs,
Dan Gohman23ce5022008-04-25 18:27:55 +0000154 const SmallVector<MVT::ValueType, 4> &regvts,
155 const SmallVector<MVT::ValueType, 4> &valuevts)
156 : TLI(&tli), Regs(regs), RegVTs(regvts), ValueVTs(valuevts) {}
157 RegsForValue(const TargetLowering &tli,
158 unsigned Reg, const Type *Ty) : TLI(&tli) {
159 ComputeValueVTs(tli, Ty, ValueVTs);
160
161 for (unsigned Value = 0; Value != ValueVTs.size(); ++Value) {
162 MVT::ValueType ValueVT = ValueVTs[Value];
163 unsigned NumRegs = TLI->getNumRegisters(ValueVT);
164 MVT::ValueType RegisterVT = TLI->getRegisterType(ValueVT);
165 for (unsigned i = 0; i != NumRegs; ++i)
166 Regs.push_back(Reg + i);
167 RegVTs.push_back(RegisterVT);
168 Reg += NumRegs;
169 }
Chris Lattner864635a2006-02-22 22:37:12 +0000170 }
171
172 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
Dan Gohman23ce5022008-04-25 18:27:55 +0000173 /// this value and returns the result as a ValueVTs value. This uses
Chris Lattner864635a2006-02-22 22:37:12 +0000174 /// Chain/Flag as the input and updates them for the output Chain/Flag.
Dan Gohmanb6f5b002007-06-28 23:29:44 +0000175 /// If the Flag pointer is NULL, no flag is used.
Chris Lattner864635a2006-02-22 22:37:12 +0000176 SDOperand getCopyFromRegs(SelectionDAG &DAG,
Dan Gohmanb6f5b002007-06-28 23:29:44 +0000177 SDOperand &Chain, SDOperand *Flag) const;
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +0000178
179 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
180 /// specified value into the registers specified by this object. This uses
181 /// Chain/Flag as the input and updates them for the output Chain/Flag.
Dan Gohmanb6f5b002007-06-28 23:29:44 +0000182 /// If the Flag pointer is NULL, no flag is used.
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +0000183 void getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
Dan Gohmanb6f5b002007-06-28 23:29:44 +0000184 SDOperand &Chain, SDOperand *Flag) const;
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +0000185
186 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
187 /// operand list. This adds the code marker and includes the number of
188 /// values added into it.
189 void AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
Chris Lattner9f6637d2006-02-23 20:06:57 +0000190 std::vector<SDOperand> &Ops) const;
Chris Lattner864635a2006-02-22 22:37:12 +0000191 };
192}
Evan Cheng4ef10862006-01-23 07:01:07 +0000193
Chris Lattner1c08c712005-01-07 07:47:53 +0000194namespace llvm {
195 //===--------------------------------------------------------------------===//
Jim Laskey9373beb2006-08-01 19:14:14 +0000196 /// createDefaultScheduler - This creates an instruction scheduler appropriate
197 /// for the target.
198 ScheduleDAG* createDefaultScheduler(SelectionDAGISel *IS,
199 SelectionDAG *DAG,
200 MachineBasicBlock *BB) {
201 TargetLowering &TLI = IS->getTargetLowering();
202
203 if (TLI.getSchedulingPreference() == TargetLowering::SchedulingForLatency) {
204 return createTDListDAGScheduler(IS, DAG, BB);
205 } else {
206 assert(TLI.getSchedulingPreference() ==
207 TargetLowering::SchedulingForRegPressure && "Unknown sched type!");
208 return createBURRListDAGScheduler(IS, DAG, BB);
209 }
210 }
211
212
213 //===--------------------------------------------------------------------===//
Chris Lattner1c08c712005-01-07 07:47:53 +0000214 /// FunctionLoweringInfo - This contains information that is global to a
215 /// function that is used when lowering a region of the function.
Chris Lattnerf26bc8e2005-01-08 19:52:31 +0000216 class FunctionLoweringInfo {
217 public:
Chris Lattner1c08c712005-01-07 07:47:53 +0000218 TargetLowering &TLI;
219 Function &Fn;
220 MachineFunction &MF;
Chris Lattner84bc5422007-12-31 04:13:23 +0000221 MachineRegisterInfo &RegInfo;
Chris Lattner1c08c712005-01-07 07:47:53 +0000222
223 FunctionLoweringInfo(TargetLowering &TLI, Function &Fn,MachineFunction &MF);
224
225 /// MBBMap - A mapping from LLVM basic blocks to their machine code entry.
226 std::map<const BasicBlock*, MachineBasicBlock *> MBBMap;
227
228 /// ValueMap - Since we emit code for the function a basic block at a time,
229 /// we must remember which virtual registers hold the values for
230 /// cross-basic-block values.
Chris Lattner9f24ad72007-02-04 01:35:11 +0000231 DenseMap<const Value*, unsigned> ValueMap;
Chris Lattner1c08c712005-01-07 07:47:53 +0000232
233 /// StaticAllocaMap - Keep track of frame indices for fixed sized allocas in
234 /// the entry block. This allows the allocas to be efficiently referenced
235 /// anywhere in the function.
236 std::map<const AllocaInst*, int> StaticAllocaMap;
237
Duncan Sandsf4070822007-06-15 19:04:19 +0000238#ifndef NDEBUG
239 SmallSet<Instruction*, 8> CatchInfoLost;
240 SmallSet<Instruction*, 8> CatchInfoFound;
241#endif
242
Chris Lattner1c08c712005-01-07 07:47:53 +0000243 unsigned MakeReg(MVT::ValueType VT) {
Chris Lattner84bc5422007-12-31 04:13:23 +0000244 return RegInfo.createVirtualRegister(TLI.getRegClassFor(VT));
Chris Lattner1c08c712005-01-07 07:47:53 +0000245 }
Chris Lattner571e4342006-10-27 21:36:01 +0000246
247 /// isExportedInst - Return true if the specified value is an instruction
248 /// exported from its block.
249 bool isExportedInst(const Value *V) {
250 return ValueMap.count(V);
251 }
Misha Brukmanedf128a2005-04-21 22:36:52 +0000252
Chris Lattner3c384492006-03-16 19:51:18 +0000253 unsigned CreateRegForValue(const Value *V);
254
Chris Lattner1c08c712005-01-07 07:47:53 +0000255 unsigned InitializeRegForValue(const Value *V) {
256 unsigned &R = ValueMap[V];
257 assert(R == 0 && "Already initialized this value register!");
258 return R = CreateRegForValue(V);
259 }
260 };
261}
262
Duncan Sandscf26d7c2007-07-04 20:52:51 +0000263/// isSelector - Return true if this instruction is a call to the
264/// eh.selector intrinsic.
265static bool isSelector(Instruction *I) {
Duncan Sandsf4070822007-06-15 19:04:19 +0000266 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
Anton Korobeynikov8806c7b2007-09-07 11:39:35 +0000267 return (II->getIntrinsicID() == Intrinsic::eh_selector_i32 ||
268 II->getIntrinsicID() == Intrinsic::eh_selector_i64);
Duncan Sandsf4070822007-06-15 19:04:19 +0000269 return false;
270}
271
Chris Lattner1c08c712005-01-07 07:47:53 +0000272/// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by
Nate Begemanf15485a2006-03-27 01:32:24 +0000273/// PHI nodes or outside of the basic block that defines it, or used by a
Andrew Lenharthab0b9492008-02-21 06:45:13 +0000274/// switch or atomic instruction, which may expand to multiple basic blocks.
Chris Lattner1c08c712005-01-07 07:47:53 +0000275static bool isUsedOutsideOfDefiningBlock(Instruction *I) {
276 if (isa<PHINode>(I)) return true;
277 BasicBlock *BB = I->getParent();
278 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; ++UI)
Nate Begemanf15485a2006-03-27 01:32:24 +0000279 if (cast<Instruction>(*UI)->getParent() != BB || isa<PHINode>(*UI) ||
Chris Lattner571e4342006-10-27 21:36:01 +0000280 // FIXME: Remove switchinst special case.
Nate Begemanf15485a2006-03-27 01:32:24 +0000281 isa<SwitchInst>(*UI))
Chris Lattner1c08c712005-01-07 07:47:53 +0000282 return true;
283 return false;
284}
285
Chris Lattnerbf209482005-10-30 19:42:35 +0000286/// isOnlyUsedInEntryBlock - If the specified argument is only used in the
Nate Begemanf15485a2006-03-27 01:32:24 +0000287/// entry block, return true. This includes arguments used by switches, since
288/// the switch may expand into multiple basic blocks.
Chris Lattnerbf209482005-10-30 19:42:35 +0000289static bool isOnlyUsedInEntryBlock(Argument *A) {
290 BasicBlock *Entry = A->getParent()->begin();
291 for (Value::use_iterator UI = A->use_begin(), E = A->use_end(); UI != E; ++UI)
Nate Begemanf15485a2006-03-27 01:32:24 +0000292 if (cast<Instruction>(*UI)->getParent() != Entry || isa<SwitchInst>(*UI))
Chris Lattnerbf209482005-10-30 19:42:35 +0000293 return false; // Use not in entry block.
294 return true;
295}
296
Chris Lattner1c08c712005-01-07 07:47:53 +0000297FunctionLoweringInfo::FunctionLoweringInfo(TargetLowering &tli,
Misha Brukmanedf128a2005-04-21 22:36:52 +0000298 Function &fn, MachineFunction &mf)
Chris Lattner84bc5422007-12-31 04:13:23 +0000299 : TLI(tli), Fn(fn), MF(mf), RegInfo(MF.getRegInfo()) {
Chris Lattner1c08c712005-01-07 07:47:53 +0000300
Chris Lattnerbf209482005-10-30 19:42:35 +0000301 // Create a vreg for each argument register that is not dead and is used
302 // outside of the entry block for the function.
303 for (Function::arg_iterator AI = Fn.arg_begin(), E = Fn.arg_end();
304 AI != E; ++AI)
305 if (!isOnlyUsedInEntryBlock(AI))
306 InitializeRegForValue(AI);
307
Chris Lattner1c08c712005-01-07 07:47:53 +0000308 // Initialize the mapping of values to registers. This is only set up for
309 // instruction values that are used outside of the block that defines
310 // them.
Jeff Cohen2aeaf4e2005-10-01 03:57:14 +0000311 Function::iterator BB = Fn.begin(), EB = Fn.end();
Chris Lattner1c08c712005-01-07 07:47:53 +0000312 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
313 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
Reid Spencerb83eb642006-10-20 07:07:24 +0000314 if (ConstantInt *CUI = dyn_cast<ConstantInt>(AI->getArraySize())) {
Chris Lattner1c08c712005-01-07 07:47:53 +0000315 const Type *Ty = AI->getAllocatedType();
Duncan Sands514ab342007-11-01 20:53:16 +0000316 uint64_t TySize = TLI.getTargetData()->getABITypeSize(Ty);
Nate Begemanae232e72005-11-06 09:00:38 +0000317 unsigned Align =
Chris Lattnerd2b7cec2007-02-14 05:52:17 +0000318 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
Nate Begemanae232e72005-11-06 09:00:38 +0000319 AI->getAlignment());
Chris Lattnera8217e32005-05-13 23:14:17 +0000320
Reid Spencerb83eb642006-10-20 07:07:24 +0000321 TySize *= CUI->getZExtValue(); // Get total allocated size.
Chris Lattnerd222f6a2005-10-18 22:14:06 +0000322 if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
Chris Lattner1c08c712005-01-07 07:47:53 +0000323 StaticAllocaMap[AI] =
Chris Lattner6266c182007-04-25 04:08:28 +0000324 MF.getFrameInfo()->CreateStackObject(TySize, Align);
Chris Lattner1c08c712005-01-07 07:47:53 +0000325 }
326
Jeff Cohen2aeaf4e2005-10-01 03:57:14 +0000327 for (; BB != EB; ++BB)
328 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
Chris Lattner1c08c712005-01-07 07:47:53 +0000329 if (!I->use_empty() && isUsedOutsideOfDefiningBlock(I))
330 if (!isa<AllocaInst>(I) ||
331 !StaticAllocaMap.count(cast<AllocaInst>(I)))
332 InitializeRegForValue(I);
333
334 // Create an initial MachineBasicBlock for each LLVM BasicBlock in F. This
335 // also creates the initial PHI MachineInstrs, though none of the input
336 // operands are populated.
Jeff Cohen2aeaf4e2005-10-01 03:57:14 +0000337 for (BB = Fn.begin(), EB = Fn.end(); BB != EB; ++BB) {
Chris Lattner1c08c712005-01-07 07:47:53 +0000338 MachineBasicBlock *MBB = new MachineBasicBlock(BB);
339 MBBMap[BB] = MBB;
340 MF.getBasicBlockList().push_back(MBB);
341
342 // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
343 // appropriate.
344 PHINode *PN;
Chris Lattner8c494ab2006-10-27 23:50:33 +0000345 for (BasicBlock::iterator I = BB->begin();(PN = dyn_cast<PHINode>(I)); ++I){
346 if (PN->use_empty()) continue;
347
348 MVT::ValueType VT = TLI.getValueType(PN->getType());
Dan Gohman7f321562007-06-25 16:23:39 +0000349 unsigned NumRegisters = TLI.getNumRegisters(VT);
Chris Lattner8c494ab2006-10-27 23:50:33 +0000350 unsigned PHIReg = ValueMap[PN];
351 assert(PHIReg && "PHI node does not have an assigned virtual register!");
Evan Chengc0f64ff2006-11-27 23:37:22 +0000352 const TargetInstrInfo *TII = TLI.getTargetMachine().getInstrInfo();
Dan Gohmanb9f10192007-06-21 14:42:22 +0000353 for (unsigned i = 0; i != NumRegisters; ++i)
Evan Chengc0f64ff2006-11-27 23:37:22 +0000354 BuildMI(MBB, TII->get(TargetInstrInfo::PHI), PHIReg+i);
Chris Lattner8c494ab2006-10-27 23:50:33 +0000355 }
Chris Lattner1c08c712005-01-07 07:47:53 +0000356 }
357}
358
Chris Lattner3c384492006-03-16 19:51:18 +0000359/// CreateRegForValue - Allocate the appropriate number of virtual registers of
360/// the correctly promoted or expanded types. Assign these registers
361/// consecutive vreg numbers and return the first assigned number.
362unsigned FunctionLoweringInfo::CreateRegForValue(const Value *V) {
Dan Gohman23ce5022008-04-25 18:27:55 +0000363 SmallVector<MVT::ValueType, 4> ValueVTs;
Chris Lattnerb606dba2008-04-28 06:44:42 +0000364 ComputeValueVTs(TLI, V->getType(), ValueVTs);
Bill Wendling95b39552007-04-24 21:13:23 +0000365
Dan Gohman23ce5022008-04-25 18:27:55 +0000366 unsigned FirstReg = 0;
367 for (unsigned Value = 0; Value != ValueVTs.size(); ++Value) {
368 MVT::ValueType ValueVT = ValueVTs[Value];
Dan Gohman23ce5022008-04-25 18:27:55 +0000369 MVT::ValueType RegisterVT = TLI.getRegisterType(ValueVT);
Dan Gohman8c8c5fc2007-06-27 14:34:07 +0000370
Chris Lattnerb606dba2008-04-28 06:44:42 +0000371 unsigned NumRegs = TLI.getNumRegisters(ValueVT);
Dan Gohman23ce5022008-04-25 18:27:55 +0000372 for (unsigned i = 0; i != NumRegs; ++i) {
373 unsigned R = MakeReg(RegisterVT);
374 if (!FirstReg) FirstReg = R;
375 }
376 }
377 return FirstReg;
Chris Lattner3c384492006-03-16 19:51:18 +0000378}
Chris Lattner1c08c712005-01-07 07:47:53 +0000379
380//===----------------------------------------------------------------------===//
381/// SelectionDAGLowering - This is the common target-independent lowering
382/// implementation that is parameterized by a TargetLowering object.
383/// Also, targets can overload any lowering method.
384///
385namespace llvm {
386class SelectionDAGLowering {
387 MachineBasicBlock *CurMBB;
388
Chris Lattner0da331f2007-02-04 01:31:47 +0000389 DenseMap<const Value*, SDOperand> NodeMap;
Chris Lattner1c08c712005-01-07 07:47:53 +0000390
Chris Lattnerd3948112005-01-17 22:19:26 +0000391 /// PendingLoads - Loads are not emitted to the program immediately. We bunch
392 /// them up and then emit token factor nodes when possible. This allows us to
393 /// get simple disambiguation between loads without worrying about alias
394 /// analysis.
395 std::vector<SDOperand> PendingLoads;
396
Dan Gohman86e1ebf2008-03-27 19:56:19 +0000397 /// PendingExports - CopyToReg nodes that copy values to virtual registers
398 /// for export to other blocks need to be emitted before any terminator
399 /// instruction, but they have no other ordering requirements. We bunch them
400 /// up and the emit a single tokenfactor for them just before terminator
401 /// instructions.
402 std::vector<SDOperand> PendingExports;
403
Anton Korobeynikov5502bf62007-04-04 21:14:49 +0000404 /// Case - A struct to record the Value for a switch case, and the
405 /// case's target basic block.
406 struct Case {
407 Constant* Low;
408 Constant* High;
409 MachineBasicBlock* BB;
410
411 Case() : Low(0), High(0), BB(0) { }
412 Case(Constant* low, Constant* high, MachineBasicBlock* bb) :
413 Low(low), High(high), BB(bb) { }
414 uint64_t size() const {
415 uint64_t rHigh = cast<ConstantInt>(High)->getSExtValue();
416 uint64_t rLow = cast<ConstantInt>(Low)->getSExtValue();
417 return (rHigh - rLow + 1ULL);
418 }
419 };
420
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000421 struct CaseBits {
422 uint64_t Mask;
423 MachineBasicBlock* BB;
424 unsigned Bits;
425
426 CaseBits(uint64_t mask, MachineBasicBlock* bb, unsigned bits):
427 Mask(mask), BB(bb), Bits(bits) { }
428 };
429
Anton Korobeynikov5502bf62007-04-04 21:14:49 +0000430 typedef std::vector<Case> CaseVector;
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000431 typedef std::vector<CaseBits> CaseBitsVector;
Anton Korobeynikov5502bf62007-04-04 21:14:49 +0000432 typedef CaseVector::iterator CaseItr;
433 typedef std::pair<CaseItr, CaseItr> CaseRange;
Nate Begemanf15485a2006-03-27 01:32:24 +0000434
435 /// CaseRec - A struct with ctor used in lowering switches to a binary tree
436 /// of conditional branches.
437 struct CaseRec {
438 CaseRec(MachineBasicBlock *bb, Constant *lt, Constant *ge, CaseRange r) :
439 CaseBB(bb), LT(lt), GE(ge), Range(r) {}
440
441 /// CaseBB - The MBB in which to emit the compare and branch
442 MachineBasicBlock *CaseBB;
443 /// LT, GE - If nonzero, we know the current case value must be less-than or
444 /// greater-than-or-equal-to these Constants.
445 Constant *LT;
446 Constant *GE;
447 /// Range - A pair of iterators representing the range of case values to be
448 /// processed at this point in the binary search tree.
449 CaseRange Range;
450 };
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +0000451
452 typedef std::vector<CaseRec> CaseRecVector;
Anton Korobeynikov5502bf62007-04-04 21:14:49 +0000453
454 /// The comparison function for sorting the switch case values in the vector.
455 /// WARNING: Case ranges should be disjoint!
Nate Begemanf15485a2006-03-27 01:32:24 +0000456 struct CaseCmp {
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000457 bool operator () (const Case& C1, const Case& C2) {
Anton Korobeynikov5502bf62007-04-04 21:14:49 +0000458 assert(isa<ConstantInt>(C1.Low) && isa<ConstantInt>(C2.High));
459 const ConstantInt* CI1 = cast<const ConstantInt>(C1.Low);
460 const ConstantInt* CI2 = cast<const ConstantInt>(C2.High);
461 return CI1->getValue().slt(CI2->getValue());
Nate Begemanf15485a2006-03-27 01:32:24 +0000462 }
463 };
Anton Korobeynikov5502bf62007-04-04 21:14:49 +0000464
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000465 struct CaseBitsCmp {
466 bool operator () (const CaseBits& C1, const CaseBits& C2) {
467 return C1.Bits > C2.Bits;
468 }
469 };
470
Anton Korobeynikov5502bf62007-04-04 21:14:49 +0000471 unsigned Clusterify(CaseVector& Cases, const SwitchInst &SI);
Nate Begemanf15485a2006-03-27 01:32:24 +0000472
Chris Lattner1c08c712005-01-07 07:47:53 +0000473public:
474 // TLI - This is information that describes the available target features we
475 // need for lowering. This indicates when operations are unavailable,
476 // implemented with a libcall, etc.
477 TargetLowering &TLI;
478 SelectionDAG &DAG;
Owen Andersona69571c2006-05-03 01:29:57 +0000479 const TargetData *TD;
Dan Gohman5f43f922007-08-27 16:26:13 +0000480 AliasAnalysis &AA;
Chris Lattner1c08c712005-01-07 07:47:53 +0000481
Nate Begemanf15485a2006-03-27 01:32:24 +0000482 /// SwitchCases - Vector of CaseBlock structures used to communicate
483 /// SwitchInst code generation information.
484 std::vector<SelectionDAGISel::CaseBlock> SwitchCases;
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +0000485 /// JTCases - Vector of JumpTable structures used to communicate
486 /// SwitchInst code generation information.
487 std::vector<SelectionDAGISel::JumpTableBlock> JTCases;
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000488 std::vector<SelectionDAGISel::BitTestBlock> BitTestCases;
Nate Begemanf15485a2006-03-27 01:32:24 +0000489
Chris Lattner1c08c712005-01-07 07:47:53 +0000490 /// FuncInfo - Information about the function as a whole.
491 ///
492 FunctionLoweringInfo &FuncInfo;
Gordon Henriksence224772008-01-07 01:30:38 +0000493
494 /// GCI - Garbage collection metadata for the function.
495 CollectorMetadata *GCI;
Chris Lattner1c08c712005-01-07 07:47:53 +0000496
497 SelectionDAGLowering(SelectionDAG &dag, TargetLowering &tli,
Dan Gohman5f43f922007-08-27 16:26:13 +0000498 AliasAnalysis &aa,
Gordon Henriksence224772008-01-07 01:30:38 +0000499 FunctionLoweringInfo &funcinfo,
500 CollectorMetadata *gci)
Dan Gohman5f43f922007-08-27 16:26:13 +0000501 : TLI(tli), DAG(dag), TD(DAG.getTarget().getTargetData()), AA(aa),
Gordon Henriksence224772008-01-07 01:30:38 +0000502 FuncInfo(funcinfo), GCI(gci) {
Chris Lattner1c08c712005-01-07 07:47:53 +0000503 }
504
Dan Gohman86e1ebf2008-03-27 19:56:19 +0000505 /// getRoot - Return the current virtual root of the Selection DAG,
506 /// flushing any PendingLoad items. This must be done before emitting
507 /// a store or any other node that may need to be ordered after any
508 /// prior load instructions.
Chris Lattnera651cf62005-01-17 19:43:36 +0000509 ///
510 SDOperand getRoot() {
Chris Lattnerd3948112005-01-17 22:19:26 +0000511 if (PendingLoads.empty())
512 return DAG.getRoot();
Misha Brukmanedf128a2005-04-21 22:36:52 +0000513
Chris Lattnerd3948112005-01-17 22:19:26 +0000514 if (PendingLoads.size() == 1) {
515 SDOperand Root = PendingLoads[0];
516 DAG.setRoot(Root);
517 PendingLoads.clear();
518 return Root;
519 }
520
521 // Otherwise, we have to make a token factor node.
Chris Lattnerbd564bf2006-08-08 02:23:42 +0000522 SDOperand Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
523 &PendingLoads[0], PendingLoads.size());
Chris Lattnerd3948112005-01-17 22:19:26 +0000524 PendingLoads.clear();
525 DAG.setRoot(Root);
526 return Root;
Chris Lattnera651cf62005-01-17 19:43:36 +0000527 }
528
Dan Gohman86e1ebf2008-03-27 19:56:19 +0000529 /// getControlRoot - Similar to getRoot, but instead of flushing all the
530 /// PendingLoad items, flush all the PendingExports items. It is necessary
531 /// to do this before emitting a terminator instruction.
532 ///
533 SDOperand getControlRoot() {
534 SDOperand Root = DAG.getRoot();
535
536 if (PendingExports.empty())
537 return Root;
538
539 // Turn all of the CopyToReg chains into one factored node.
540 if (Root.getOpcode() != ISD::EntryToken) {
541 unsigned i = 0, e = PendingExports.size();
542 for (; i != e; ++i) {
543 assert(PendingExports[i].Val->getNumOperands() > 1);
544 if (PendingExports[i].Val->getOperand(0) == Root)
545 break; // Don't add the root if we already indirectly depend on it.
546 }
547
548 if (i == e)
549 PendingExports.push_back(Root);
550 }
551
552 Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
553 &PendingExports[0],
554 PendingExports.size());
555 PendingExports.clear();
556 DAG.setRoot(Root);
557 return Root;
558 }
559
560 void CopyValueToVirtualRegister(Value *V, unsigned Reg);
Chris Lattner571e4342006-10-27 21:36:01 +0000561
Chris Lattner1c08c712005-01-07 07:47:53 +0000562 void visit(Instruction &I) { visit(I.getOpcode(), I); }
563
564 void visit(unsigned Opcode, User &I) {
Chris Lattner1e7aa5c2006-11-10 04:41:34 +0000565 // Note: this doesn't use InstVisitor, because it has to work with
566 // ConstantExpr's in addition to instructions.
Chris Lattner1c08c712005-01-07 07:47:53 +0000567 switch (Opcode) {
568 default: assert(0 && "Unknown instruction type encountered!");
569 abort();
570 // Build the switch statement using the Instruction.def file.
571#define HANDLE_INST(NUM, OPCODE, CLASS) \
572 case Instruction::OPCODE:return visit##OPCODE((CLASS&)I);
573#include "llvm/Instruction.def"
574 }
575 }
576
577 void setCurrentBasicBlock(MachineBasicBlock *MBB) { CurMBB = MBB; }
578
Chris Lattner28b5b1c2006-03-15 22:19:46 +0000579 SDOperand getLoadFrom(const Type *Ty, SDOperand Ptr,
Evan Cheng466685d2006-10-09 20:57:25 +0000580 const Value *SV, SDOperand Root,
Christopher Lamb95c218a2007-04-22 23:15:30 +0000581 bool isVolatile, unsigned Alignment);
Chris Lattner1c08c712005-01-07 07:47:53 +0000582
Chris Lattner199862b2006-03-16 19:57:50 +0000583 SDOperand getValue(const Value *V);
Chris Lattner1c08c712005-01-07 07:47:53 +0000584
Chris Lattner0da331f2007-02-04 01:31:47 +0000585 void setValue(const Value *V, SDOperand NewN) {
Chris Lattner1c08c712005-01-07 07:47:53 +0000586 SDOperand &N = NodeMap[V];
587 assert(N.Val == 0 && "Already set a value for this node!");
Chris Lattner0da331f2007-02-04 01:31:47 +0000588 N = NewN;
Chris Lattner1c08c712005-01-07 07:47:53 +0000589 }
Chris Lattner4e4b5762006-02-01 18:59:47 +0000590
Evan Cheng5c807602008-02-26 02:33:44 +0000591 void GetRegistersForValue(SDISelAsmOperandInfo &OpInfo, bool HasEarlyClobber,
Chris Lattnere7cf56a2007-04-30 21:11:17 +0000592 std::set<unsigned> &OutputRegs,
593 std::set<unsigned> &InputRegs);
Nate Begemanf15485a2006-03-27 01:32:24 +0000594
Chris Lattner571e4342006-10-27 21:36:01 +0000595 void FindMergedConditions(Value *Cond, MachineBasicBlock *TBB,
596 MachineBasicBlock *FBB, MachineBasicBlock *CurBB,
597 unsigned Opc);
Chris Lattner8c494ab2006-10-27 23:50:33 +0000598 bool isExportableFromCurrentBlock(Value *V, const BasicBlock *FromBB);
Chris Lattner571e4342006-10-27 21:36:01 +0000599 void ExportFromCurrentBlock(Value *V);
Duncan Sands6f74b482007-12-19 09:48:52 +0000600 void LowerCallTo(CallSite CS, SDOperand Callee, bool IsTailCall,
Anton Korobeynikov070280e2007-05-23 11:08:31 +0000601 MachineBasicBlock *LandingPad = NULL);
Duncan Sandsdc024672007-11-27 13:23:08 +0000602
Chris Lattner1c08c712005-01-07 07:47:53 +0000603 // Terminator instructions.
604 void visitRet(ReturnInst &I);
605 void visitBr(BranchInst &I);
Nate Begemanf15485a2006-03-27 01:32:24 +0000606 void visitSwitch(SwitchInst &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000607 void visitUnreachable(UnreachableInst &I) { /* noop */ }
608
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +0000609 // Helpers for visitSwitch
Anton Korobeynikovdd433212007-03-27 12:05:48 +0000610 bool handleSmallSwitchRange(CaseRec& CR,
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +0000611 CaseRecVector& WorkList,
612 Value* SV,
613 MachineBasicBlock* Default);
Anton Korobeynikovdd433212007-03-27 12:05:48 +0000614 bool handleJTSwitchCase(CaseRec& CR,
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +0000615 CaseRecVector& WorkList,
616 Value* SV,
617 MachineBasicBlock* Default);
Anton Korobeynikovdd433212007-03-27 12:05:48 +0000618 bool handleBTSplitSwitchCase(CaseRec& CR,
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +0000619 CaseRecVector& WorkList,
620 Value* SV,
621 MachineBasicBlock* Default);
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000622 bool handleBitTestsSwitchCase(CaseRec& CR,
623 CaseRecVector& WorkList,
624 Value* SV,
625 MachineBasicBlock* Default);
Nate Begemanf15485a2006-03-27 01:32:24 +0000626 void visitSwitchCase(SelectionDAGISel::CaseBlock &CB);
Anton Korobeynikov4198c582007-04-09 12:31:58 +0000627 void visitBitTestHeader(SelectionDAGISel::BitTestBlock &B);
628 void visitBitTestCase(MachineBasicBlock* NextMBB,
629 unsigned Reg,
630 SelectionDAGISel::BitTestCase &B);
Nate Begeman37efe672006-04-22 18:53:45 +0000631 void visitJumpTable(SelectionDAGISel::JumpTable &JT);
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +0000632 void visitJumpTableHeader(SelectionDAGISel::JumpTable &JT,
633 SelectionDAGISel::JumpTableHeader &JTH);
Nate Begemanf15485a2006-03-27 01:32:24 +0000634
Chris Lattner1c08c712005-01-07 07:47:53 +0000635 // These all get lowered before this pass.
Jim Laskeyb180aa12007-02-21 22:53:45 +0000636 void visitInvoke(InvokeInst &I);
637 void visitUnwind(UnwindInst &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000638
Dan Gohman7f321562007-06-25 16:23:39 +0000639 void visitBinary(User &I, unsigned OpCode);
Nate Begemane21ea612005-11-18 07:42:56 +0000640 void visitShift(User &I, unsigned Opcode);
Nate Begeman5fbb5d22005-11-19 00:36:38 +0000641 void visitAdd(User &I) {
Dan Gohman7f321562007-06-25 16:23:39 +0000642 if (I.getType()->isFPOrFPVector())
643 visitBinary(I, ISD::FADD);
Reid Spencer1628cec2006-10-26 06:15:43 +0000644 else
Dan Gohman7f321562007-06-25 16:23:39 +0000645 visitBinary(I, ISD::ADD);
Chris Lattner01b3d732005-09-28 22:28:18 +0000646 }
Chris Lattnerb9fccc42005-04-02 05:04:50 +0000647 void visitSub(User &I);
Reid Spencer1628cec2006-10-26 06:15:43 +0000648 void visitMul(User &I) {
Dan Gohman7f321562007-06-25 16:23:39 +0000649 if (I.getType()->isFPOrFPVector())
650 visitBinary(I, ISD::FMUL);
Reid Spencer1628cec2006-10-26 06:15:43 +0000651 else
Dan Gohman7f321562007-06-25 16:23:39 +0000652 visitBinary(I, ISD::MUL);
Chris Lattner01b3d732005-09-28 22:28:18 +0000653 }
Dan Gohman7f321562007-06-25 16:23:39 +0000654 void visitURem(User &I) { visitBinary(I, ISD::UREM); }
655 void visitSRem(User &I) { visitBinary(I, ISD::SREM); }
656 void visitFRem(User &I) { visitBinary(I, ISD::FREM); }
657 void visitUDiv(User &I) { visitBinary(I, ISD::UDIV); }
658 void visitSDiv(User &I) { visitBinary(I, ISD::SDIV); }
659 void visitFDiv(User &I) { visitBinary(I, ISD::FDIV); }
660 void visitAnd (User &I) { visitBinary(I, ISD::AND); }
661 void visitOr (User &I) { visitBinary(I, ISD::OR); }
662 void visitXor (User &I) { visitBinary(I, ISD::XOR); }
Reid Spencer24d6da52007-01-21 00:29:26 +0000663 void visitShl (User &I) { visitShift(I, ISD::SHL); }
Reid Spencer3822ff52006-11-08 06:47:33 +0000664 void visitLShr(User &I) { visitShift(I, ISD::SRL); }
665 void visitAShr(User &I) { visitShift(I, ISD::SRA); }
Reid Spencer45fb3f32006-11-20 01:22:35 +0000666 void visitICmp(User &I);
667 void visitFCmp(User &I);
Reid Spencer3da59db2006-11-27 01:05:10 +0000668 // Visit the conversion instructions
669 void visitTrunc(User &I);
670 void visitZExt(User &I);
671 void visitSExt(User &I);
672 void visitFPTrunc(User &I);
673 void visitFPExt(User &I);
674 void visitFPToUI(User &I);
675 void visitFPToSI(User &I);
676 void visitUIToFP(User &I);
677 void visitSIToFP(User &I);
678 void visitPtrToInt(User &I);
679 void visitIntToPtr(User &I);
680 void visitBitCast(User &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000681
Chris Lattner2bbd8102006-03-29 00:11:43 +0000682 void visitExtractElement(User &I);
683 void visitInsertElement(User &I);
Chris Lattner3e104b12006-04-08 04:15:24 +0000684 void visitShuffleVector(User &I);
Chris Lattnerc7029802006-03-18 01:44:44 +0000685
Chris Lattner1c08c712005-01-07 07:47:53 +0000686 void visitGetElementPtr(User &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000687 void visitSelect(User &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000688
689 void visitMalloc(MallocInst &I);
690 void visitFree(FreeInst &I);
691 void visitAlloca(AllocaInst &I);
692 void visitLoad(LoadInst &I);
693 void visitStore(StoreInst &I);
694 void visitPHI(PHINode &I) { } // PHI nodes are handled specially.
695 void visitCall(CallInst &I);
Duncan Sandsfd7b3262007-12-17 18:08:19 +0000696 void visitInlineAsm(CallSite CS);
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +0000697 const char *visitIntrinsicCall(CallInst &I, unsigned Intrinsic);
Chris Lattner0eade312006-03-24 02:22:33 +0000698 void visitTargetIntrinsic(CallInst &I, unsigned Intrinsic);
Chris Lattner1c08c712005-01-07 07:47:53 +0000699
Chris Lattner1c08c712005-01-07 07:47:53 +0000700 void visitVAStart(CallInst &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000701 void visitVAArg(VAArgInst &I);
702 void visitVAEnd(CallInst &I);
703 void visitVACopy(CallInst &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000704
Dan Gohmanef5d1942008-03-11 21:11:25 +0000705 void visitGetResult(GetResultInst &I);
Devang Patel40a04212008-02-19 22:15:16 +0000706
Chris Lattner1c08c712005-01-07 07:47:53 +0000707 void visitUserOp1(Instruction &I) {
708 assert(0 && "UserOp1 should not exist at instruction selection time!");
709 abort();
710 }
711 void visitUserOp2(Instruction &I) {
712 assert(0 && "UserOp2 should not exist at instruction selection time!");
713 abort();
714 }
715};
716} // end namespace llvm
717
Dan Gohman6183f782007-07-05 20:12:34 +0000718
Duncan Sandsb988bac2008-02-11 20:58:28 +0000719/// getCopyFromParts - Create a value that contains the specified legal parts
720/// combined into the value they represent. If the parts combine to a type
721/// larger then ValueVT then AssertOp can be used to specify whether the extra
722/// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
Chris Lattner4468c1f2008-03-09 09:38:46 +0000723/// (ISD::AssertSext).
Dan Gohman6183f782007-07-05 20:12:34 +0000724static SDOperand getCopyFromParts(SelectionDAG &DAG,
725 const SDOperand *Parts,
726 unsigned NumParts,
727 MVT::ValueType PartVT,
728 MVT::ValueType ValueVT,
Chris Lattner4468c1f2008-03-09 09:38:46 +0000729 ISD::NodeType AssertOp = ISD::DELETED_NODE) {
Duncan Sands014e04a2008-02-12 20:46:31 +0000730 assert(NumParts > 0 && "No parts to assemble!");
731 TargetLowering &TLI = DAG.getTargetLoweringInfo();
732 SDOperand Val = Parts[0];
Dan Gohman6183f782007-07-05 20:12:34 +0000733
Duncan Sands014e04a2008-02-12 20:46:31 +0000734 if (NumParts > 1) {
735 // Assemble the value from multiple parts.
736 if (!MVT::isVector(ValueVT)) {
737 unsigned PartBits = MVT::getSizeInBits(PartVT);
738 unsigned ValueBits = MVT::getSizeInBits(ValueVT);
Dan Gohman6183f782007-07-05 20:12:34 +0000739
Duncan Sands014e04a2008-02-12 20:46:31 +0000740 // Assemble the power of 2 part.
741 unsigned RoundParts = NumParts & (NumParts - 1) ?
742 1 << Log2_32(NumParts) : NumParts;
743 unsigned RoundBits = PartBits * RoundParts;
744 MVT::ValueType RoundVT = RoundBits == ValueBits ?
745 ValueVT : MVT::getIntegerType(RoundBits);
746 SDOperand Lo, Hi;
747
748 if (RoundParts > 2) {
749 MVT::ValueType HalfVT = MVT::getIntegerType(RoundBits/2);
750 Lo = getCopyFromParts(DAG, Parts, RoundParts/2, PartVT, HalfVT);
751 Hi = getCopyFromParts(DAG, Parts+RoundParts/2, RoundParts/2,
752 PartVT, HalfVT);
Dan Gohman6183f782007-07-05 20:12:34 +0000753 } else {
Duncan Sands014e04a2008-02-12 20:46:31 +0000754 Lo = Parts[0];
755 Hi = Parts[1];
Dan Gohman6183f782007-07-05 20:12:34 +0000756 }
Duncan Sands014e04a2008-02-12 20:46:31 +0000757 if (TLI.isBigEndian())
758 std::swap(Lo, Hi);
759 Val = DAG.getNode(ISD::BUILD_PAIR, RoundVT, Lo, Hi);
760
761 if (RoundParts < NumParts) {
762 // Assemble the trailing non-power-of-2 part.
763 unsigned OddParts = NumParts - RoundParts;
764 MVT::ValueType OddVT = MVT::getIntegerType(OddParts * PartBits);
765 Hi = getCopyFromParts(DAG, Parts+RoundParts, OddParts, PartVT, OddVT);
766
767 // Combine the round and odd parts.
768 Lo = Val;
769 if (TLI.isBigEndian())
770 std::swap(Lo, Hi);
771 MVT::ValueType TotalVT = MVT::getIntegerType(NumParts * PartBits);
772 Hi = DAG.getNode(ISD::ANY_EXTEND, TotalVT, Hi);
773 Hi = DAG.getNode(ISD::SHL, TotalVT, Hi,
774 DAG.getConstant(MVT::getSizeInBits(Lo.getValueType()),
775 TLI.getShiftAmountTy()));
776 Lo = DAG.getNode(ISD::ZERO_EXTEND, TotalVT, Lo);
777 Val = DAG.getNode(ISD::OR, TotalVT, Lo, Hi);
778 }
779 } else {
780 // Handle a multi-element vector.
781 MVT::ValueType IntermediateVT, RegisterVT;
782 unsigned NumIntermediates;
783 unsigned NumRegs =
784 TLI.getVectorTypeBreakdown(ValueVT, IntermediateVT, NumIntermediates,
785 RegisterVT);
786
787 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
788 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
789 assert(RegisterVT == Parts[0].getValueType() &&
790 "Part type doesn't match part!");
791
792 // Assemble the parts into intermediate operands.
793 SmallVector<SDOperand, 8> Ops(NumIntermediates);
794 if (NumIntermediates == NumParts) {
795 // If the register was not expanded, truncate or copy the value,
796 // as appropriate.
797 for (unsigned i = 0; i != NumParts; ++i)
798 Ops[i] = getCopyFromParts(DAG, &Parts[i], 1,
799 PartVT, IntermediateVT);
800 } else if (NumParts > 0) {
801 // If the intermediate type was expanded, build the intermediate operands
802 // from the parts.
803 assert(NumParts % NumIntermediates == 0 &&
804 "Must expand into a divisible number of parts!");
805 unsigned Factor = NumParts / NumIntermediates;
806 for (unsigned i = 0; i != NumIntermediates; ++i)
807 Ops[i] = getCopyFromParts(DAG, &Parts[i * Factor], Factor,
808 PartVT, IntermediateVT);
809 }
810
811 // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the intermediate
812 // operands.
813 Val = DAG.getNode(MVT::isVector(IntermediateVT) ?
814 ISD::CONCAT_VECTORS : ISD::BUILD_VECTOR,
815 ValueVT, &Ops[0], NumIntermediates);
Dan Gohman6183f782007-07-05 20:12:34 +0000816 }
Dan Gohman6183f782007-07-05 20:12:34 +0000817 }
818
Duncan Sands014e04a2008-02-12 20:46:31 +0000819 // There is now one part, held in Val. Correct it to match ValueVT.
820 PartVT = Val.getValueType();
Dan Gohman6183f782007-07-05 20:12:34 +0000821
Duncan Sands014e04a2008-02-12 20:46:31 +0000822 if (PartVT == ValueVT)
823 return Val;
Dan Gohman6183f782007-07-05 20:12:34 +0000824
Duncan Sands014e04a2008-02-12 20:46:31 +0000825 if (MVT::isVector(PartVT)) {
826 assert(MVT::isVector(ValueVT) && "Unknown vector conversion!");
827 return DAG.getNode(ISD::BIT_CONVERT, ValueVT, Val);
Dan Gohman6183f782007-07-05 20:12:34 +0000828 }
Duncan Sands014e04a2008-02-12 20:46:31 +0000829
830 if (MVT::isVector(ValueVT)) {
831 assert(MVT::getVectorElementType(ValueVT) == PartVT &&
832 MVT::getVectorNumElements(ValueVT) == 1 &&
833 "Only trivial scalar-to-vector conversions should get here!");
834 return DAG.getNode(ISD::BUILD_VECTOR, ValueVT, Val);
835 }
836
837 if (MVT::isInteger(PartVT) &&
838 MVT::isInteger(ValueVT)) {
839 if (MVT::getSizeInBits(ValueVT) < MVT::getSizeInBits(PartVT)) {
840 // For a truncate, see if we have any information to
841 // indicate whether the truncated bits will always be
842 // zero or sign-extension.
843 if (AssertOp != ISD::DELETED_NODE)
844 Val = DAG.getNode(AssertOp, PartVT, Val,
845 DAG.getValueType(ValueVT));
846 return DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
847 } else {
848 return DAG.getNode(ISD::ANY_EXTEND, ValueVT, Val);
849 }
850 }
851
Chris Lattnerd43d85c2008-03-09 07:47:22 +0000852 if (MVT::isFloatingPoint(PartVT) && MVT::isFloatingPoint(ValueVT)) {
853 if (ValueVT < Val.getValueType())
Chris Lattner4468c1f2008-03-09 09:38:46 +0000854 // FP_ROUND's are always exact here.
Chris Lattnerd43d85c2008-03-09 07:47:22 +0000855 return DAG.getNode(ISD::FP_ROUND, ValueVT, Val,
Chris Lattner4468c1f2008-03-09 09:38:46 +0000856 DAG.getIntPtrConstant(1));
Chris Lattnerd43d85c2008-03-09 07:47:22 +0000857 return DAG.getNode(ISD::FP_EXTEND, ValueVT, Val);
858 }
Duncan Sands014e04a2008-02-12 20:46:31 +0000859
860 if (MVT::getSizeInBits(PartVT) == MVT::getSizeInBits(ValueVT))
861 return DAG.getNode(ISD::BIT_CONVERT, ValueVT, Val);
862
863 assert(0 && "Unknown mismatch!");
Chris Lattnerd27c9912008-03-30 18:22:13 +0000864 return SDOperand();
Dan Gohman6183f782007-07-05 20:12:34 +0000865}
866
Duncan Sandsb988bac2008-02-11 20:58:28 +0000867/// getCopyToParts - Create a series of nodes that contain the specified value
868/// split into legal parts. If the parts contain more bits than Val, then, for
869/// integers, ExtendKind can be used to specify how to generate the extra bits.
Dan Gohman6183f782007-07-05 20:12:34 +0000870static void getCopyToParts(SelectionDAG &DAG,
871 SDOperand Val,
872 SDOperand *Parts,
873 unsigned NumParts,
Duncan Sandsb988bac2008-02-11 20:58:28 +0000874 MVT::ValueType PartVT,
875 ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
Dan Gohman25ac7e82007-08-10 14:59:38 +0000876 TargetLowering &TLI = DAG.getTargetLoweringInfo();
877 MVT::ValueType PtrVT = TLI.getPointerTy();
Dan Gohman6183f782007-07-05 20:12:34 +0000878 MVT::ValueType ValueVT = Val.getValueType();
Duncan Sands014e04a2008-02-12 20:46:31 +0000879 unsigned PartBits = MVT::getSizeInBits(PartVT);
880 assert(TLI.isTypeLegal(PartVT) && "Copying to an illegal type!");
Dan Gohman6183f782007-07-05 20:12:34 +0000881
Duncan Sands014e04a2008-02-12 20:46:31 +0000882 if (!NumParts)
883 return;
884
885 if (!MVT::isVector(ValueVT)) {
886 if (PartVT == ValueVT) {
887 assert(NumParts == 1 && "No-op copy with multiple parts!");
888 Parts[0] = Val;
Dan Gohman6183f782007-07-05 20:12:34 +0000889 return;
890 }
891
Duncan Sands014e04a2008-02-12 20:46:31 +0000892 if (NumParts * PartBits > MVT::getSizeInBits(ValueVT)) {
893 // If the parts cover more bits than the value has, promote the value.
894 if (MVT::isFloatingPoint(PartVT) && MVT::isFloatingPoint(ValueVT)) {
895 assert(NumParts == 1 && "Do not know what to promote to!");
Dan Gohman6183f782007-07-05 20:12:34 +0000896 Val = DAG.getNode(ISD::FP_EXTEND, PartVT, Val);
Duncan Sands014e04a2008-02-12 20:46:31 +0000897 } else if (MVT::isInteger(PartVT) && MVT::isInteger(ValueVT)) {
898 ValueVT = MVT::getIntegerType(NumParts * PartBits);
899 Val = DAG.getNode(ExtendKind, ValueVT, Val);
900 } else {
901 assert(0 && "Unknown mismatch!");
902 }
903 } else if (PartBits == MVT::getSizeInBits(ValueVT)) {
904 // Different types of the same size.
905 assert(NumParts == 1 && PartVT != ValueVT);
906 Val = DAG.getNode(ISD::BIT_CONVERT, PartVT, Val);
907 } else if (NumParts * PartBits < MVT::getSizeInBits(ValueVT)) {
908 // If the parts cover less bits than value has, truncate the value.
909 if (MVT::isInteger(PartVT) && MVT::isInteger(ValueVT)) {
910 ValueVT = MVT::getIntegerType(NumParts * PartBits);
911 Val = DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
Dan Gohman6183f782007-07-05 20:12:34 +0000912 } else {
913 assert(0 && "Unknown mismatch!");
914 }
915 }
Duncan Sands014e04a2008-02-12 20:46:31 +0000916
917 // The value may have changed - recompute ValueVT.
918 ValueVT = Val.getValueType();
919 assert(NumParts * PartBits == MVT::getSizeInBits(ValueVT) &&
920 "Failed to tile the value with PartVT!");
921
922 if (NumParts == 1) {
923 assert(PartVT == ValueVT && "Type conversion failed!");
924 Parts[0] = Val;
925 return;
926 }
927
928 // Expand the value into multiple parts.
929 if (NumParts & (NumParts - 1)) {
930 // The number of parts is not a power of 2. Split off and copy the tail.
931 assert(MVT::isInteger(PartVT) && MVT::isInteger(ValueVT) &&
932 "Do not know what to expand to!");
933 unsigned RoundParts = 1 << Log2_32(NumParts);
934 unsigned RoundBits = RoundParts * PartBits;
935 unsigned OddParts = NumParts - RoundParts;
936 SDOperand OddVal = DAG.getNode(ISD::SRL, ValueVT, Val,
937 DAG.getConstant(RoundBits,
938 TLI.getShiftAmountTy()));
939 getCopyToParts(DAG, OddVal, Parts + RoundParts, OddParts, PartVT);
940 if (TLI.isBigEndian())
941 // The odd parts were reversed by getCopyToParts - unreverse them.
942 std::reverse(Parts + RoundParts, Parts + NumParts);
943 NumParts = RoundParts;
944 ValueVT = MVT::getIntegerType(NumParts * PartBits);
945 Val = DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
946 }
947
948 // The number of parts is a power of 2. Repeatedly bisect the value using
949 // EXTRACT_ELEMENT.
Duncan Sands25eb0432008-03-12 20:30:08 +0000950 Parts[0] = DAG.getNode(ISD::BIT_CONVERT,
951 MVT::getIntegerType(MVT::getSizeInBits(ValueVT)),
952 Val);
Duncan Sands014e04a2008-02-12 20:46:31 +0000953 for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
954 for (unsigned i = 0; i < NumParts; i += StepSize) {
955 unsigned ThisBits = StepSize * PartBits / 2;
Duncan Sands25eb0432008-03-12 20:30:08 +0000956 MVT::ValueType ThisVT = MVT::getIntegerType (ThisBits);
957 SDOperand &Part0 = Parts[i];
958 SDOperand &Part1 = Parts[i+StepSize/2];
Duncan Sands014e04a2008-02-12 20:46:31 +0000959
Duncan Sands25eb0432008-03-12 20:30:08 +0000960 Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, ThisVT, Part0,
961 DAG.getConstant(1, PtrVT));
962 Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, ThisVT, Part0,
963 DAG.getConstant(0, PtrVT));
964
965 if (ThisBits == PartBits && ThisVT != PartVT) {
966 Part0 = DAG.getNode(ISD::BIT_CONVERT, PartVT, Part0);
967 Part1 = DAG.getNode(ISD::BIT_CONVERT, PartVT, Part1);
968 }
Duncan Sands014e04a2008-02-12 20:46:31 +0000969 }
970 }
971
972 if (TLI.isBigEndian())
973 std::reverse(Parts, Parts + NumParts);
974
975 return;
976 }
977
978 // Vector ValueVT.
979 if (NumParts == 1) {
980 if (PartVT != ValueVT) {
981 if (MVT::isVector(PartVT)) {
982 Val = DAG.getNode(ISD::BIT_CONVERT, PartVT, Val);
983 } else {
984 assert(MVT::getVectorElementType(ValueVT) == PartVT &&
985 MVT::getVectorNumElements(ValueVT) == 1 &&
986 "Only trivial vector-to-scalar conversions should get here!");
987 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, PartVT, Val,
988 DAG.getConstant(0, PtrVT));
989 }
990 }
991
Dan Gohman6183f782007-07-05 20:12:34 +0000992 Parts[0] = Val;
993 return;
994 }
995
996 // Handle a multi-element vector.
997 MVT::ValueType IntermediateVT, RegisterVT;
998 unsigned NumIntermediates;
999 unsigned NumRegs =
1000 DAG.getTargetLoweringInfo()
1001 .getVectorTypeBreakdown(ValueVT, IntermediateVT, NumIntermediates,
1002 RegisterVT);
1003 unsigned NumElements = MVT::getVectorNumElements(ValueVT);
1004
1005 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
1006 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
1007
1008 // Split the vector into intermediate operands.
1009 SmallVector<SDOperand, 8> Ops(NumIntermediates);
1010 for (unsigned i = 0; i != NumIntermediates; ++i)
1011 if (MVT::isVector(IntermediateVT))
1012 Ops[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR,
1013 IntermediateVT, Val,
1014 DAG.getConstant(i * (NumElements / NumIntermediates),
Dan Gohman25ac7e82007-08-10 14:59:38 +00001015 PtrVT));
Dan Gohman6183f782007-07-05 20:12:34 +00001016 else
1017 Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
1018 IntermediateVT, Val,
Dan Gohman25ac7e82007-08-10 14:59:38 +00001019 DAG.getConstant(i, PtrVT));
Dan Gohman6183f782007-07-05 20:12:34 +00001020
1021 // Split the intermediate operands into legal parts.
1022 if (NumParts == NumIntermediates) {
1023 // If the register was not expanded, promote or copy the value,
1024 // as appropriate.
1025 for (unsigned i = 0; i != NumParts; ++i)
Dan Gohman532dc2e2007-07-09 20:59:04 +00001026 getCopyToParts(DAG, Ops[i], &Parts[i], 1, PartVT);
Dan Gohman6183f782007-07-05 20:12:34 +00001027 } else if (NumParts > 0) {
1028 // If the intermediate type was expanded, split each the value into
1029 // legal parts.
1030 assert(NumParts % NumIntermediates == 0 &&
1031 "Must expand into a divisible number of parts!");
1032 unsigned Factor = NumParts / NumIntermediates;
1033 for (unsigned i = 0; i != NumIntermediates; ++i)
Dan Gohman532dc2e2007-07-09 20:59:04 +00001034 getCopyToParts(DAG, Ops[i], &Parts[i * Factor], Factor, PartVT);
Dan Gohman6183f782007-07-05 20:12:34 +00001035 }
1036}
1037
1038
Chris Lattner199862b2006-03-16 19:57:50 +00001039SDOperand SelectionDAGLowering::getValue(const Value *V) {
1040 SDOperand &N = NodeMap[V];
1041 if (N.Val) return N;
1042
1043 const Type *VTy = V->getType();
Chris Lattner199862b2006-03-16 19:57:50 +00001044 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V))) {
Chris Lattnerb606dba2008-04-28 06:44:42 +00001045 MVT::ValueType VT = TLI.getValueType(VTy, true);
1046
1047 if (ConstantInt *CI = dyn_cast<ConstantInt>(C))
1048 return N = DAG.getConstant(CI->getValue(), VT);
1049
1050 if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
Chris Lattner199862b2006-03-16 19:57:50 +00001051 return N = DAG.getGlobalAddress(GV, VT);
Chris Lattnerb606dba2008-04-28 06:44:42 +00001052
1053 if (isa<ConstantPointerNull>(C))
Chris Lattner199862b2006-03-16 19:57:50 +00001054 return N = DAG.getConstant(0, TLI.getPointerTy());
Chris Lattnerb606dba2008-04-28 06:44:42 +00001055
1056 if (ConstantFP *CFP = dyn_cast<ConstantFP>(C))
1057 return N = DAG.getConstantFP(CFP->getValueAPF(), VT);
1058
1059 if (isa<UndefValue>(C)) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001060 if (!isa<VectorType>(VTy))
Chris Lattner23d564c2006-03-19 00:20:20 +00001061 return N = DAG.getNode(ISD::UNDEF, VT);
1062
Dan Gohman7f321562007-06-25 16:23:39 +00001063 // Create a BUILD_VECTOR of undef nodes.
Reid Spencer9d6565a2007-02-15 02:26:10 +00001064 const VectorType *PTy = cast<VectorType>(VTy);
Chris Lattner23d564c2006-03-19 00:20:20 +00001065 unsigned NumElements = PTy->getNumElements();
1066 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
1067
Chris Lattnerbd564bf2006-08-08 02:23:42 +00001068 SmallVector<SDOperand, 8> Ops;
Chris Lattner23d564c2006-03-19 00:20:20 +00001069 Ops.assign(NumElements, DAG.getNode(ISD::UNDEF, PVT));
1070
1071 // Create a VConstant node with generic Vector type.
Dan Gohman7f321562007-06-25 16:23:39 +00001072 MVT::ValueType VT = MVT::getVectorType(PVT, NumElements);
Chris Lattnerb606dba2008-04-28 06:44:42 +00001073 return N = DAG.getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
Chris Lattner199862b2006-03-16 19:57:50 +00001074 }
Chris Lattnerb606dba2008-04-28 06:44:42 +00001075
1076 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
1077 visit(CE->getOpcode(), *CE);
1078 SDOperand N1 = NodeMap[V];
1079 assert(N1.Val && "visit didn't populate the ValueMap!");
1080 return N1;
1081 }
1082
1083 const VectorType *VecTy = cast<VectorType>(VTy);
1084 unsigned NumElements = VecTy->getNumElements();
1085 MVT::ValueType PVT = TLI.getValueType(VecTy->getElementType());
1086
1087 // Now that we know the number and type of the elements, push a
1088 // Constant or ConstantFP node onto the ops list for each element of
1089 // the vector constant.
1090 SmallVector<SDOperand, 8> Ops;
1091 if (ConstantVector *CP = dyn_cast<ConstantVector>(C)) {
1092 for (unsigned i = 0; i != NumElements; ++i)
1093 Ops.push_back(getValue(CP->getOperand(i)));
1094 } else {
1095 assert(isa<ConstantAggregateZero>(C) && "Unknown vector constant!");
1096 SDOperand Op;
1097 if (MVT::isFloatingPoint(PVT))
1098 Op = DAG.getConstantFP(0, PVT);
1099 else
1100 Op = DAG.getConstant(0, PVT);
1101 Ops.assign(NumElements, Op);
1102 }
1103
1104 // Create a BUILD_VECTOR node.
1105 return NodeMap[V] = DAG.getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
Chris Lattner199862b2006-03-16 19:57:50 +00001106 }
1107
Chris Lattnerb606dba2008-04-28 06:44:42 +00001108 // If this is a static alloca, generate it as the frameindex instead of
1109 // computation.
Chris Lattner199862b2006-03-16 19:57:50 +00001110 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1111 std::map<const AllocaInst*, int>::iterator SI =
Chris Lattnerb606dba2008-04-28 06:44:42 +00001112 FuncInfo.StaticAllocaMap.find(AI);
Chris Lattner199862b2006-03-16 19:57:50 +00001113 if (SI != FuncInfo.StaticAllocaMap.end())
1114 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
1115 }
1116
Chris Lattner251db182007-02-25 18:40:32 +00001117 unsigned InReg = FuncInfo.ValueMap[V];
1118 assert(InReg && "Value not in map!");
Chris Lattner199862b2006-03-16 19:57:50 +00001119
Dan Gohman23ce5022008-04-25 18:27:55 +00001120 RegsForValue RFV(TLI, InReg, VTy);
Dan Gohmanb6f5b002007-06-28 23:29:44 +00001121 SDOperand Chain = DAG.getEntryNode();
Dan Gohmanb6f5b002007-06-28 23:29:44 +00001122 return RFV.getCopyFromRegs(DAG, Chain, NULL);
Chris Lattner199862b2006-03-16 19:57:50 +00001123}
1124
1125
Chris Lattner1c08c712005-01-07 07:47:53 +00001126void SelectionDAGLowering::visitRet(ReturnInst &I) {
1127 if (I.getNumOperands() == 0) {
Dan Gohman86e1ebf2008-03-27 19:56:19 +00001128 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getControlRoot()));
Chris Lattner1c08c712005-01-07 07:47:53 +00001129 return;
1130 }
Chris Lattnerb606dba2008-04-28 06:44:42 +00001131
Chris Lattnerbd564bf2006-08-08 02:23:42 +00001132 SmallVector<SDOperand, 8> NewValues;
Dan Gohman86e1ebf2008-03-27 19:56:19 +00001133 NewValues.push_back(getControlRoot());
1134 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
Nate Begemanee625572006-01-27 21:09:22 +00001135 SDOperand RetOp = getValue(I.getOperand(i));
Duncan Sandsb988bac2008-02-11 20:58:28 +00001136 MVT::ValueType VT = RetOp.getValueType();
1137
Evan Cheng8e7d0562006-05-26 23:09:09 +00001138 // FIXME: C calling convention requires the return type to be promoted to
1139 // at least 32-bit. But this is not necessary for non-C calling conventions.
Duncan Sandsb988bac2008-02-11 20:58:28 +00001140 if (MVT::isInteger(VT)) {
1141 MVT::ValueType MinVT = TLI.getRegisterType(MVT::i32);
1142 if (MVT::getSizeInBits(VT) < MVT::getSizeInBits(MinVT))
1143 VT = MinVT;
1144 }
1145
1146 unsigned NumParts = TLI.getNumRegisters(VT);
1147 MVT::ValueType PartVT = TLI.getRegisterType(VT);
1148 SmallVector<SDOperand, 4> Parts(NumParts);
1149 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
1150
1151 const Function *F = I.getParent()->getParent();
1152 if (F->paramHasAttr(0, ParamAttr::SExt))
1153 ExtendKind = ISD::SIGN_EXTEND;
1154 else if (F->paramHasAttr(0, ParamAttr::ZExt))
1155 ExtendKind = ISD::ZERO_EXTEND;
1156
1157 getCopyToParts(DAG, RetOp, &Parts[0], NumParts, PartVT, ExtendKind);
1158
1159 for (unsigned i = 0; i < NumParts; ++i) {
1160 NewValues.push_back(Parts[i]);
Duncan Sands276dcbd2008-03-21 09:14:45 +00001161 NewValues.push_back(DAG.getArgFlags(ISD::ArgFlagsTy()));
Nate Begemanee625572006-01-27 21:09:22 +00001162 }
Chris Lattner1c08c712005-01-07 07:47:53 +00001163 }
Chris Lattnerbd564bf2006-08-08 02:23:42 +00001164 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other,
1165 &NewValues[0], NewValues.size()));
Chris Lattner1c08c712005-01-07 07:47:53 +00001166}
1167
Chris Lattner571e4342006-10-27 21:36:01 +00001168/// ExportFromCurrentBlock - If this condition isn't known to be exported from
1169/// the current basic block, add it to ValueMap now so that we'll get a
1170/// CopyTo/FromReg.
1171void SelectionDAGLowering::ExportFromCurrentBlock(Value *V) {
1172 // No need to export constants.
1173 if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
1174
1175 // Already exported?
1176 if (FuncInfo.isExportedInst(V)) return;
1177
1178 unsigned Reg = FuncInfo.InitializeRegForValue(V);
Dan Gohman86e1ebf2008-03-27 19:56:19 +00001179 CopyValueToVirtualRegister(V, Reg);
Chris Lattner571e4342006-10-27 21:36:01 +00001180}
1181
Chris Lattner8c494ab2006-10-27 23:50:33 +00001182bool SelectionDAGLowering::isExportableFromCurrentBlock(Value *V,
1183 const BasicBlock *FromBB) {
1184 // The operands of the setcc have to be in this block. We don't know
1185 // how to export them from some other block.
1186 if (Instruction *VI = dyn_cast<Instruction>(V)) {
1187 // Can export from current BB.
1188 if (VI->getParent() == FromBB)
1189 return true;
1190
1191 // Is already exported, noop.
1192 return FuncInfo.isExportedInst(V);
1193 }
1194
1195 // If this is an argument, we can export it if the BB is the entry block or
1196 // if it is already exported.
1197 if (isa<Argument>(V)) {
1198 if (FromBB == &FromBB->getParent()->getEntryBlock())
1199 return true;
1200
1201 // Otherwise, can only export this if it is already exported.
1202 return FuncInfo.isExportedInst(V);
1203 }
1204
1205 // Otherwise, constants can always be exported.
1206 return true;
1207}
1208
Chris Lattner6a586c82006-10-29 21:01:20 +00001209static bool InBlock(const Value *V, const BasicBlock *BB) {
1210 if (const Instruction *I = dyn_cast<Instruction>(V))
1211 return I->getParent() == BB;
1212 return true;
1213}
1214
Chris Lattner571e4342006-10-27 21:36:01 +00001215/// FindMergedConditions - If Cond is an expression like
1216void SelectionDAGLowering::FindMergedConditions(Value *Cond,
1217 MachineBasicBlock *TBB,
1218 MachineBasicBlock *FBB,
1219 MachineBasicBlock *CurBB,
1220 unsigned Opc) {
Chris Lattner571e4342006-10-27 21:36:01 +00001221 // If this node is not part of the or/and tree, emit it as a branch.
Reid Spencere4d87aa2006-12-23 06:05:41 +00001222 Instruction *BOp = dyn_cast<Instruction>(Cond);
Chris Lattner571e4342006-10-27 21:36:01 +00001223
Reid Spencere4d87aa2006-12-23 06:05:41 +00001224 if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
1225 (unsigned)BOp->getOpcode() != Opc || !BOp->hasOneUse() ||
Chris Lattner6a586c82006-10-29 21:01:20 +00001226 BOp->getParent() != CurBB->getBasicBlock() ||
1227 !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
1228 !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
Chris Lattner571e4342006-10-27 21:36:01 +00001229 const BasicBlock *BB = CurBB->getBasicBlock();
1230
Reid Spencere4d87aa2006-12-23 06:05:41 +00001231 // If the leaf of the tree is a comparison, merge the condition into
1232 // the caseblock.
1233 if ((isa<ICmpInst>(Cond) || isa<FCmpInst>(Cond)) &&
1234 // The operands of the cmp have to be in this block. We don't know
Chris Lattner5a145f02006-10-29 18:23:37 +00001235 // how to export them from some other block. If this is the first block
1236 // of the sequence, no exporting is needed.
1237 (CurBB == CurMBB ||
1238 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
1239 isExportableFromCurrentBlock(BOp->getOperand(1), BB)))) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00001240 BOp = cast<Instruction>(Cond);
1241 ISD::CondCode Condition;
1242 if (ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
1243 switch (IC->getPredicate()) {
1244 default: assert(0 && "Unknown icmp predicate opcode!");
1245 case ICmpInst::ICMP_EQ: Condition = ISD::SETEQ; break;
1246 case ICmpInst::ICMP_NE: Condition = ISD::SETNE; break;
1247 case ICmpInst::ICMP_SLE: Condition = ISD::SETLE; break;
1248 case ICmpInst::ICMP_ULE: Condition = ISD::SETULE; break;
1249 case ICmpInst::ICMP_SGE: Condition = ISD::SETGE; break;
1250 case ICmpInst::ICMP_UGE: Condition = ISD::SETUGE; break;
1251 case ICmpInst::ICMP_SLT: Condition = ISD::SETLT; break;
1252 case ICmpInst::ICMP_ULT: Condition = ISD::SETULT; break;
1253 case ICmpInst::ICMP_SGT: Condition = ISD::SETGT; break;
1254 case ICmpInst::ICMP_UGT: Condition = ISD::SETUGT; break;
1255 }
1256 } else if (FCmpInst *FC = dyn_cast<FCmpInst>(Cond)) {
1257 ISD::CondCode FPC, FOC;
1258 switch (FC->getPredicate()) {
1259 default: assert(0 && "Unknown fcmp predicate opcode!");
1260 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
1261 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
1262 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
1263 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
1264 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
1265 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
1266 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
1267 case FCmpInst::FCMP_ORD: FOC = ISD::SETEQ; FPC = ISD::SETO; break;
1268 case FCmpInst::FCMP_UNO: FOC = ISD::SETNE; FPC = ISD::SETUO; break;
1269 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
1270 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
1271 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
1272 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
1273 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
1274 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
1275 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
1276 }
1277 if (FiniteOnlyFPMath())
1278 Condition = FOC;
1279 else
1280 Condition = FPC;
1281 } else {
Chris Lattner0da331f2007-02-04 01:31:47 +00001282 Condition = ISD::SETEQ; // silence warning.
Reid Spencere4d87aa2006-12-23 06:05:41 +00001283 assert(0 && "Unknown compare instruction");
Chris Lattner571e4342006-10-27 21:36:01 +00001284 }
1285
Chris Lattner571e4342006-10-27 21:36:01 +00001286 SelectionDAGISel::CaseBlock CB(Condition, BOp->getOperand(0),
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001287 BOp->getOperand(1), NULL, TBB, FBB, CurBB);
Chris Lattner571e4342006-10-27 21:36:01 +00001288 SwitchCases.push_back(CB);
1289 return;
1290 }
1291
1292 // Create a CaseBlock record representing this branch.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001293 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, Cond, ConstantInt::getTrue(),
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001294 NULL, TBB, FBB, CurBB);
Chris Lattner571e4342006-10-27 21:36:01 +00001295 SwitchCases.push_back(CB);
Chris Lattner571e4342006-10-27 21:36:01 +00001296 return;
1297 }
1298
Chris Lattnerd2f9ee92006-10-27 21:54:23 +00001299
1300 // Create TmpBB after CurBB.
Chris Lattner571e4342006-10-27 21:36:01 +00001301 MachineFunction::iterator BBI = CurBB;
1302 MachineBasicBlock *TmpBB = new MachineBasicBlock(CurBB->getBasicBlock());
1303 CurBB->getParent()->getBasicBlockList().insert(++BBI, TmpBB);
1304
Chris Lattnerd2f9ee92006-10-27 21:54:23 +00001305 if (Opc == Instruction::Or) {
1306 // Codegen X | Y as:
1307 // jmp_if_X TBB
1308 // jmp TmpBB
1309 // TmpBB:
1310 // jmp_if_Y TBB
1311 // jmp FBB
1312 //
Chris Lattner571e4342006-10-27 21:36:01 +00001313
Chris Lattnerd2f9ee92006-10-27 21:54:23 +00001314 // Emit the LHS condition.
1315 FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, Opc);
1316
1317 // Emit the RHS condition into TmpBB.
1318 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
1319 } else {
1320 assert(Opc == Instruction::And && "Unknown merge op!");
1321 // Codegen X & Y as:
1322 // jmp_if_X TmpBB
1323 // jmp FBB
1324 // TmpBB:
1325 // jmp_if_Y TBB
1326 // jmp FBB
1327 //
1328 // This requires creation of TmpBB after CurBB.
1329
1330 // Emit the LHS condition.
1331 FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, Opc);
1332
1333 // Emit the RHS condition into TmpBB.
1334 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
1335 }
Chris Lattner571e4342006-10-27 21:36:01 +00001336}
1337
Chris Lattnerdf19f272006-10-31 22:37:42 +00001338/// If the set of cases should be emitted as a series of branches, return true.
1339/// If we should emit this as a bunch of and/or'd together conditions, return
1340/// false.
1341static bool
1342ShouldEmitAsBranches(const std::vector<SelectionDAGISel::CaseBlock> &Cases) {
1343 if (Cases.size() != 2) return true;
1344
Chris Lattner0ccb5002006-10-31 23:06:00 +00001345 // If this is two comparisons of the same values or'd or and'd together, they
1346 // will get folded into a single comparison, so don't emit two blocks.
1347 if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
1348 Cases[0].CmpRHS == Cases[1].CmpRHS) ||
1349 (Cases[0].CmpRHS == Cases[1].CmpLHS &&
1350 Cases[0].CmpLHS == Cases[1].CmpRHS)) {
1351 return false;
1352 }
1353
Chris Lattnerdf19f272006-10-31 22:37:42 +00001354 return true;
1355}
1356
Chris Lattner1c08c712005-01-07 07:47:53 +00001357void SelectionDAGLowering::visitBr(BranchInst &I) {
1358 // Update machine-CFG edges.
1359 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
Chris Lattner1c08c712005-01-07 07:47:53 +00001360
1361 // Figure out which block is immediately after the current one.
1362 MachineBasicBlock *NextBlock = 0;
1363 MachineFunction::iterator BBI = CurMBB;
1364 if (++BBI != CurMBB->getParent()->end())
1365 NextBlock = BBI;
1366
1367 if (I.isUnconditional()) {
1368 // If this is not a fall-through branch, emit the branch.
1369 if (Succ0MBB != NextBlock)
Dan Gohman86e1ebf2008-03-27 19:56:19 +00001370 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getControlRoot(),
Misha Brukmandedf2bd2005-04-22 04:01:18 +00001371 DAG.getBasicBlock(Succ0MBB)));
Chris Lattner1c08c712005-01-07 07:47:53 +00001372
Chris Lattner57ab6592006-10-24 17:57:59 +00001373 // Update machine-CFG edges.
1374 CurMBB->addSuccessor(Succ0MBB);
Chris Lattner57ab6592006-10-24 17:57:59 +00001375 return;
1376 }
1377
1378 // If this condition is one of the special cases we handle, do special stuff
1379 // now.
1380 Value *CondVal = I.getCondition();
Chris Lattner57ab6592006-10-24 17:57:59 +00001381 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
Chris Lattner571e4342006-10-27 21:36:01 +00001382
1383 // If this is a series of conditions that are or'd or and'd together, emit
1384 // this as a sequence of branches instead of setcc's with and/or operations.
1385 // For example, instead of something like:
1386 // cmp A, B
1387 // C = seteq
1388 // cmp D, E
1389 // F = setle
1390 // or C, F
1391 // jnz foo
1392 // Emit:
1393 // cmp A, B
1394 // je foo
1395 // cmp D, E
1396 // jle foo
1397 //
1398 if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
1399 if (BOp->hasOneUse() &&
Chris Lattnerd2f9ee92006-10-27 21:54:23 +00001400 (BOp->getOpcode() == Instruction::And ||
Chris Lattner571e4342006-10-27 21:36:01 +00001401 BOp->getOpcode() == Instruction::Or)) {
1402 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, CurMBB, BOp->getOpcode());
Chris Lattner0ccb5002006-10-31 23:06:00 +00001403 // If the compares in later blocks need to use values not currently
1404 // exported from this block, export them now. This block should always
1405 // be the first entry.
1406 assert(SwitchCases[0].ThisBB == CurMBB && "Unexpected lowering!");
1407
Chris Lattnerdf19f272006-10-31 22:37:42 +00001408 // Allow some cases to be rejected.
1409 if (ShouldEmitAsBranches(SwitchCases)) {
Chris Lattnerdf19f272006-10-31 22:37:42 +00001410 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
1411 ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
1412 ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
1413 }
1414
1415 // Emit the branch for this block.
1416 visitSwitchCase(SwitchCases[0]);
1417 SwitchCases.erase(SwitchCases.begin());
1418 return;
Chris Lattner5a145f02006-10-29 18:23:37 +00001419 }
1420
Chris Lattner0ccb5002006-10-31 23:06:00 +00001421 // Okay, we decided not to do this, remove any inserted MBB's and clear
1422 // SwitchCases.
1423 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
1424 CurMBB->getParent()->getBasicBlockList().erase(SwitchCases[i].ThisBB);
1425
Chris Lattnerdf19f272006-10-31 22:37:42 +00001426 SwitchCases.clear();
Chris Lattner571e4342006-10-27 21:36:01 +00001427 }
1428 }
Chris Lattner24525952006-10-24 18:07:37 +00001429
1430 // Create a CaseBlock record representing this branch.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001431 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(),
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001432 NULL, Succ0MBB, Succ1MBB, CurMBB);
Chris Lattner24525952006-10-24 18:07:37 +00001433 // Use visitSwitchCase to actually insert the fast branch sequence for this
1434 // cond branch.
1435 visitSwitchCase(CB);
Chris Lattner1c08c712005-01-07 07:47:53 +00001436}
1437
Nate Begemanf15485a2006-03-27 01:32:24 +00001438/// visitSwitchCase - Emits the necessary code to represent a single node in
1439/// the binary search tree resulting from lowering a switch instruction.
1440void SelectionDAGLowering::visitSwitchCase(SelectionDAGISel::CaseBlock &CB) {
Chris Lattner57ab6592006-10-24 17:57:59 +00001441 SDOperand Cond;
1442 SDOperand CondLHS = getValue(CB.CmpLHS);
1443
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001444 // Build the setcc now.
1445 if (CB.CmpMHS == NULL) {
1446 // Fold "(X == true)" to X and "(X == false)" to !X to
1447 // handle common cases produced by branch lowering.
1448 if (CB.CmpRHS == ConstantInt::getTrue() && CB.CC == ISD::SETEQ)
1449 Cond = CondLHS;
1450 else if (CB.CmpRHS == ConstantInt::getFalse() && CB.CC == ISD::SETEQ) {
1451 SDOperand True = DAG.getConstant(1, CondLHS.getValueType());
1452 Cond = DAG.getNode(ISD::XOR, CondLHS.getValueType(), CondLHS, True);
1453 } else
1454 Cond = DAG.getSetCC(MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
1455 } else {
1456 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001457
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001458 uint64_t Low = cast<ConstantInt>(CB.CmpLHS)->getSExtValue();
1459 uint64_t High = cast<ConstantInt>(CB.CmpRHS)->getSExtValue();
1460
1461 SDOperand CmpOp = getValue(CB.CmpMHS);
1462 MVT::ValueType VT = CmpOp.getValueType();
1463
1464 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
1465 Cond = DAG.getSetCC(MVT::i1, CmpOp, DAG.getConstant(High, VT), ISD::SETLE);
1466 } else {
1467 SDOperand SUB = DAG.getNode(ISD::SUB, VT, CmpOp, DAG.getConstant(Low, VT));
1468 Cond = DAG.getSetCC(MVT::i1, SUB,
1469 DAG.getConstant(High-Low, VT), ISD::SETULE);
1470 }
1471
1472 }
1473
Nate Begemanf15485a2006-03-27 01:32:24 +00001474 // Set NextBlock to be the MBB immediately after the current one, if any.
1475 // This is used to avoid emitting unnecessary branches to the next block.
1476 MachineBasicBlock *NextBlock = 0;
1477 MachineFunction::iterator BBI = CurMBB;
1478 if (++BBI != CurMBB->getParent()->end())
1479 NextBlock = BBI;
1480
1481 // If the lhs block is the next block, invert the condition so that we can
1482 // fall through to the lhs instead of the rhs block.
Chris Lattner57ab6592006-10-24 17:57:59 +00001483 if (CB.TrueBB == NextBlock) {
1484 std::swap(CB.TrueBB, CB.FalseBB);
Nate Begemanf15485a2006-03-27 01:32:24 +00001485 SDOperand True = DAG.getConstant(1, Cond.getValueType());
1486 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
1487 }
Dan Gohman86e1ebf2008-03-27 19:56:19 +00001488 SDOperand BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, getControlRoot(), Cond,
Chris Lattner57ab6592006-10-24 17:57:59 +00001489 DAG.getBasicBlock(CB.TrueBB));
1490 if (CB.FalseBB == NextBlock)
Nate Begemanf15485a2006-03-27 01:32:24 +00001491 DAG.setRoot(BrCond);
1492 else
1493 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond,
Chris Lattner57ab6592006-10-24 17:57:59 +00001494 DAG.getBasicBlock(CB.FalseBB)));
Nate Begemanf15485a2006-03-27 01:32:24 +00001495 // Update successor info
Chris Lattner57ab6592006-10-24 17:57:59 +00001496 CurMBB->addSuccessor(CB.TrueBB);
1497 CurMBB->addSuccessor(CB.FalseBB);
Nate Begemanf15485a2006-03-27 01:32:24 +00001498}
1499
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001500/// visitJumpTable - Emit JumpTable node in the current MBB
Nate Begeman37efe672006-04-22 18:53:45 +00001501void SelectionDAGLowering::visitJumpTable(SelectionDAGISel::JumpTable &JT) {
Nate Begeman37efe672006-04-22 18:53:45 +00001502 // Emit the code for the jump table
Scott Michelf147a8d2007-04-24 01:24:20 +00001503 assert(JT.Reg != -1U && "Should lower JT Header first!");
Nate Begeman37efe672006-04-22 18:53:45 +00001504 MVT::ValueType PTy = TLI.getPointerTy();
Dan Gohman86e1ebf2008-03-27 19:56:19 +00001505 SDOperand Index = DAG.getCopyFromReg(getControlRoot(), JT.Reg, PTy);
Evan Cheng3d4ce112006-10-30 08:00:44 +00001506 SDOperand Table = DAG.getJumpTable(JT.JTI, PTy);
1507 DAG.setRoot(DAG.getNode(ISD::BR_JT, MVT::Other, Index.getValue(1),
1508 Table, Index));
1509 return;
Nate Begeman37efe672006-04-22 18:53:45 +00001510}
1511
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001512/// visitJumpTableHeader - This function emits necessary code to produce index
1513/// in the JumpTable from switch case.
1514void SelectionDAGLowering::visitJumpTableHeader(SelectionDAGISel::JumpTable &JT,
1515 SelectionDAGISel::JumpTableHeader &JTH) {
1516 // Subtract the lowest switch case value from the value being switched on
1517 // and conditional branch to default mbb if the result is greater than the
1518 // difference between smallest and largest cases.
1519 SDOperand SwitchOp = getValue(JTH.SValue);
1520 MVT::ValueType VT = SwitchOp.getValueType();
1521 SDOperand SUB = DAG.getNode(ISD::SUB, VT, SwitchOp,
1522 DAG.getConstant(JTH.First, VT));
1523
1524 // The SDNode we just created, which holds the value being switched on
1525 // minus the the smallest case value, needs to be copied to a virtual
1526 // register so it can be used as an index into the jump table in a
1527 // subsequent basic block. This value may be smaller or larger than the
1528 // target's pointer type, and therefore require extension or truncating.
Dan Gohman7f321562007-06-25 16:23:39 +00001529 if (MVT::getSizeInBits(VT) > MVT::getSizeInBits(TLI.getPointerTy()))
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001530 SwitchOp = DAG.getNode(ISD::TRUNCATE, TLI.getPointerTy(), SUB);
1531 else
1532 SwitchOp = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(), SUB);
1533
1534 unsigned JumpTableReg = FuncInfo.MakeReg(TLI.getPointerTy());
Dan Gohman86e1ebf2008-03-27 19:56:19 +00001535 SDOperand CopyTo = DAG.getCopyToReg(getControlRoot(), JumpTableReg, SwitchOp);
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001536 JT.Reg = JumpTableReg;
1537
1538 // Emit the range check for the jump table, and branch to the default
1539 // block for the switch statement if the value being switched on exceeds
1540 // the largest case in the switch.
Scott Michel5b8f82e2008-03-10 15:42:14 +00001541 SDOperand CMP = DAG.getSetCC(TLI.getSetCCResultType(SUB), SUB,
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001542 DAG.getConstant(JTH.Last-JTH.First,VT),
1543 ISD::SETUGT);
1544
1545 // Set NextBlock to be the MBB immediately after the current one, if any.
1546 // This is used to avoid emitting unnecessary branches to the next block.
1547 MachineBasicBlock *NextBlock = 0;
1548 MachineFunction::iterator BBI = CurMBB;
1549 if (++BBI != CurMBB->getParent()->end())
1550 NextBlock = BBI;
1551
1552 SDOperand BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, CopyTo, CMP,
1553 DAG.getBasicBlock(JT.Default));
1554
1555 if (JT.MBB == NextBlock)
1556 DAG.setRoot(BrCond);
1557 else
1558 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond,
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001559 DAG.getBasicBlock(JT.MBB)));
1560
1561 return;
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001562}
1563
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001564/// visitBitTestHeader - This function emits necessary code to produce value
1565/// suitable for "bit tests"
1566void SelectionDAGLowering::visitBitTestHeader(SelectionDAGISel::BitTestBlock &B) {
1567 // Subtract the minimum value
1568 SDOperand SwitchOp = getValue(B.SValue);
1569 MVT::ValueType VT = SwitchOp.getValueType();
1570 SDOperand SUB = DAG.getNode(ISD::SUB, VT, SwitchOp,
1571 DAG.getConstant(B.First, VT));
1572
1573 // Check range
Scott Michel5b8f82e2008-03-10 15:42:14 +00001574 SDOperand RangeCmp = DAG.getSetCC(TLI.getSetCCResultType(SUB), SUB,
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001575 DAG.getConstant(B.Range, VT),
1576 ISD::SETUGT);
1577
1578 SDOperand ShiftOp;
Dan Gohman7f321562007-06-25 16:23:39 +00001579 if (MVT::getSizeInBits(VT) > MVT::getSizeInBits(TLI.getShiftAmountTy()))
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001580 ShiftOp = DAG.getNode(ISD::TRUNCATE, TLI.getShiftAmountTy(), SUB);
1581 else
1582 ShiftOp = DAG.getNode(ISD::ZERO_EXTEND, TLI.getShiftAmountTy(), SUB);
1583
1584 // Make desired shift
1585 SDOperand SwitchVal = DAG.getNode(ISD::SHL, TLI.getPointerTy(),
1586 DAG.getConstant(1, TLI.getPointerTy()),
1587 ShiftOp);
1588
1589 unsigned SwitchReg = FuncInfo.MakeReg(TLI.getPointerTy());
Dan Gohman86e1ebf2008-03-27 19:56:19 +00001590 SDOperand CopyTo = DAG.getCopyToReg(getControlRoot(), SwitchReg, SwitchVal);
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001591 B.Reg = SwitchReg;
1592
1593 SDOperand BrRange = DAG.getNode(ISD::BRCOND, MVT::Other, CopyTo, RangeCmp,
1594 DAG.getBasicBlock(B.Default));
1595
1596 // Set NextBlock to be the MBB immediately after the current one, if any.
1597 // This is used to avoid emitting unnecessary branches to the next block.
1598 MachineBasicBlock *NextBlock = 0;
1599 MachineFunction::iterator BBI = CurMBB;
1600 if (++BBI != CurMBB->getParent()->end())
1601 NextBlock = BBI;
1602
1603 MachineBasicBlock* MBB = B.Cases[0].ThisBB;
1604 if (MBB == NextBlock)
1605 DAG.setRoot(BrRange);
1606 else
1607 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, CopyTo,
1608 DAG.getBasicBlock(MBB)));
1609
1610 CurMBB->addSuccessor(B.Default);
1611 CurMBB->addSuccessor(MBB);
1612
1613 return;
1614}
1615
1616/// visitBitTestCase - this function produces one "bit test"
1617void SelectionDAGLowering::visitBitTestCase(MachineBasicBlock* NextMBB,
1618 unsigned Reg,
1619 SelectionDAGISel::BitTestCase &B) {
1620 // Emit bit tests and jumps
Dan Gohman86e1ebf2008-03-27 19:56:19 +00001621 SDOperand SwitchVal = DAG.getCopyFromReg(getControlRoot(), Reg, TLI.getPointerTy());
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001622
1623 SDOperand AndOp = DAG.getNode(ISD::AND, TLI.getPointerTy(),
1624 SwitchVal,
1625 DAG.getConstant(B.Mask,
1626 TLI.getPointerTy()));
Scott Michel5b8f82e2008-03-10 15:42:14 +00001627 SDOperand AndCmp = DAG.getSetCC(TLI.getSetCCResultType(AndOp), AndOp,
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001628 DAG.getConstant(0, TLI.getPointerTy()),
1629 ISD::SETNE);
Dan Gohman86e1ebf2008-03-27 19:56:19 +00001630 SDOperand BrAnd = DAG.getNode(ISD::BRCOND, MVT::Other, getControlRoot(),
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001631 AndCmp, DAG.getBasicBlock(B.TargetBB));
1632
1633 // Set NextBlock to be the MBB immediately after the current one, if any.
1634 // This is used to avoid emitting unnecessary branches to the next block.
1635 MachineBasicBlock *NextBlock = 0;
1636 MachineFunction::iterator BBI = CurMBB;
1637 if (++BBI != CurMBB->getParent()->end())
1638 NextBlock = BBI;
1639
1640 if (NextMBB == NextBlock)
1641 DAG.setRoot(BrAnd);
1642 else
1643 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrAnd,
1644 DAG.getBasicBlock(NextMBB)));
1645
1646 CurMBB->addSuccessor(B.TargetBB);
1647 CurMBB->addSuccessor(NextMBB);
1648
1649 return;
1650}
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00001651
Jim Laskeyb180aa12007-02-21 22:53:45 +00001652void SelectionDAGLowering::visitInvoke(InvokeInst &I) {
1653 // Retrieve successors.
1654 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
Duncan Sandsf19f6bb2007-06-13 05:51:31 +00001655 MachineBasicBlock *LandingPad = FuncInfo.MBBMap[I.getSuccessor(1)];
Duncan Sands9fac0b52007-06-06 10:05:18 +00001656
Duncan Sandsfd7b3262007-12-17 18:08:19 +00001657 if (isa<InlineAsm>(I.getCalledValue()))
1658 visitInlineAsm(&I);
1659 else
Duncan Sands6f74b482007-12-19 09:48:52 +00001660 LowerCallTo(&I, getValue(I.getOperand(0)), false, LandingPad);
Duncan Sands9fac0b52007-06-06 10:05:18 +00001661
Duncan Sandsf19f6bb2007-06-13 05:51:31 +00001662 // If the value of the invoke is used outside of its defining block, make it
1663 // available as a virtual register.
1664 if (!I.use_empty()) {
1665 DenseMap<const Value*, unsigned>::iterator VMI = FuncInfo.ValueMap.find(&I);
1666 if (VMI != FuncInfo.ValueMap.end())
Dan Gohman86e1ebf2008-03-27 19:56:19 +00001667 CopyValueToVirtualRegister(&I, VMI->second);
Jim Laskey183f47f2007-02-25 21:43:59 +00001668 }
Duncan Sandsf19f6bb2007-06-13 05:51:31 +00001669
1670 // Drop into normal successor.
Dan Gohman86e1ebf2008-03-27 19:56:19 +00001671 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getControlRoot(),
Duncan Sandsf19f6bb2007-06-13 05:51:31 +00001672 DAG.getBasicBlock(Return)));
1673
1674 // Update successor info
1675 CurMBB->addSuccessor(Return);
1676 CurMBB->addSuccessor(LandingPad);
Jim Laskeyb180aa12007-02-21 22:53:45 +00001677}
1678
1679void SelectionDAGLowering::visitUnwind(UnwindInst &I) {
1680}
1681
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001682/// handleSmallSwitchCaseRange - Emit a series of specific tests (suitable for
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001683/// small case ranges).
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001684bool SelectionDAGLowering::handleSmallSwitchRange(CaseRec& CR,
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001685 CaseRecVector& WorkList,
1686 Value* SV,
1687 MachineBasicBlock* Default) {
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001688 Case& BackCase = *(CR.Range.second-1);
1689
1690 // Size is the number of Cases represented by this range.
1691 unsigned Size = CR.Range.second - CR.Range.first;
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001692 if (Size > 3)
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001693 return false;
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001694
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001695 // Get the MachineFunction which holds the current MBB. This is used when
1696 // inserting any additional MBBs necessary to represent the switch.
1697 MachineFunction *CurMF = CurMBB->getParent();
1698
1699 // Figure out which block is immediately after the current one.
1700 MachineBasicBlock *NextBlock = 0;
1701 MachineFunction::iterator BBI = CR.CaseBB;
1702
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001703 if (++BBI != CurMBB->getParent()->end())
1704 NextBlock = BBI;
1705
1706 // TODO: If any two of the cases has the same destination, and if one value
1707 // is the same as the other, but has one bit unset that the other has set,
1708 // use bit manipulation to do two compares at once. For example:
1709 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
1710
1711 // Rearrange the case blocks so that the last one falls through if possible.
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001712 if (NextBlock && Default != NextBlock && BackCase.BB != NextBlock) {
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001713 // The last case block won't fall through into 'NextBlock' if we emit the
1714 // branches in this order. See if rearranging a case value would help.
1715 for (CaseItr I = CR.Range.first, E = CR.Range.second-1; I != E; ++I) {
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001716 if (I->BB == NextBlock) {
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001717 std::swap(*I, BackCase);
1718 break;
1719 }
1720 }
1721 }
1722
1723 // Create a CaseBlock record representing a conditional branch to
1724 // the Case's target mbb if the value being switched on SV is equal
1725 // to C.
1726 MachineBasicBlock *CurBlock = CR.CaseBB;
1727 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I) {
1728 MachineBasicBlock *FallThrough;
1729 if (I != E-1) {
1730 FallThrough = new MachineBasicBlock(CurBlock->getBasicBlock());
1731 CurMF->getBasicBlockList().insert(BBI, FallThrough);
1732 } else {
1733 // If the last case doesn't match, go to the default block.
1734 FallThrough = Default;
1735 }
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001736
1737 Value *RHS, *LHS, *MHS;
1738 ISD::CondCode CC;
1739 if (I->High == I->Low) {
1740 // This is just small small case range :) containing exactly 1 case
1741 CC = ISD::SETEQ;
1742 LHS = SV; RHS = I->High; MHS = NULL;
1743 } else {
1744 CC = ISD::SETLE;
1745 LHS = I->Low; MHS = SV; RHS = I->High;
1746 }
1747 SelectionDAGISel::CaseBlock CB(CC, LHS, RHS, MHS,
1748 I->BB, FallThrough, CurBlock);
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001749
1750 // If emitting the first comparison, just call visitSwitchCase to emit the
1751 // code into the current block. Otherwise, push the CaseBlock onto the
1752 // vector to be later processed by SDISel, and insert the node's MBB
1753 // before the next MBB.
1754 if (CurBlock == CurMBB)
1755 visitSwitchCase(CB);
1756 else
1757 SwitchCases.push_back(CB);
1758
1759 CurBlock = FallThrough;
1760 }
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001761
1762 return true;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001763}
1764
Anton Korobeynikov7294b582007-05-09 20:07:08 +00001765static inline bool areJTsAllowed(const TargetLowering &TLI) {
1766 return (TLI.isOperationLegal(ISD::BR_JT, MVT::Other) ||
1767 TLI.isOperationLegal(ISD::BRIND, MVT::Other));
1768}
1769
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001770/// handleJTSwitchCase - Emit jumptable for current switch case range
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001771bool SelectionDAGLowering::handleJTSwitchCase(CaseRec& CR,
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001772 CaseRecVector& WorkList,
1773 Value* SV,
1774 MachineBasicBlock* Default) {
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001775 Case& FrontCase = *CR.Range.first;
1776 Case& BackCase = *(CR.Range.second-1);
1777
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001778 int64_t First = cast<ConstantInt>(FrontCase.Low)->getSExtValue();
1779 int64_t Last = cast<ConstantInt>(BackCase.High)->getSExtValue();
1780
1781 uint64_t TSize = 0;
1782 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1783 I!=E; ++I)
1784 TSize += I->size();
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001785
Anton Korobeynikov7294b582007-05-09 20:07:08 +00001786 if (!areJTsAllowed(TLI) || TSize <= 3)
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001787 return false;
1788
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001789 double Density = (double)TSize / (double)((Last - First) + 1ULL);
1790 if (Density < 0.4)
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001791 return false;
1792
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001793 DOUT << "Lowering jump table\n"
1794 << "First entry: " << First << ". Last entry: " << Last << "\n"
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001795 << "Size: " << TSize << ". Density: " << Density << "\n\n";
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001796
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001797 // Get the MachineFunction which holds the current MBB. This is used when
1798 // inserting any additional MBBs necessary to represent the switch.
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001799 MachineFunction *CurMF = CurMBB->getParent();
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001800
1801 // Figure out which block is immediately after the current one.
1802 MachineBasicBlock *NextBlock = 0;
1803 MachineFunction::iterator BBI = CR.CaseBB;
1804
1805 if (++BBI != CurMBB->getParent()->end())
1806 NextBlock = BBI;
1807
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001808 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1809
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001810 // Create a new basic block to hold the code for loading the address
1811 // of the jump table, and jumping to it. Update successor information;
1812 // we will either branch to the default case for the switch, or the jump
1813 // table.
1814 MachineBasicBlock *JumpTableBB = new MachineBasicBlock(LLVMBB);
1815 CurMF->getBasicBlockList().insert(BBI, JumpTableBB);
1816 CR.CaseBB->addSuccessor(Default);
1817 CR.CaseBB->addSuccessor(JumpTableBB);
1818
1819 // Build a vector of destination BBs, corresponding to each target
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001820 // of the jump table. If the value of the jump table slot corresponds to
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001821 // a case statement, push the case's BB onto the vector, otherwise, push
1822 // the default BB.
1823 std::vector<MachineBasicBlock*> DestBBs;
1824 int64_t TEI = First;
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001825 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++TEI) {
1826 int64_t Low = cast<ConstantInt>(I->Low)->getSExtValue();
1827 int64_t High = cast<ConstantInt>(I->High)->getSExtValue();
1828
1829 if ((Low <= TEI) && (TEI <= High)) {
1830 DestBBs.push_back(I->BB);
1831 if (TEI==High)
1832 ++I;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001833 } else {
1834 DestBBs.push_back(Default);
1835 }
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001836 }
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001837
1838 // Update successor info. Add one edge to each unique successor.
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001839 BitVector SuccsHandled(CR.CaseBB->getParent()->getNumBlockIDs());
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001840 for (std::vector<MachineBasicBlock*>::iterator I = DestBBs.begin(),
1841 E = DestBBs.end(); I != E; ++I) {
1842 if (!SuccsHandled[(*I)->getNumber()]) {
1843 SuccsHandled[(*I)->getNumber()] = true;
1844 JumpTableBB->addSuccessor(*I);
1845 }
1846 }
1847
1848 // Create a jump table index for this jump table, or return an existing
1849 // one.
1850 unsigned JTI = CurMF->getJumpTableInfo()->getJumpTableIndex(DestBBs);
1851
1852 // Set the jump table information so that we can codegen it as a second
1853 // MachineBasicBlock
Scott Michelf147a8d2007-04-24 01:24:20 +00001854 SelectionDAGISel::JumpTable JT(-1U, JTI, JumpTableBB, Default);
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001855 SelectionDAGISel::JumpTableHeader JTH(First, Last, SV, CR.CaseBB,
1856 (CR.CaseBB == CurMBB));
1857 if (CR.CaseBB == CurMBB)
1858 visitJumpTableHeader(JT, JTH);
1859
1860 JTCases.push_back(SelectionDAGISel::JumpTableBlock(JTH, JT));
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001861
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001862 return true;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001863}
1864
1865/// handleBTSplitSwitchCase - emit comparison and split binary search tree into
1866/// 2 subtrees.
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001867bool SelectionDAGLowering::handleBTSplitSwitchCase(CaseRec& CR,
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001868 CaseRecVector& WorkList,
1869 Value* SV,
1870 MachineBasicBlock* Default) {
1871 // Get the MachineFunction which holds the current MBB. This is used when
1872 // inserting any additional MBBs necessary to represent the switch.
1873 MachineFunction *CurMF = CurMBB->getParent();
1874
1875 // Figure out which block is immediately after the current one.
1876 MachineBasicBlock *NextBlock = 0;
1877 MachineFunction::iterator BBI = CR.CaseBB;
1878
1879 if (++BBI != CurMBB->getParent()->end())
1880 NextBlock = BBI;
1881
1882 Case& FrontCase = *CR.Range.first;
1883 Case& BackCase = *(CR.Range.second-1);
1884 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1885
1886 // Size is the number of Cases represented by this range.
1887 unsigned Size = CR.Range.second - CR.Range.first;
1888
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001889 int64_t First = cast<ConstantInt>(FrontCase.Low)->getSExtValue();
1890 int64_t Last = cast<ConstantInt>(BackCase.High)->getSExtValue();
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001891 double FMetric = 0;
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001892 CaseItr Pivot = CR.Range.first + Size/2;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001893
1894 // Select optimal pivot, maximizing sum density of LHS and RHS. This will
1895 // (heuristically) allow us to emit JumpTable's later.
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001896 uint64_t TSize = 0;
1897 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1898 I!=E; ++I)
1899 TSize += I->size();
1900
1901 uint64_t LSize = FrontCase.size();
1902 uint64_t RSize = TSize-LSize;
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001903 DOUT << "Selecting best pivot: \n"
1904 << "First: " << First << ", Last: " << Last <<"\n"
1905 << "LSize: " << LSize << ", RSize: " << RSize << "\n";
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001906 for (CaseItr I = CR.Range.first, J=I+1, E = CR.Range.second;
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001907 J!=E; ++I, ++J) {
1908 int64_t LEnd = cast<ConstantInt>(I->High)->getSExtValue();
1909 int64_t RBegin = cast<ConstantInt>(J->Low)->getSExtValue();
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001910 assert((RBegin-LEnd>=1) && "Invalid case distance");
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001911 double LDensity = (double)LSize / (double)((LEnd - First) + 1ULL);
1912 double RDensity = (double)RSize / (double)((Last - RBegin) + 1ULL);
Anton Korobeynikov54e2b142007-04-09 21:57:03 +00001913 double Metric = Log2_64(RBegin-LEnd)*(LDensity+RDensity);
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001914 // Should always split in some non-trivial place
1915 DOUT <<"=>Step\n"
1916 << "LEnd: " << LEnd << ", RBegin: " << RBegin << "\n"
1917 << "LDensity: " << LDensity << ", RDensity: " << RDensity << "\n"
1918 << "Metric: " << Metric << "\n";
1919 if (FMetric < Metric) {
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001920 Pivot = J;
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001921 FMetric = Metric;
1922 DOUT << "Current metric set to: " << FMetric << "\n";
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001923 }
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001924
1925 LSize += J->size();
1926 RSize -= J->size();
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001927 }
Anton Korobeynikov7294b582007-05-09 20:07:08 +00001928 if (areJTsAllowed(TLI)) {
1929 // If our case is dense we *really* should handle it earlier!
1930 assert((FMetric > 0) && "Should handle dense range earlier!");
1931 } else {
1932 Pivot = CR.Range.first + Size/2;
1933 }
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001934
1935 CaseRange LHSR(CR.Range.first, Pivot);
1936 CaseRange RHSR(Pivot, CR.Range.second);
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001937 Constant *C = Pivot->Low;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001938 MachineBasicBlock *FalseBB = 0, *TrueBB = 0;
1939
1940 // We know that we branch to the LHS if the Value being switched on is
1941 // less than the Pivot value, C. We use this to optimize our binary
1942 // tree a bit, by recognizing that if SV is greater than or equal to the
1943 // LHS's Case Value, and that Case Value is exactly one less than the
1944 // Pivot's Value, then we can branch directly to the LHS's Target,
1945 // rather than creating a leaf node for it.
1946 if ((LHSR.second - LHSR.first) == 1 &&
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001947 LHSR.first->High == CR.GE &&
1948 cast<ConstantInt>(C)->getSExtValue() ==
1949 (cast<ConstantInt>(CR.GE)->getSExtValue() + 1LL)) {
1950 TrueBB = LHSR.first->BB;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001951 } else {
1952 TrueBB = new MachineBasicBlock(LLVMBB);
1953 CurMF->getBasicBlockList().insert(BBI, TrueBB);
1954 WorkList.push_back(CaseRec(TrueBB, C, CR.GE, LHSR));
1955 }
1956
1957 // Similar to the optimization above, if the Value being switched on is
1958 // known to be less than the Constant CR.LT, and the current Case Value
1959 // is CR.LT - 1, then we can branch directly to the target block for
1960 // the current Case Value, rather than emitting a RHS leaf node for it.
1961 if ((RHSR.second - RHSR.first) == 1 && CR.LT &&
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001962 cast<ConstantInt>(RHSR.first->Low)->getSExtValue() ==
1963 (cast<ConstantInt>(CR.LT)->getSExtValue() - 1LL)) {
1964 FalseBB = RHSR.first->BB;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001965 } else {
1966 FalseBB = new MachineBasicBlock(LLVMBB);
1967 CurMF->getBasicBlockList().insert(BBI, FalseBB);
1968 WorkList.push_back(CaseRec(FalseBB,CR.LT,C,RHSR));
1969 }
1970
1971 // Create a CaseBlock record representing a conditional branch to
1972 // the LHS node if the value being switched on SV is less than C.
1973 // Otherwise, branch to LHS.
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00001974 SelectionDAGISel::CaseBlock CB(ISD::SETLT, SV, C, NULL,
1975 TrueBB, FalseBB, CR.CaseBB);
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001976
1977 if (CR.CaseBB == CurMBB)
1978 visitSwitchCase(CB);
1979 else
1980 SwitchCases.push_back(CB);
Anton Korobeynikovdd433212007-03-27 12:05:48 +00001981
1982 return true;
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00001983}
1984
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001985/// handleBitTestsSwitchCase - if current case range has few destination and
1986/// range span less, than machine word bitwidth, encode case range into series
1987/// of masks and emit bit tests with these masks.
1988bool SelectionDAGLowering::handleBitTestsSwitchCase(CaseRec& CR,
1989 CaseRecVector& WorkList,
1990 Value* SV,
Chris Lattner3ff98172007-04-14 02:26:56 +00001991 MachineBasicBlock* Default){
Dan Gohmanb55757e2007-05-18 17:52:13 +00001992 unsigned IntPtrBits = MVT::getSizeInBits(TLI.getPointerTy());
Anton Korobeynikov4198c582007-04-09 12:31:58 +00001993
1994 Case& FrontCase = *CR.Range.first;
1995 Case& BackCase = *(CR.Range.second-1);
1996
1997 // Get the MachineFunction which holds the current MBB. This is used when
1998 // inserting any additional MBBs necessary to represent the switch.
1999 MachineFunction *CurMF = CurMBB->getParent();
2000
2001 unsigned numCmps = 0;
2002 for (CaseItr I = CR.Range.first, E = CR.Range.second;
2003 I!=E; ++I) {
2004 // Single case counts one, case range - two.
2005 if (I->Low == I->High)
2006 numCmps +=1;
2007 else
2008 numCmps +=2;
2009 }
2010
2011 // Count unique destinations
2012 SmallSet<MachineBasicBlock*, 4> Dests;
2013 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
2014 Dests.insert(I->BB);
2015 if (Dests.size() > 3)
2016 // Don't bother the code below, if there are too much unique destinations
2017 return false;
2018 }
2019 DOUT << "Total number of unique destinations: " << Dests.size() << "\n"
2020 << "Total number of comparisons: " << numCmps << "\n";
2021
2022 // Compute span of values.
2023 Constant* minValue = FrontCase.Low;
2024 Constant* maxValue = BackCase.High;
2025 uint64_t range = cast<ConstantInt>(maxValue)->getSExtValue() -
2026 cast<ConstantInt>(minValue)->getSExtValue();
2027 DOUT << "Compare range: " << range << "\n"
2028 << "Low bound: " << cast<ConstantInt>(minValue)->getSExtValue() << "\n"
2029 << "High bound: " << cast<ConstantInt>(maxValue)->getSExtValue() << "\n";
2030
Anton Korobeynikovab8fd402007-04-26 20:44:04 +00002031 if (range>=IntPtrBits ||
Anton Korobeynikov4198c582007-04-09 12:31:58 +00002032 (!(Dests.size() == 1 && numCmps >= 3) &&
2033 !(Dests.size() == 2 && numCmps >= 5) &&
2034 !(Dests.size() >= 3 && numCmps >= 6)))
2035 return false;
2036
2037 DOUT << "Emitting bit tests\n";
2038 int64_t lowBound = 0;
2039
2040 // Optimize the case where all the case values fit in a
2041 // word without having to subtract minValue. In this case,
2042 // we can optimize away the subtraction.
2043 if (cast<ConstantInt>(minValue)->getSExtValue() >= 0 &&
Anton Korobeynikove01017b2007-04-14 13:25:55 +00002044 cast<ConstantInt>(maxValue)->getSExtValue() < IntPtrBits) {
Anton Korobeynikov4198c582007-04-09 12:31:58 +00002045 range = cast<ConstantInt>(maxValue)->getSExtValue();
2046 } else {
2047 lowBound = cast<ConstantInt>(minValue)->getSExtValue();
2048 }
2049
2050 CaseBitsVector CasesBits;
2051 unsigned i, count = 0;
2052
2053 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
2054 MachineBasicBlock* Dest = I->BB;
2055 for (i = 0; i < count; ++i)
2056 if (Dest == CasesBits[i].BB)
2057 break;
2058
2059 if (i == count) {
2060 assert((count < 3) && "Too much destinations to test!");
2061 CasesBits.push_back(CaseBits(0, Dest, 0));
2062 count++;
2063 }
2064
2065 uint64_t lo = cast<ConstantInt>(I->Low)->getSExtValue() - lowBound;
2066 uint64_t hi = cast<ConstantInt>(I->High)->getSExtValue() - lowBound;
2067
2068 for (uint64_t j = lo; j <= hi; j++) {
Anton Korobeynikove01017b2007-04-14 13:25:55 +00002069 CasesBits[i].Mask |= 1ULL << j;
Anton Korobeynikov4198c582007-04-09 12:31:58 +00002070 CasesBits[i].Bits++;
2071 }
2072
2073 }
2074 std::sort(CasesBits.begin(), CasesBits.end(), CaseBitsCmp());
2075
2076 SelectionDAGISel::BitTestInfo BTC;
2077
2078 // Figure out which block is immediately after the current one.
2079 MachineFunction::iterator BBI = CR.CaseBB;
2080 ++BBI;
2081
2082 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
2083
2084 DOUT << "Cases:\n";
2085 for (unsigned i = 0, e = CasesBits.size(); i!=e; ++i) {
2086 DOUT << "Mask: " << CasesBits[i].Mask << ", Bits: " << CasesBits[i].Bits
2087 << ", BB: " << CasesBits[i].BB << "\n";
2088
2089 MachineBasicBlock *CaseBB = new MachineBasicBlock(LLVMBB);
2090 CurMF->getBasicBlockList().insert(BBI, CaseBB);
2091 BTC.push_back(SelectionDAGISel::BitTestCase(CasesBits[i].Mask,
2092 CaseBB,
2093 CasesBits[i].BB));
2094 }
2095
2096 SelectionDAGISel::BitTestBlock BTB(lowBound, range, SV,
Jeff Cohenefc36622007-04-09 14:32:59 +00002097 -1U, (CR.CaseBB == CurMBB),
Anton Korobeynikov4198c582007-04-09 12:31:58 +00002098 CR.CaseBB, Default, BTC);
2099
2100 if (CR.CaseBB == CurMBB)
2101 visitBitTestHeader(BTB);
2102
2103 BitTestCases.push_back(BTB);
2104
2105 return true;
2106}
2107
2108
Dan Gohman86e1ebf2008-03-27 19:56:19 +00002109/// Clusterify - Transform simple list of Cases into list of CaseRange's
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002110unsigned SelectionDAGLowering::Clusterify(CaseVector& Cases,
2111 const SwitchInst& SI) {
2112 unsigned numCmps = 0;
2113
2114 // Start with "simple" cases
2115 for (unsigned i = 1; i < SI.getNumSuccessors(); ++i) {
2116 MachineBasicBlock *SMBB = FuncInfo.MBBMap[SI.getSuccessor(i)];
2117 Cases.push_back(Case(SI.getSuccessorValue(i),
2118 SI.getSuccessorValue(i),
2119 SMBB));
2120 }
Chris Lattnerb3d9cdb2007-11-27 06:14:32 +00002121 std::sort(Cases.begin(), Cases.end(), CaseCmp());
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002122
2123 // Merge case into clusters
2124 if (Cases.size()>=2)
David Greenea2a48852007-06-29 03:42:23 +00002125 // Must recompute end() each iteration because it may be
2126 // invalidated by erase if we hold on to it
Chris Lattner27a6c732007-11-24 07:07:01 +00002127 for (CaseItr I=Cases.begin(), J=++(Cases.begin()); J!=Cases.end(); ) {
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002128 int64_t nextValue = cast<ConstantInt>(J->Low)->getSExtValue();
2129 int64_t currentValue = cast<ConstantInt>(I->High)->getSExtValue();
2130 MachineBasicBlock* nextBB = J->BB;
2131 MachineBasicBlock* currentBB = I->BB;
2132
2133 // If the two neighboring cases go to the same destination, merge them
2134 // into a single case.
2135 if ((nextValue-currentValue==1) && (currentBB == nextBB)) {
2136 I->High = J->High;
2137 J = Cases.erase(J);
2138 } else {
2139 I = J++;
2140 }
2141 }
2142
2143 for (CaseItr I=Cases.begin(), E=Cases.end(); I!=E; ++I, ++numCmps) {
2144 if (I->Low != I->High)
2145 // A range counts double, since it requires two compares.
2146 ++numCmps;
2147 }
2148
2149 return numCmps;
2150}
2151
2152void SelectionDAGLowering::visitSwitch(SwitchInst &SI) {
Nate Begemanf15485a2006-03-27 01:32:24 +00002153 // Figure out which block is immediately after the current one.
2154 MachineBasicBlock *NextBlock = 0;
2155 MachineFunction::iterator BBI = CurMBB;
Bill Wendlingc70ddad2006-10-19 21:46:38 +00002156
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002157 MachineBasicBlock *Default = FuncInfo.MBBMap[SI.getDefaultDest()];
Chris Lattnerd2c1d222006-10-22 21:36:53 +00002158
Nate Begemanf15485a2006-03-27 01:32:24 +00002159 // If there is only the default destination, branch to it if it is not the
2160 // next basic block. Otherwise, just fall through.
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002161 if (SI.getNumOperands() == 2) {
Nate Begemanf15485a2006-03-27 01:32:24 +00002162 // Update machine-CFG edges.
Bill Wendlingc70ddad2006-10-19 21:46:38 +00002163
Nate Begemanf15485a2006-03-27 01:32:24 +00002164 // If this is not a fall-through branch, emit the branch.
Chris Lattnerd2c1d222006-10-22 21:36:53 +00002165 if (Default != NextBlock)
Dan Gohman86e1ebf2008-03-27 19:56:19 +00002166 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getControlRoot(),
Chris Lattnerd2c1d222006-10-22 21:36:53 +00002167 DAG.getBasicBlock(Default)));
Bill Wendlingc70ddad2006-10-19 21:46:38 +00002168
Chris Lattnerd2c1d222006-10-22 21:36:53 +00002169 CurMBB->addSuccessor(Default);
Nate Begemanf15485a2006-03-27 01:32:24 +00002170 return;
2171 }
2172
2173 // If there are any non-default case statements, create a vector of Cases
2174 // representing each one, and sort the vector so that we can efficiently
2175 // create a binary search tree from them.
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002176 CaseVector Cases;
2177 unsigned numCmps = Clusterify(Cases, SI);
2178 DOUT << "Clusterify finished. Total clusters: " << Cases.size()
2179 << ". Total compares: " << numCmps << "\n";
Bill Wendlingc70ddad2006-10-19 21:46:38 +00002180
Nate Begemanf15485a2006-03-27 01:32:24 +00002181 // Get the Value to be switched on and default basic blocks, which will be
2182 // inserted into CaseBlock records, representing basic blocks in the binary
2183 // search tree.
Anton Korobeynikov5502bf62007-04-04 21:14:49 +00002184 Value *SV = SI.getOperand(0);
Nate Begeman37efe672006-04-22 18:53:45 +00002185
Nate Begemanf15485a2006-03-27 01:32:24 +00002186 // Push the initial CaseRec onto the worklist
Anton Korobeynikovb17b08d2007-03-27 11:29:11 +00002187 CaseRecVector WorkList;
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00002188 WorkList.push_back(CaseRec(CurMBB,0,0,CaseRange(Cases.begin(),Cases.end())));
2189
2190 while (!WorkList.empty()) {
Nate Begemanf15485a2006-03-27 01:32:24 +00002191 // Grab a record representing a case range to process off the worklist
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00002192 CaseRec CR = WorkList.back();
2193 WorkList.pop_back();
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00002194
Anton Korobeynikov4198c582007-04-09 12:31:58 +00002195 if (handleBitTestsSwitchCase(CR, WorkList, SV, Default))
2196 continue;
2197
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00002198 // If the range has few cases (two or less) emit a series of specific
2199 // tests.
Anton Korobeynikovdd433212007-03-27 12:05:48 +00002200 if (handleSmallSwitchRange(CR, WorkList, SV, Default))
2201 continue;
2202
Anton Korobeynikov4198c582007-04-09 12:31:58 +00002203 // If the switch has more than 5 blocks, and at least 40% dense, and the
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00002204 // target supports indirect branches, then emit a jump table rather than
2205 // lowering the switch to a binary tree of conditional branches.
Anton Korobeynikovdd433212007-03-27 12:05:48 +00002206 if (handleJTSwitchCase(CR, WorkList, SV, Default))
2207 continue;
2208
2209 // Emit binary tree. We need to pick a pivot, and push left and right ranges
2210 // onto the worklist. Leafs are handled via handleSmallSwitchRange() call.
2211 handleBTSplitSwitchCase(CR, WorkList, SV, Default);
Nate Begemanf15485a2006-03-27 01:32:24 +00002212 }
2213}
2214
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00002215
Chris Lattnerb9fccc42005-04-02 05:04:50 +00002216void SelectionDAGLowering::visitSub(User &I) {
2217 // -0.0 - X --> fneg
Reid Spencer24d6da52007-01-21 00:29:26 +00002218 const Type *Ty = I.getType();
Reid Spencer9d6565a2007-02-15 02:26:10 +00002219 if (isa<VectorType>(Ty)) {
Dan Gohman7f321562007-06-25 16:23:39 +00002220 if (ConstantVector *CV = dyn_cast<ConstantVector>(I.getOperand(0))) {
2221 const VectorType *DestTy = cast<VectorType>(I.getType());
2222 const Type *ElTy = DestTy->getElementType();
Evan Chengc45453f2007-06-29 21:44:35 +00002223 if (ElTy->isFloatingPoint()) {
2224 unsigned VL = DestTy->getNumElements();
Dale Johannesen9e3d3ab2007-09-14 22:26:36 +00002225 std::vector<Constant*> NZ(VL, ConstantFP::getNegativeZero(ElTy));
Evan Chengc45453f2007-06-29 21:44:35 +00002226 Constant *CNZ = ConstantVector::get(&NZ[0], NZ.size());
2227 if (CV == CNZ) {
2228 SDOperand Op2 = getValue(I.getOperand(1));
2229 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
2230 return;
2231 }
Dan Gohman7f321562007-06-25 16:23:39 +00002232 }
2233 }
2234 }
2235 if (Ty->isFloatingPoint()) {
Chris Lattner01b3d732005-09-28 22:28:18 +00002236 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
Dale Johannesen9e3d3ab2007-09-14 22:26:36 +00002237 if (CFP->isExactlyValue(ConstantFP::getNegativeZero(Ty)->getValueAPF())) {
Chris Lattner01b3d732005-09-28 22:28:18 +00002238 SDOperand Op2 = getValue(I.getOperand(1));
2239 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
2240 return;
2241 }
Dan Gohman7f321562007-06-25 16:23:39 +00002242 }
2243
2244 visitBinary(I, Ty->isFPOrFPVector() ? ISD::FSUB : ISD::SUB);
Chris Lattnerb9fccc42005-04-02 05:04:50 +00002245}
2246
Dan Gohman7f321562007-06-25 16:23:39 +00002247void SelectionDAGLowering::visitBinary(User &I, unsigned OpCode) {
Chris Lattner1c08c712005-01-07 07:47:53 +00002248 SDOperand Op1 = getValue(I.getOperand(0));
2249 SDOperand Op2 = getValue(I.getOperand(1));
Reid Spencer24d6da52007-01-21 00:29:26 +00002250
2251 setValue(&I, DAG.getNode(OpCode, Op1.getValueType(), Op1, Op2));
Reid Spencer1628cec2006-10-26 06:15:43 +00002252}
2253
Nate Begemane21ea612005-11-18 07:42:56 +00002254void SelectionDAGLowering::visitShift(User &I, unsigned Opcode) {
2255 SDOperand Op1 = getValue(I.getOperand(0));
2256 SDOperand Op2 = getValue(I.getOperand(1));
2257
Dan Gohman7f321562007-06-25 16:23:39 +00002258 if (MVT::getSizeInBits(TLI.getShiftAmountTy()) <
2259 MVT::getSizeInBits(Op2.getValueType()))
Reid Spencer832254e2007-02-02 02:16:23 +00002260 Op2 = DAG.getNode(ISD::TRUNCATE, TLI.getShiftAmountTy(), Op2);
2261 else if (TLI.getShiftAmountTy() > Op2.getValueType())
2262 Op2 = DAG.getNode(ISD::ANY_EXTEND, TLI.getShiftAmountTy(), Op2);
Nate Begemane21ea612005-11-18 07:42:56 +00002263
Chris Lattner1c08c712005-01-07 07:47:53 +00002264 setValue(&I, DAG.getNode(Opcode, Op1.getValueType(), Op1, Op2));
2265}
2266
Reid Spencer45fb3f32006-11-20 01:22:35 +00002267void SelectionDAGLowering::visitICmp(User &I) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002268 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
2269 if (ICmpInst *IC = dyn_cast<ICmpInst>(&I))
2270 predicate = IC->getPredicate();
2271 else if (ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
2272 predicate = ICmpInst::Predicate(IC->getPredicate());
2273 SDOperand Op1 = getValue(I.getOperand(0));
2274 SDOperand Op2 = getValue(I.getOperand(1));
Reid Spencer45fb3f32006-11-20 01:22:35 +00002275 ISD::CondCode Opcode;
Reid Spencere4d87aa2006-12-23 06:05:41 +00002276 switch (predicate) {
Reid Spencer45fb3f32006-11-20 01:22:35 +00002277 case ICmpInst::ICMP_EQ : Opcode = ISD::SETEQ; break;
2278 case ICmpInst::ICMP_NE : Opcode = ISD::SETNE; break;
2279 case ICmpInst::ICMP_UGT : Opcode = ISD::SETUGT; break;
2280 case ICmpInst::ICMP_UGE : Opcode = ISD::SETUGE; break;
2281 case ICmpInst::ICMP_ULT : Opcode = ISD::SETULT; break;
2282 case ICmpInst::ICMP_ULE : Opcode = ISD::SETULE; break;
2283 case ICmpInst::ICMP_SGT : Opcode = ISD::SETGT; break;
2284 case ICmpInst::ICMP_SGE : Opcode = ISD::SETGE; break;
2285 case ICmpInst::ICMP_SLT : Opcode = ISD::SETLT; break;
2286 case ICmpInst::ICMP_SLE : Opcode = ISD::SETLE; break;
2287 default:
2288 assert(!"Invalid ICmp predicate value");
2289 Opcode = ISD::SETEQ;
2290 break;
2291 }
2292 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Opcode));
2293}
2294
2295void SelectionDAGLowering::visitFCmp(User &I) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002296 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
2297 if (FCmpInst *FC = dyn_cast<FCmpInst>(&I))
2298 predicate = FC->getPredicate();
2299 else if (ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
2300 predicate = FCmpInst::Predicate(FC->getPredicate());
Chris Lattner1c08c712005-01-07 07:47:53 +00002301 SDOperand Op1 = getValue(I.getOperand(0));
2302 SDOperand Op2 = getValue(I.getOperand(1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00002303 ISD::CondCode Condition, FOC, FPC;
2304 switch (predicate) {
2305 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
2306 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
2307 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
2308 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
2309 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
2310 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
2311 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
2312 case FCmpInst::FCMP_ORD: FOC = ISD::SETEQ; FPC = ISD::SETO; break;
2313 case FCmpInst::FCMP_UNO: FOC = ISD::SETNE; FPC = ISD::SETUO; break;
2314 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
2315 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
2316 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
2317 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
2318 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
2319 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
2320 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
2321 default:
2322 assert(!"Invalid FCmp predicate value");
2323 FOC = FPC = ISD::SETFALSE;
2324 break;
2325 }
2326 if (FiniteOnlyFPMath())
2327 Condition = FOC;
2328 else
2329 Condition = FPC;
2330 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Condition));
Chris Lattner1c08c712005-01-07 07:47:53 +00002331}
2332
2333void SelectionDAGLowering::visitSelect(User &I) {
2334 SDOperand Cond = getValue(I.getOperand(0));
2335 SDOperand TrueVal = getValue(I.getOperand(1));
2336 SDOperand FalseVal = getValue(I.getOperand(2));
Dan Gohman7f321562007-06-25 16:23:39 +00002337 setValue(&I, DAG.getNode(ISD::SELECT, TrueVal.getValueType(), Cond,
2338 TrueVal, FalseVal));
Chris Lattner1c08c712005-01-07 07:47:53 +00002339}
2340
Reid Spencer3da59db2006-11-27 01:05:10 +00002341
2342void SelectionDAGLowering::visitTrunc(User &I) {
2343 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
2344 SDOperand N = getValue(I.getOperand(0));
2345 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2346 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
2347}
2348
2349void SelectionDAGLowering::visitZExt(User &I) {
2350 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2351 // ZExt also can't be a cast to bool for same reason. So, nothing much to do
2352 SDOperand N = getValue(I.getOperand(0));
2353 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2354 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
2355}
2356
2357void SelectionDAGLowering::visitSExt(User &I) {
2358 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2359 // SExt also can't be a cast to bool for same reason. So, nothing much to do
2360 SDOperand N = getValue(I.getOperand(0));
2361 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2362 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, DestVT, N));
2363}
2364
2365void SelectionDAGLowering::visitFPTrunc(User &I) {
2366 // FPTrunc is never a no-op cast, no need to check
2367 SDOperand N = getValue(I.getOperand(0));
2368 MVT::ValueType DestVT = TLI.getValueType(I.getType());
Chris Lattner0bd48932008-01-17 07:00:52 +00002369 setValue(&I, DAG.getNode(ISD::FP_ROUND, DestVT, N, DAG.getIntPtrConstant(0)));
Reid Spencer3da59db2006-11-27 01:05:10 +00002370}
2371
2372void SelectionDAGLowering::visitFPExt(User &I){
2373 // FPTrunc is never a no-op cast, no need to check
2374 SDOperand N = getValue(I.getOperand(0));
2375 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2376 setValue(&I, DAG.getNode(ISD::FP_EXTEND, DestVT, N));
2377}
2378
2379void SelectionDAGLowering::visitFPToUI(User &I) {
2380 // FPToUI is never a no-op cast, no need to check
2381 SDOperand N = getValue(I.getOperand(0));
2382 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2383 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, DestVT, N));
2384}
2385
2386void SelectionDAGLowering::visitFPToSI(User &I) {
2387 // FPToSI is never a no-op cast, no need to check
2388 SDOperand N = getValue(I.getOperand(0));
2389 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2390 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, DestVT, N));
2391}
2392
2393void SelectionDAGLowering::visitUIToFP(User &I) {
2394 // UIToFP is never a no-op cast, no need to check
2395 SDOperand N = getValue(I.getOperand(0));
2396 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2397 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, DestVT, N));
2398}
2399
2400void SelectionDAGLowering::visitSIToFP(User &I){
2401 // UIToFP is never a no-op cast, no need to check
2402 SDOperand N = getValue(I.getOperand(0));
2403 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2404 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, DestVT, N));
2405}
2406
2407void SelectionDAGLowering::visitPtrToInt(User &I) {
2408 // What to do depends on the size of the integer and the size of the pointer.
2409 // We can either truncate, zero extend, or no-op, accordingly.
Chris Lattner1c08c712005-01-07 07:47:53 +00002410 SDOperand N = getValue(I.getOperand(0));
Chris Lattnere25ca692006-03-22 20:09:35 +00002411 MVT::ValueType SrcVT = N.getValueType();
Chris Lattner28b5b1c2006-03-15 22:19:46 +00002412 MVT::ValueType DestVT = TLI.getValueType(I.getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00002413 SDOperand Result;
2414 if (MVT::getSizeInBits(DestVT) < MVT::getSizeInBits(SrcVT))
2415 Result = DAG.getNode(ISD::TRUNCATE, DestVT, N);
2416 else
2417 // Note: ZERO_EXTEND can handle cases where the sizes are equal too
2418 Result = DAG.getNode(ISD::ZERO_EXTEND, DestVT, N);
2419 setValue(&I, Result);
2420}
Chris Lattner1c08c712005-01-07 07:47:53 +00002421
Reid Spencer3da59db2006-11-27 01:05:10 +00002422void SelectionDAGLowering::visitIntToPtr(User &I) {
2423 // What to do depends on the size of the integer and the size of the pointer.
2424 // We can either truncate, zero extend, or no-op, accordingly.
2425 SDOperand N = getValue(I.getOperand(0));
2426 MVT::ValueType SrcVT = N.getValueType();
2427 MVT::ValueType DestVT = TLI.getValueType(I.getType());
2428 if (MVT::getSizeInBits(DestVT) < MVT::getSizeInBits(SrcVT))
2429 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
2430 else
2431 // Note: ZERO_EXTEND can handle cases where the sizes are equal too
2432 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
2433}
2434
2435void SelectionDAGLowering::visitBitCast(User &I) {
2436 SDOperand N = getValue(I.getOperand(0));
2437 MVT::ValueType DestVT = TLI.getValueType(I.getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00002438
2439 // BitCast assures us that source and destination are the same size so this
2440 // is either a BIT_CONVERT or a no-op.
2441 if (DestVT != N.getValueType())
2442 setValue(&I, DAG.getNode(ISD::BIT_CONVERT, DestVT, N)); // convert types
2443 else
2444 setValue(&I, N); // noop cast.
Chris Lattner1c08c712005-01-07 07:47:53 +00002445}
2446
Chris Lattner2bbd8102006-03-29 00:11:43 +00002447void SelectionDAGLowering::visitInsertElement(User &I) {
Chris Lattnerc7029802006-03-18 01:44:44 +00002448 SDOperand InVec = getValue(I.getOperand(0));
2449 SDOperand InVal = getValue(I.getOperand(1));
2450 SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
2451 getValue(I.getOperand(2)));
2452
Dan Gohman7f321562007-06-25 16:23:39 +00002453 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT,
2454 TLI.getValueType(I.getType()),
2455 InVec, InVal, InIdx));
Chris Lattnerc7029802006-03-18 01:44:44 +00002456}
2457
Chris Lattner2bbd8102006-03-29 00:11:43 +00002458void SelectionDAGLowering::visitExtractElement(User &I) {
Chris Lattner384504c2006-03-21 20:44:12 +00002459 SDOperand InVec = getValue(I.getOperand(0));
2460 SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
2461 getValue(I.getOperand(1)));
Dan Gohman7f321562007-06-25 16:23:39 +00002462 setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
Chris Lattner384504c2006-03-21 20:44:12 +00002463 TLI.getValueType(I.getType()), InVec, InIdx));
2464}
Chris Lattnerc7029802006-03-18 01:44:44 +00002465
Chris Lattner3e104b12006-04-08 04:15:24 +00002466void SelectionDAGLowering::visitShuffleVector(User &I) {
2467 SDOperand V1 = getValue(I.getOperand(0));
2468 SDOperand V2 = getValue(I.getOperand(1));
2469 SDOperand Mask = getValue(I.getOperand(2));
2470
Dan Gohman7f321562007-06-25 16:23:39 +00002471 setValue(&I, DAG.getNode(ISD::VECTOR_SHUFFLE,
2472 TLI.getValueType(I.getType()),
2473 V1, V2, Mask));
Chris Lattner3e104b12006-04-08 04:15:24 +00002474}
2475
2476
Chris Lattner1c08c712005-01-07 07:47:53 +00002477void SelectionDAGLowering::visitGetElementPtr(User &I) {
2478 SDOperand N = getValue(I.getOperand(0));
2479 const Type *Ty = I.getOperand(0)->getType();
Chris Lattner1c08c712005-01-07 07:47:53 +00002480
2481 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
2482 OI != E; ++OI) {
2483 Value *Idx = *OI;
Chris Lattnerc88d8e92005-12-05 07:10:48 +00002484 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002485 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
Chris Lattner1c08c712005-01-07 07:47:53 +00002486 if (Field) {
2487 // N = N + Offset
Chris Lattnerb1919e22007-02-10 19:55:17 +00002488 uint64_t Offset = TD->getStructLayout(StTy)->getElementOffset(Field);
Chris Lattner1c08c712005-01-07 07:47:53 +00002489 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
Chris Lattner0bd48932008-01-17 07:00:52 +00002490 DAG.getIntPtrConstant(Offset));
Chris Lattner1c08c712005-01-07 07:47:53 +00002491 }
2492 Ty = StTy->getElementType(Field);
2493 } else {
2494 Ty = cast<SequentialType>(Ty)->getElementType();
Chris Lattner7cc47772005-01-07 21:56:57 +00002495
Chris Lattner7c0104b2005-11-09 04:45:33 +00002496 // If this is a constant subscript, handle it quickly.
2497 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002498 if (CI->getZExtValue() == 0) continue;
Reid Spencer47857812006-12-31 05:55:36 +00002499 uint64_t Offs =
Dale Johannesena7ac2bd2007-10-01 23:08:35 +00002500 TD->getABITypeSize(Ty)*cast<ConstantInt>(CI)->getSExtValue();
Chris Lattner0bd48932008-01-17 07:00:52 +00002501 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
2502 DAG.getIntPtrConstant(Offs));
Chris Lattner7c0104b2005-11-09 04:45:33 +00002503 continue;
Chris Lattner1c08c712005-01-07 07:47:53 +00002504 }
Chris Lattner7c0104b2005-11-09 04:45:33 +00002505
2506 // N = N + Idx * ElementSize;
Dale Johannesena7ac2bd2007-10-01 23:08:35 +00002507 uint64_t ElementSize = TD->getABITypeSize(Ty);
Chris Lattner7c0104b2005-11-09 04:45:33 +00002508 SDOperand IdxN = getValue(Idx);
2509
2510 // If the index is smaller or larger than intptr_t, truncate or extend
2511 // it.
2512 if (IdxN.getValueType() < N.getValueType()) {
Reid Spencer47857812006-12-31 05:55:36 +00002513 IdxN = DAG.getNode(ISD::SIGN_EXTEND, N.getValueType(), IdxN);
Chris Lattner7c0104b2005-11-09 04:45:33 +00002514 } else if (IdxN.getValueType() > N.getValueType())
2515 IdxN = DAG.getNode(ISD::TRUNCATE, N.getValueType(), IdxN);
2516
2517 // If this is a multiply by a power of two, turn it into a shl
2518 // immediately. This is a very common case.
2519 if (isPowerOf2_64(ElementSize)) {
2520 unsigned Amt = Log2_64(ElementSize);
2521 IdxN = DAG.getNode(ISD::SHL, N.getValueType(), IdxN,
Chris Lattner6b2d6962005-11-09 16:50:40 +00002522 DAG.getConstant(Amt, TLI.getShiftAmountTy()));
Chris Lattner7c0104b2005-11-09 04:45:33 +00002523 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
2524 continue;
2525 }
2526
Chris Lattner0bd48932008-01-17 07:00:52 +00002527 SDOperand Scale = DAG.getIntPtrConstant(ElementSize);
Chris Lattner7c0104b2005-11-09 04:45:33 +00002528 IdxN = DAG.getNode(ISD::MUL, N.getValueType(), IdxN, Scale);
2529 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
Chris Lattner1c08c712005-01-07 07:47:53 +00002530 }
2531 }
2532 setValue(&I, N);
2533}
2534
2535void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
2536 // If this is a fixed sized alloca in the entry block of the function,
2537 // allocate it statically on the stack.
2538 if (FuncInfo.StaticAllocaMap.count(&I))
2539 return; // getValue will auto-populate this.
2540
2541 const Type *Ty = I.getAllocatedType();
Duncan Sands514ab342007-11-01 20:53:16 +00002542 uint64_t TySize = TLI.getTargetData()->getABITypeSize(Ty);
Chris Lattner58092e32007-01-20 22:35:55 +00002543 unsigned Align =
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00002544 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
Chris Lattner58092e32007-01-20 22:35:55 +00002545 I.getAlignment());
Chris Lattner1c08c712005-01-07 07:47:53 +00002546
2547 SDOperand AllocSize = getValue(I.getArraySize());
Chris Lattner68cd65e2005-01-22 23:04:37 +00002548 MVT::ValueType IntPtr = TLI.getPointerTy();
2549 if (IntPtr < AllocSize.getValueType())
2550 AllocSize = DAG.getNode(ISD::TRUNCATE, IntPtr, AllocSize);
2551 else if (IntPtr > AllocSize.getValueType())
2552 AllocSize = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, AllocSize);
Chris Lattner1c08c712005-01-07 07:47:53 +00002553
Chris Lattner68cd65e2005-01-22 23:04:37 +00002554 AllocSize = DAG.getNode(ISD::MUL, IntPtr, AllocSize,
Chris Lattner0bd48932008-01-17 07:00:52 +00002555 DAG.getIntPtrConstant(TySize));
Chris Lattner1c08c712005-01-07 07:47:53 +00002556
Evan Cheng45157792007-08-16 23:46:29 +00002557 // Handle alignment. If the requested alignment is less than or equal to
2558 // the stack alignment, ignore it. If the size is greater than or equal to
2559 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
Chris Lattner1c08c712005-01-07 07:47:53 +00002560 unsigned StackAlign =
2561 TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
Evan Cheng45157792007-08-16 23:46:29 +00002562 if (Align <= StackAlign)
Chris Lattner1c08c712005-01-07 07:47:53 +00002563 Align = 0;
Evan Cheng45157792007-08-16 23:46:29 +00002564
2565 // Round the size of the allocation up to the stack alignment size
2566 // by add SA-1 to the size.
2567 AllocSize = DAG.getNode(ISD::ADD, AllocSize.getValueType(), AllocSize,
Chris Lattner0bd48932008-01-17 07:00:52 +00002568 DAG.getIntPtrConstant(StackAlign-1));
Evan Cheng45157792007-08-16 23:46:29 +00002569 // Mask out the low bits for alignment purposes.
2570 AllocSize = DAG.getNode(ISD::AND, AllocSize.getValueType(), AllocSize,
Chris Lattner0bd48932008-01-17 07:00:52 +00002571 DAG.getIntPtrConstant(~(uint64_t)(StackAlign-1)));
Chris Lattner1c08c712005-01-07 07:47:53 +00002572
Chris Lattner0bd48932008-01-17 07:00:52 +00002573 SDOperand Ops[] = { getRoot(), AllocSize, DAG.getIntPtrConstant(Align) };
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00002574 const MVT::ValueType *VTs = DAG.getNodeValueTypes(AllocSize.getValueType(),
2575 MVT::Other);
2576 SDOperand DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, VTs, 2, Ops, 3);
Chris Lattner0da331f2007-02-04 01:31:47 +00002577 setValue(&I, DSA);
2578 DAG.setRoot(DSA.getValue(1));
Chris Lattner1c08c712005-01-07 07:47:53 +00002579
2580 // Inform the Frame Information that we have just allocated a variable-sized
2581 // object.
2582 CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
2583}
2584
Chris Lattner1c08c712005-01-07 07:47:53 +00002585void SelectionDAGLowering::visitLoad(LoadInst &I) {
2586 SDOperand Ptr = getValue(I.getOperand(0));
Misha Brukmanedf128a2005-04-21 22:36:52 +00002587
Chris Lattnerd3948112005-01-17 22:19:26 +00002588 SDOperand Root;
2589 if (I.isVolatile())
2590 Root = getRoot();
2591 else {
2592 // Do not serialize non-volatile loads against each other.
2593 Root = DAG.getRoot();
2594 }
Chris Lattner28b5b1c2006-03-15 22:19:46 +00002595
Evan Cheng466685d2006-10-09 20:57:25 +00002596 setValue(&I, getLoadFrom(I.getType(), Ptr, I.getOperand(0),
Christopher Lamb95c218a2007-04-22 23:15:30 +00002597 Root, I.isVolatile(), I.getAlignment()));
Chris Lattner28b5b1c2006-03-15 22:19:46 +00002598}
2599
2600SDOperand SelectionDAGLowering::getLoadFrom(const Type *Ty, SDOperand Ptr,
Evan Cheng466685d2006-10-09 20:57:25 +00002601 const Value *SV, SDOperand Root,
Christopher Lamb95c218a2007-04-22 23:15:30 +00002602 bool isVolatile,
2603 unsigned Alignment) {
Dan Gohman7f321562007-06-25 16:23:39 +00002604 SDOperand L =
2605 DAG.getLoad(TLI.getValueType(Ty), Root, Ptr, SV, 0,
2606 isVolatile, Alignment);
Chris Lattnerd3948112005-01-17 22:19:26 +00002607
Chris Lattner28b5b1c2006-03-15 22:19:46 +00002608 if (isVolatile)
Chris Lattnerd3948112005-01-17 22:19:26 +00002609 DAG.setRoot(L.getValue(1));
2610 else
2611 PendingLoads.push_back(L.getValue(1));
Chris Lattner28b5b1c2006-03-15 22:19:46 +00002612
2613 return L;
Chris Lattner1c08c712005-01-07 07:47:53 +00002614}
2615
2616
2617void SelectionDAGLowering::visitStore(StoreInst &I) {
2618 Value *SrcV = I.getOperand(0);
2619 SDOperand Src = getValue(SrcV);
2620 SDOperand Ptr = getValue(I.getOperand(1));
Evan Cheng0b4f80e2006-12-20 01:27:29 +00002621 DAG.setRoot(DAG.getStore(getRoot(), Src, Ptr, I.getOperand(1), 0,
Christopher Lamb95c218a2007-04-22 23:15:30 +00002622 I.isVolatile(), I.getAlignment()));
Chris Lattner1c08c712005-01-07 07:47:53 +00002623}
2624
Chris Lattner0eade312006-03-24 02:22:33 +00002625/// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
2626/// node.
2627void SelectionDAGLowering::visitTargetIntrinsic(CallInst &I,
2628 unsigned Intrinsic) {
Duncan Sandsa3355ff2007-12-03 20:06:50 +00002629 bool HasChain = !I.doesNotAccessMemory();
2630 bool OnlyLoad = HasChain && I.onlyReadsMemory();
2631
Chris Lattner0eade312006-03-24 02:22:33 +00002632 // Build the operand list.
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002633 SmallVector<SDOperand, 8> Ops;
Chris Lattnere58a7802006-04-02 03:41:14 +00002634 if (HasChain) { // If this intrinsic has side-effects, chainify it.
2635 if (OnlyLoad) {
2636 // We don't need to serialize loads against other loads.
2637 Ops.push_back(DAG.getRoot());
2638 } else {
2639 Ops.push_back(getRoot());
2640 }
2641 }
Chris Lattner0eade312006-03-24 02:22:33 +00002642
2643 // Add the intrinsic ID as an integer operand.
2644 Ops.push_back(DAG.getConstant(Intrinsic, TLI.getPointerTy()));
2645
2646 // Add all operands of the call to the operand list.
2647 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
2648 SDOperand Op = getValue(I.getOperand(i));
Chris Lattner0eade312006-03-24 02:22:33 +00002649 assert(TLI.isTypeLegal(Op.getValueType()) &&
2650 "Intrinsic uses a non-legal type?");
2651 Ops.push_back(Op);
2652 }
2653
2654 std::vector<MVT::ValueType> VTs;
2655 if (I.getType() != Type::VoidTy) {
2656 MVT::ValueType VT = TLI.getValueType(I.getType());
Dan Gohman7f321562007-06-25 16:23:39 +00002657 if (MVT::isVector(VT)) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00002658 const VectorType *DestTy = cast<VectorType>(I.getType());
Chris Lattner0eade312006-03-24 02:22:33 +00002659 MVT::ValueType EltVT = TLI.getValueType(DestTy->getElementType());
2660
2661 VT = MVT::getVectorType(EltVT, DestTy->getNumElements());
2662 assert(VT != MVT::Other && "Intrinsic uses a non-legal type?");
2663 }
2664
2665 assert(TLI.isTypeLegal(VT) && "Intrinsic uses a non-legal type?");
2666 VTs.push_back(VT);
2667 }
2668 if (HasChain)
2669 VTs.push_back(MVT::Other);
2670
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00002671 const MVT::ValueType *VTList = DAG.getNodeValueTypes(VTs);
2672
Chris Lattner0eade312006-03-24 02:22:33 +00002673 // Create the node.
Chris Lattner48b61a72006-03-28 00:40:33 +00002674 SDOperand Result;
2675 if (!HasChain)
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00002676 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VTList, VTs.size(),
2677 &Ops[0], Ops.size());
Chris Lattner48b61a72006-03-28 00:40:33 +00002678 else if (I.getType() != Type::VoidTy)
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00002679 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, VTList, VTs.size(),
2680 &Ops[0], Ops.size());
Chris Lattner48b61a72006-03-28 00:40:33 +00002681 else
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00002682 Result = DAG.getNode(ISD::INTRINSIC_VOID, VTList, VTs.size(),
2683 &Ops[0], Ops.size());
Chris Lattner48b61a72006-03-28 00:40:33 +00002684
Chris Lattnere58a7802006-04-02 03:41:14 +00002685 if (HasChain) {
2686 SDOperand Chain = Result.getValue(Result.Val->getNumValues()-1);
2687 if (OnlyLoad)
2688 PendingLoads.push_back(Chain);
2689 else
2690 DAG.setRoot(Chain);
2691 }
Chris Lattner0eade312006-03-24 02:22:33 +00002692 if (I.getType() != Type::VoidTy) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00002693 if (const VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
Dan Gohman7f321562007-06-25 16:23:39 +00002694 MVT::ValueType VT = TLI.getValueType(PTy);
2695 Result = DAG.getNode(ISD::BIT_CONVERT, VT, Result);
Chris Lattner0eade312006-03-24 02:22:33 +00002696 }
2697 setValue(&I, Result);
2698 }
2699}
2700
Duncan Sandsb4fd45e2007-07-06 09:10:03 +00002701/// ExtractTypeInfo - Returns the type info, possibly bitcast, encoded in V.
Duncan Sandscf26d7c2007-07-04 20:52:51 +00002702static GlobalVariable *ExtractTypeInfo (Value *V) {
Duncan Sandsb4fd45e2007-07-06 09:10:03 +00002703 V = IntrinsicInst::StripPointerCasts(V);
2704 GlobalVariable *GV = dyn_cast<GlobalVariable>(V);
Anton Korobeynikov4c71dfe2008-02-20 11:10:28 +00002705 assert ((GV || isa<ConstantPointerNull>(V)) &&
Duncan Sandscf26d7c2007-07-04 20:52:51 +00002706 "TypeInfo must be a global variable or NULL");
2707 return GV;
2708}
2709
Duncan Sandsf4070822007-06-15 19:04:19 +00002710/// addCatchInfo - Extract the personality and type infos from an eh.selector
Duncan Sandscf26d7c2007-07-04 20:52:51 +00002711/// call, and add them to the specified machine basic block.
Duncan Sandsf4070822007-06-15 19:04:19 +00002712static void addCatchInfo(CallInst &I, MachineModuleInfo *MMI,
2713 MachineBasicBlock *MBB) {
2714 // Inform the MachineModuleInfo of the personality for this landing pad.
2715 ConstantExpr *CE = cast<ConstantExpr>(I.getOperand(2));
2716 assert(CE->getOpcode() == Instruction::BitCast &&
2717 isa<Function>(CE->getOperand(0)) &&
2718 "Personality should be a function");
2719 MMI->addPersonality(MBB, cast<Function>(CE->getOperand(0)));
2720
2721 // Gather all the type infos for this landing pad and pass them along to
2722 // MachineModuleInfo.
2723 std::vector<GlobalVariable *> TyInfo;
Duncan Sandscf26d7c2007-07-04 20:52:51 +00002724 unsigned N = I.getNumOperands();
2725
2726 for (unsigned i = N - 1; i > 2; --i) {
2727 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(i))) {
2728 unsigned FilterLength = CI->getZExtValue();
Duncan Sands6590b042007-08-27 15:47:50 +00002729 unsigned FirstCatch = i + FilterLength + !FilterLength;
Duncan Sandscf26d7c2007-07-04 20:52:51 +00002730 assert (FirstCatch <= N && "Invalid filter length");
2731
2732 if (FirstCatch < N) {
2733 TyInfo.reserve(N - FirstCatch);
2734 for (unsigned j = FirstCatch; j < N; ++j)
2735 TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
2736 MMI->addCatchTypeInfo(MBB, TyInfo);
2737 TyInfo.clear();
2738 }
2739
Duncan Sands6590b042007-08-27 15:47:50 +00002740 if (!FilterLength) {
2741 // Cleanup.
2742 MMI->addCleanup(MBB);
2743 } else {
2744 // Filter.
2745 TyInfo.reserve(FilterLength - 1);
2746 for (unsigned j = i + 1; j < FirstCatch; ++j)
2747 TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
2748 MMI->addFilterTypeInfo(MBB, TyInfo);
2749 TyInfo.clear();
2750 }
Duncan Sandscf26d7c2007-07-04 20:52:51 +00002751
2752 N = i;
2753 }
Duncan Sandsf4070822007-06-15 19:04:19 +00002754 }
Duncan Sandscf26d7c2007-07-04 20:52:51 +00002755
2756 if (N > 3) {
2757 TyInfo.reserve(N - 3);
2758 for (unsigned j = 3; j < N; ++j)
2759 TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
Duncan Sandsf4070822007-06-15 19:04:19 +00002760 MMI->addCatchTypeInfo(MBB, TyInfo);
Duncan Sandscf26d7c2007-07-04 20:52:51 +00002761 }
Duncan Sandsf4070822007-06-15 19:04:19 +00002762}
2763
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002764/// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
2765/// we want to emit this as a call to a named external function, return the name
2766/// otherwise lower it and return null.
2767const char *
2768SelectionDAGLowering::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
2769 switch (Intrinsic) {
Chris Lattner0eade312006-03-24 02:22:33 +00002770 default:
2771 // By default, turn this into a target intrinsic node.
2772 visitTargetIntrinsic(I, Intrinsic);
2773 return 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002774 case Intrinsic::vastart: visitVAStart(I); return 0;
2775 case Intrinsic::vaend: visitVAEnd(I); return 0;
2776 case Intrinsic::vacopy: visitVACopy(I); return 0;
Nate Begemanbcc5f362007-01-29 22:58:52 +00002777 case Intrinsic::returnaddress:
2778 setValue(&I, DAG.getNode(ISD::RETURNADDR, TLI.getPointerTy(),
2779 getValue(I.getOperand(1))));
2780 return 0;
2781 case Intrinsic::frameaddress:
2782 setValue(&I, DAG.getNode(ISD::FRAMEADDR, TLI.getPointerTy(),
2783 getValue(I.getOperand(1))));
2784 return 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002785 case Intrinsic::setjmp:
Anton Korobeynikovd27a2582006-12-10 23:12:42 +00002786 return "_setjmp"+!TLI.usesUnderscoreSetJmp();
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002787 break;
2788 case Intrinsic::longjmp:
Anton Korobeynikovd27a2582006-12-10 23:12:42 +00002789 return "_longjmp"+!TLI.usesUnderscoreLongJmp();
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002790 break;
Chris Lattner03dd4652006-03-03 00:00:25 +00002791 case Intrinsic::memcpy_i32:
Dan Gohman707e0182008-04-12 04:36:06 +00002792 case Intrinsic::memcpy_i64: {
2793 SDOperand Op1 = getValue(I.getOperand(1));
2794 SDOperand Op2 = getValue(I.getOperand(2));
2795 SDOperand Op3 = getValue(I.getOperand(3));
2796 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
2797 DAG.setRoot(DAG.getMemcpy(getRoot(), Op1, Op2, Op3, Align, false,
2798 I.getOperand(1), 0, I.getOperand(2), 0));
Chris Lattner03dd4652006-03-03 00:00:25 +00002799 return 0;
Dan Gohman707e0182008-04-12 04:36:06 +00002800 }
Chris Lattner03dd4652006-03-03 00:00:25 +00002801 case Intrinsic::memset_i32:
Dan Gohman707e0182008-04-12 04:36:06 +00002802 case Intrinsic::memset_i64: {
2803 SDOperand Op1 = getValue(I.getOperand(1));
2804 SDOperand Op2 = getValue(I.getOperand(2));
2805 SDOperand Op3 = getValue(I.getOperand(3));
2806 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
2807 DAG.setRoot(DAG.getMemset(getRoot(), Op1, Op2, Op3, Align,
2808 I.getOperand(1), 0));
Chris Lattner03dd4652006-03-03 00:00:25 +00002809 return 0;
Dan Gohman707e0182008-04-12 04:36:06 +00002810 }
Chris Lattner03dd4652006-03-03 00:00:25 +00002811 case Intrinsic::memmove_i32:
Dan Gohman707e0182008-04-12 04:36:06 +00002812 case Intrinsic::memmove_i64: {
2813 SDOperand Op1 = getValue(I.getOperand(1));
2814 SDOperand Op2 = getValue(I.getOperand(2));
2815 SDOperand Op3 = getValue(I.getOperand(3));
2816 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
2817
2818 // If the source and destination are known to not be aliases, we can
2819 // lower memmove as memcpy.
2820 uint64_t Size = -1ULL;
2821 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op3))
2822 Size = C->getValue();
2823 if (AA.alias(I.getOperand(1), Size, I.getOperand(2), Size) ==
2824 AliasAnalysis::NoAlias) {
2825 DAG.setRoot(DAG.getMemcpy(getRoot(), Op1, Op2, Op3, Align, false,
2826 I.getOperand(1), 0, I.getOperand(2), 0));
2827 return 0;
2828 }
2829
2830 DAG.setRoot(DAG.getMemmove(getRoot(), Op1, Op2, Op3, Align,
2831 I.getOperand(1), 0, I.getOperand(2), 0));
Chris Lattner03dd4652006-03-03 00:00:25 +00002832 return 0;
Dan Gohman707e0182008-04-12 04:36:06 +00002833 }
Chris Lattner86cb6432005-12-13 17:40:33 +00002834 case Intrinsic::dbg_stoppoint: {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002835 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskey43970fe2006-03-23 18:06:46 +00002836 DbgStopPointInst &SPI = cast<DbgStopPointInst>(I);
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002837 if (MMI && SPI.getContext() && MMI->Verify(SPI.getContext())) {
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002838 SDOperand Ops[5];
Chris Lattner36ce6912005-11-29 06:21:05 +00002839
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002840 Ops[0] = getRoot();
2841 Ops[1] = getValue(SPI.getLineValue());
2842 Ops[2] = getValue(SPI.getColumnValue());
Chris Lattner36ce6912005-11-29 06:21:05 +00002843
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002844 DebugInfoDesc *DD = MMI->getDescFor(SPI.getContext());
Jim Laskeyce72b172006-02-11 01:01:30 +00002845 assert(DD && "Not a debug information descriptor");
Jim Laskey43970fe2006-03-23 18:06:46 +00002846 CompileUnitDesc *CompileUnit = cast<CompileUnitDesc>(DD);
2847
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002848 Ops[3] = DAG.getString(CompileUnit->getFileName());
2849 Ops[4] = DAG.getString(CompileUnit->getDirectory());
Jim Laskeyce72b172006-02-11 01:01:30 +00002850
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002851 DAG.setRoot(DAG.getNode(ISD::LOCATION, MVT::Other, Ops, 5));
Chris Lattner86cb6432005-12-13 17:40:33 +00002852 }
Jim Laskey43970fe2006-03-23 18:06:46 +00002853
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +00002854 return 0;
Chris Lattner36ce6912005-11-29 06:21:05 +00002855 }
Jim Laskey43970fe2006-03-23 18:06:46 +00002856 case Intrinsic::dbg_region_start: {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002857 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskey43970fe2006-03-23 18:06:46 +00002858 DbgRegionStartInst &RSI = cast<DbgRegionStartInst>(I);
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002859 if (MMI && RSI.getContext() && MMI->Verify(RSI.getContext())) {
2860 unsigned LabelID = MMI->RecordRegionStart(RSI.getContext());
Jim Laskey1ee29252007-01-26 14:34:52 +00002861 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, getRoot(),
Evan Chengbb81d972008-01-31 09:59:15 +00002862 DAG.getConstant(LabelID, MVT::i32),
2863 DAG.getConstant(0, MVT::i32)));
Jim Laskey43970fe2006-03-23 18:06:46 +00002864 }
2865
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +00002866 return 0;
Jim Laskey43970fe2006-03-23 18:06:46 +00002867 }
2868 case Intrinsic::dbg_region_end: {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002869 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskey43970fe2006-03-23 18:06:46 +00002870 DbgRegionEndInst &REI = cast<DbgRegionEndInst>(I);
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002871 if (MMI && REI.getContext() && MMI->Verify(REI.getContext())) {
2872 unsigned LabelID = MMI->RecordRegionEnd(REI.getContext());
Evan Chengbb81d972008-01-31 09:59:15 +00002873 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, getRoot(),
2874 DAG.getConstant(LabelID, MVT::i32),
2875 DAG.getConstant(0, MVT::i32)));
Jim Laskey43970fe2006-03-23 18:06:46 +00002876 }
2877
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +00002878 return 0;
Jim Laskey43970fe2006-03-23 18:06:46 +00002879 }
2880 case Intrinsic::dbg_func_start: {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002881 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Evan Cheng1b08bbc2008-02-01 09:10:45 +00002882 if (!MMI) return 0;
Jim Laskey43970fe2006-03-23 18:06:46 +00002883 DbgFuncStartInst &FSI = cast<DbgFuncStartInst>(I);
Evan Cheng1b08bbc2008-02-01 09:10:45 +00002884 Value *SP = FSI.getSubprogram();
2885 if (SP && MMI->Verify(SP)) {
2886 // llvm.dbg.func.start implicitly defines a dbg_stoppoint which is
2887 // what (most?) gdb expects.
2888 DebugInfoDesc *DD = MMI->getDescFor(SP);
2889 assert(DD && "Not a debug information descriptor");
2890 SubprogramDesc *Subprogram = cast<SubprogramDesc>(DD);
2891 const CompileUnitDesc *CompileUnit = Subprogram->getFile();
2892 unsigned SrcFile = MMI->RecordSource(CompileUnit->getDirectory(),
2893 CompileUnit->getFileName());
2894 // Record the source line but does create a label. It will be emitted
2895 // at asm emission time.
2896 MMI->RecordSourceLine(Subprogram->getLine(), 0, SrcFile);
Jim Laskey43970fe2006-03-23 18:06:46 +00002897 }
2898
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +00002899 return 0;
Jim Laskey43970fe2006-03-23 18:06:46 +00002900 }
2901 case Intrinsic::dbg_declare: {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002902 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskey43970fe2006-03-23 18:06:46 +00002903 DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
Evan Chenga844bde2008-02-02 04:07:54 +00002904 Value *Variable = DI.getVariable();
2905 if (MMI && Variable && MMI->Verify(Variable))
2906 DAG.setRoot(DAG.getNode(ISD::DECLARE, MVT::Other, getRoot(),
2907 getValue(DI.getAddress()), getValue(Variable)));
Jim Laskey43970fe2006-03-23 18:06:46 +00002908 return 0;
2909 }
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002910
Jim Laskeyb180aa12007-02-21 22:53:45 +00002911 case Intrinsic::eh_exception: {
Dale Johannesen1532f3d2008-04-02 00:25:04 +00002912 if (!CurMBB->isLandingPad()) {
2913 // FIXME: Mark exception register as live in. Hack for PR1508.
2914 unsigned Reg = TLI.getExceptionAddressRegister();
2915 if (Reg) CurMBB->addLiveIn(Reg);
Jim Laskey735b6f82007-02-22 15:38:06 +00002916 }
Dale Johannesen1532f3d2008-04-02 00:25:04 +00002917 // Insert the EXCEPTIONADDR instruction.
2918 SDVTList VTs = DAG.getVTList(TLI.getPointerTy(), MVT::Other);
2919 SDOperand Ops[1];
2920 Ops[0] = DAG.getRoot();
2921 SDOperand Op = DAG.getNode(ISD::EXCEPTIONADDR, VTs, Ops, 1);
2922 setValue(&I, Op);
2923 DAG.setRoot(Op.getValue(1));
Jim Laskeyb180aa12007-02-21 22:53:45 +00002924 return 0;
2925 }
2926
Anton Korobeynikov8806c7b2007-09-07 11:39:35 +00002927 case Intrinsic::eh_selector_i32:
2928 case Intrinsic::eh_selector_i64: {
Jim Laskeyb180aa12007-02-21 22:53:45 +00002929 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Anton Korobeynikov8806c7b2007-09-07 11:39:35 +00002930 MVT::ValueType VT = (Intrinsic == Intrinsic::eh_selector_i32 ?
2931 MVT::i32 : MVT::i64);
2932
Dale Johannesen1532f3d2008-04-02 00:25:04 +00002933 if (MMI) {
Duncan Sandsf4070822007-06-15 19:04:19 +00002934 if (CurMBB->isLandingPad())
2935 addCatchInfo(I, MMI, CurMBB);
Evan Chenge47c3332007-06-27 18:45:32 +00002936 else {
Duncan Sandsf4070822007-06-15 19:04:19 +00002937#ifndef NDEBUG
Duncan Sandsf4070822007-06-15 19:04:19 +00002938 FuncInfo.CatchInfoLost.insert(&I);
2939#endif
Duncan Sands90291952007-07-06 09:18:59 +00002940 // FIXME: Mark exception selector register as live in. Hack for PR1508.
2941 unsigned Reg = TLI.getExceptionSelectorRegister();
2942 if (Reg) CurMBB->addLiveIn(Reg);
Evan Chenge47c3332007-06-27 18:45:32 +00002943 }
Jim Laskey735b6f82007-02-22 15:38:06 +00002944
2945 // Insert the EHSELECTION instruction.
Anton Korobeynikov8806c7b2007-09-07 11:39:35 +00002946 SDVTList VTs = DAG.getVTList(VT, MVT::Other);
Jim Laskey735b6f82007-02-22 15:38:06 +00002947 SDOperand Ops[2];
2948 Ops[0] = getValue(I.getOperand(1));
2949 Ops[1] = getRoot();
2950 SDOperand Op = DAG.getNode(ISD::EHSELECTION, VTs, Ops, 2);
2951 setValue(&I, Op);
2952 DAG.setRoot(Op.getValue(1));
Jim Laskey7a1de982007-02-24 09:45:44 +00002953 } else {
Anton Korobeynikov8806c7b2007-09-07 11:39:35 +00002954 setValue(&I, DAG.getConstant(0, VT));
Jim Laskey735b6f82007-02-22 15:38:06 +00002955 }
Jim Laskeyb180aa12007-02-21 22:53:45 +00002956
2957 return 0;
2958 }
Anton Korobeynikov8806c7b2007-09-07 11:39:35 +00002959
2960 case Intrinsic::eh_typeid_for_i32:
2961 case Intrinsic::eh_typeid_for_i64: {
Jim Laskeyb180aa12007-02-21 22:53:45 +00002962 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Anton Korobeynikov8806c7b2007-09-07 11:39:35 +00002963 MVT::ValueType VT = (Intrinsic == Intrinsic::eh_typeid_for_i32 ?
2964 MVT::i32 : MVT::i64);
Jim Laskeyb180aa12007-02-21 22:53:45 +00002965
Jim Laskey735b6f82007-02-22 15:38:06 +00002966 if (MMI) {
2967 // Find the type id for the given typeinfo.
Duncan Sandscf26d7c2007-07-04 20:52:51 +00002968 GlobalVariable *GV = ExtractTypeInfo(I.getOperand(1));
Duncan Sands3b346362007-05-04 17:12:26 +00002969
Jim Laskey735b6f82007-02-22 15:38:06 +00002970 unsigned TypeID = MMI->getTypeIDFor(GV);
Anton Korobeynikov8806c7b2007-09-07 11:39:35 +00002971 setValue(&I, DAG.getConstant(TypeID, VT));
Jim Laskey7a1de982007-02-24 09:45:44 +00002972 } else {
Duncan Sandsf664e412007-07-06 14:46:23 +00002973 // Return something different to eh_selector.
Anton Korobeynikov8806c7b2007-09-07 11:39:35 +00002974 setValue(&I, DAG.getConstant(1, VT));
Jim Laskey735b6f82007-02-22 15:38:06 +00002975 }
Jim Laskeyb180aa12007-02-21 22:53:45 +00002976
2977 return 0;
2978 }
2979
Anton Korobeynikov2365f512007-07-14 14:06:15 +00002980 case Intrinsic::eh_return: {
2981 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
2982
Dale Johannesen1532f3d2008-04-02 00:25:04 +00002983 if (MMI) {
Anton Korobeynikov2365f512007-07-14 14:06:15 +00002984 MMI->setCallsEHReturn(true);
2985 DAG.setRoot(DAG.getNode(ISD::EH_RETURN,
2986 MVT::Other,
Dan Gohman86e1ebf2008-03-27 19:56:19 +00002987 getControlRoot(),
Anton Korobeynikov2365f512007-07-14 14:06:15 +00002988 getValue(I.getOperand(1)),
2989 getValue(I.getOperand(2))));
2990 } else {
2991 setValue(&I, DAG.getConstant(0, TLI.getPointerTy()));
2992 }
2993
2994 return 0;
2995 }
2996
2997 case Intrinsic::eh_unwind_init: {
2998 if (MachineModuleInfo *MMI = DAG.getMachineModuleInfo()) {
2999 MMI->setCallsUnwindInit(true);
3000 }
3001
3002 return 0;
3003 }
3004
3005 case Intrinsic::eh_dwarf_cfa: {
Dale Johannesen1532f3d2008-04-02 00:25:04 +00003006 MVT::ValueType VT = getValue(I.getOperand(1)).getValueType();
3007 SDOperand CfaArg;
3008 if (MVT::getSizeInBits(VT) > MVT::getSizeInBits(TLI.getPointerTy()))
3009 CfaArg = DAG.getNode(ISD::TRUNCATE,
3010 TLI.getPointerTy(), getValue(I.getOperand(1)));
3011 else
3012 CfaArg = DAG.getNode(ISD::SIGN_EXTEND,
3013 TLI.getPointerTy(), getValue(I.getOperand(1)));
Anton Korobeynikov2365f512007-07-14 14:06:15 +00003014
Dale Johannesen1532f3d2008-04-02 00:25:04 +00003015 SDOperand Offset = DAG.getNode(ISD::ADD,
3016 TLI.getPointerTy(),
3017 DAG.getNode(ISD::FRAME_TO_ARGS_OFFSET,
3018 TLI.getPointerTy()),
3019 CfaArg);
3020 setValue(&I, DAG.getNode(ISD::ADD,
3021 TLI.getPointerTy(),
3022 DAG.getNode(ISD::FRAMEADDR,
3023 TLI.getPointerTy(),
3024 DAG.getConstant(0,
3025 TLI.getPointerTy())),
3026 Offset));
Anton Korobeynikov2365f512007-07-14 14:06:15 +00003027 return 0;
3028 }
3029
Dale Johannesen9ab7fb32007-10-02 17:43:59 +00003030 case Intrinsic::sqrt:
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003031 setValue(&I, DAG.getNode(ISD::FSQRT,
3032 getValue(I.getOperand(1)).getValueType(),
3033 getValue(I.getOperand(1))));
3034 return 0;
Dale Johannesen9ab7fb32007-10-02 17:43:59 +00003035 case Intrinsic::powi:
Chris Lattner6ddf8ed2006-09-09 06:03:30 +00003036 setValue(&I, DAG.getNode(ISD::FPOWI,
3037 getValue(I.getOperand(1)).getValueType(),
3038 getValue(I.getOperand(1)),
3039 getValue(I.getOperand(2))));
3040 return 0;
Dan Gohmanac9385a2007-10-12 00:01:22 +00003041 case Intrinsic::sin:
3042 setValue(&I, DAG.getNode(ISD::FSIN,
3043 getValue(I.getOperand(1)).getValueType(),
3044 getValue(I.getOperand(1))));
3045 return 0;
3046 case Intrinsic::cos:
3047 setValue(&I, DAG.getNode(ISD::FCOS,
3048 getValue(I.getOperand(1)).getValueType(),
3049 getValue(I.getOperand(1))));
3050 return 0;
3051 case Intrinsic::pow:
3052 setValue(&I, DAG.getNode(ISD::FPOW,
3053 getValue(I.getOperand(1)).getValueType(),
3054 getValue(I.getOperand(1)),
3055 getValue(I.getOperand(2))));
3056 return 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003057 case Intrinsic::pcmarker: {
3058 SDOperand Tmp = getValue(I.getOperand(1));
3059 DAG.setRoot(DAG.getNode(ISD::PCMARKER, MVT::Other, getRoot(), Tmp));
3060 return 0;
3061 }
Andrew Lenharth8b91c772005-11-11 22:48:54 +00003062 case Intrinsic::readcyclecounter: {
Chris Lattnerbd564bf2006-08-08 02:23:42 +00003063 SDOperand Op = getRoot();
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00003064 SDOperand Tmp = DAG.getNode(ISD::READCYCLECOUNTER,
3065 DAG.getNodeValueTypes(MVT::i64, MVT::Other), 2,
3066 &Op, 1);
Andrew Lenharth8b91c772005-11-11 22:48:54 +00003067 setValue(&I, Tmp);
3068 DAG.setRoot(Tmp.getValue(1));
Andrew Lenharth51b8d542005-11-11 16:47:30 +00003069 return 0;
Andrew Lenharth8b91c772005-11-11 22:48:54 +00003070 }
Chris Lattnerc6eb6d72007-04-10 03:20:39 +00003071 case Intrinsic::part_select: {
Reid Spencer3f108cb2007-04-05 01:20:18 +00003072 // Currently not implemented: just abort
Reid Spencerf75b8742007-04-12 02:48:46 +00003073 assert(0 && "part_select intrinsic not implemented");
3074 abort();
3075 }
3076 case Intrinsic::part_set: {
3077 // Currently not implemented: just abort
3078 assert(0 && "part_set intrinsic not implemented");
Reid Spencer3f108cb2007-04-05 01:20:18 +00003079 abort();
Reid Spenceraddd11d2007-04-04 23:48:25 +00003080 }
Reid Spencera4f9c4d2007-04-01 07:34:11 +00003081 case Intrinsic::bswap:
Nate Begemand88fc032006-01-14 03:14:10 +00003082 setValue(&I, DAG.getNode(ISD::BSWAP,
3083 getValue(I.getOperand(1)).getValueType(),
3084 getValue(I.getOperand(1))));
3085 return 0;
Reid Spencera4f9c4d2007-04-01 07:34:11 +00003086 case Intrinsic::cttz: {
3087 SDOperand Arg = getValue(I.getOperand(1));
3088 MVT::ValueType Ty = Arg.getValueType();
3089 SDOperand result = DAG.getNode(ISD::CTTZ, Ty, Arg);
Reid Spencera4f9c4d2007-04-01 07:34:11 +00003090 setValue(&I, result);
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003091 return 0;
Reid Spencera4f9c4d2007-04-01 07:34:11 +00003092 }
3093 case Intrinsic::ctlz: {
3094 SDOperand Arg = getValue(I.getOperand(1));
3095 MVT::ValueType Ty = Arg.getValueType();
3096 SDOperand result = DAG.getNode(ISD::CTLZ, Ty, Arg);
Reid Spencera4f9c4d2007-04-01 07:34:11 +00003097 setValue(&I, result);
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003098 return 0;
Reid Spencera4f9c4d2007-04-01 07:34:11 +00003099 }
3100 case Intrinsic::ctpop: {
3101 SDOperand Arg = getValue(I.getOperand(1));
3102 MVT::ValueType Ty = Arg.getValueType();
3103 SDOperand result = DAG.getNode(ISD::CTPOP, Ty, Arg);
Reid Spencera4f9c4d2007-04-01 07:34:11 +00003104 setValue(&I, result);
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003105 return 0;
Reid Spencera4f9c4d2007-04-01 07:34:11 +00003106 }
Chris Lattner140d53c2006-01-13 02:50:02 +00003107 case Intrinsic::stacksave: {
Chris Lattnerbd564bf2006-08-08 02:23:42 +00003108 SDOperand Op = getRoot();
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00003109 SDOperand Tmp = DAG.getNode(ISD::STACKSAVE,
3110 DAG.getNodeValueTypes(TLI.getPointerTy(), MVT::Other), 2, &Op, 1);
Chris Lattner140d53c2006-01-13 02:50:02 +00003111 setValue(&I, Tmp);
3112 DAG.setRoot(Tmp.getValue(1));
3113 return 0;
3114 }
Chris Lattner39a17dd2006-01-23 05:22:07 +00003115 case Intrinsic::stackrestore: {
3116 SDOperand Tmp = getValue(I.getOperand(1));
3117 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, MVT::Other, getRoot(), Tmp));
Chris Lattner140d53c2006-01-13 02:50:02 +00003118 return 0;
Chris Lattner39a17dd2006-01-23 05:22:07 +00003119 }
Tanya Lattner24e5aad2007-06-15 22:26:58 +00003120 case Intrinsic::var_annotation:
3121 // Discard annotate attributes
3122 return 0;
Duncan Sands36397f52007-07-27 12:58:54 +00003123
Duncan Sands36397f52007-07-27 12:58:54 +00003124 case Intrinsic::init_trampoline: {
3125 const Function *F =
3126 cast<Function>(IntrinsicInst::StripPointerCasts(I.getOperand(2)));
3127
3128 SDOperand Ops[6];
3129 Ops[0] = getRoot();
3130 Ops[1] = getValue(I.getOperand(1));
3131 Ops[2] = getValue(I.getOperand(2));
3132 Ops[3] = getValue(I.getOperand(3));
3133 Ops[4] = DAG.getSrcValue(I.getOperand(1));
3134 Ops[5] = DAG.getSrcValue(F);
3135
Duncan Sandsf7331b32007-09-11 14:10:23 +00003136 SDOperand Tmp = DAG.getNode(ISD::TRAMPOLINE,
3137 DAG.getNodeValueTypes(TLI.getPointerTy(),
3138 MVT::Other), 2,
3139 Ops, 6);
3140
3141 setValue(&I, Tmp);
3142 DAG.setRoot(Tmp.getValue(1));
Duncan Sands36397f52007-07-27 12:58:54 +00003143 return 0;
3144 }
Gordon Henriksence224772008-01-07 01:30:38 +00003145
3146 case Intrinsic::gcroot:
3147 if (GCI) {
3148 Value *Alloca = I.getOperand(1);
3149 Constant *TypeMap = cast<Constant>(I.getOperand(2));
3150
3151 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).Val);
3152 GCI->addStackRoot(FI->getIndex(), TypeMap);
3153 }
3154 return 0;
3155
3156 case Intrinsic::gcread:
3157 case Intrinsic::gcwrite:
3158 assert(0 && "Collector failed to lower gcread/gcwrite intrinsics!");
3159 return 0;
3160
Anton Korobeynikov917c2a62007-11-15 23:25:33 +00003161 case Intrinsic::flt_rounds: {
Dan Gohman1a024862008-01-31 00:41:03 +00003162 setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, MVT::i32));
Anton Korobeynikov917c2a62007-11-15 23:25:33 +00003163 return 0;
3164 }
Anton Korobeynikov66fac792008-01-15 07:02:33 +00003165
3166 case Intrinsic::trap: {
3167 DAG.setRoot(DAG.getNode(ISD::TRAP, MVT::Other, getRoot()));
3168 return 0;
3169 }
Evan Cheng27b7db52008-03-08 00:58:38 +00003170 case Intrinsic::prefetch: {
3171 SDOperand Ops[4];
3172 Ops[0] = getRoot();
3173 Ops[1] = getValue(I.getOperand(1));
3174 Ops[2] = getValue(I.getOperand(2));
3175 Ops[3] = getValue(I.getOperand(3));
3176 DAG.setRoot(DAG.getNode(ISD::PREFETCH, MVT::Other, &Ops[0], 4));
3177 return 0;
3178 }
3179
Andrew Lenharth22c5c1b2008-02-16 01:24:58 +00003180 case Intrinsic::memory_barrier: {
3181 SDOperand Ops[6];
3182 Ops[0] = getRoot();
3183 for (int x = 1; x < 6; ++x)
3184 Ops[x] = getValue(I.getOperand(x));
3185
3186 DAG.setRoot(DAG.getNode(ISD::MEMBARRIER, MVT::Other, &Ops[0], 6));
3187 return 0;
3188 }
Andrew Lenharthab0b9492008-02-21 06:45:13 +00003189 case Intrinsic::atomic_lcs: {
3190 SDOperand Root = getRoot();
3191 SDOperand O3 = getValue(I.getOperand(3));
3192 SDOperand L = DAG.getAtomic(ISD::ATOMIC_LCS, Root,
3193 getValue(I.getOperand(1)),
3194 getValue(I.getOperand(2)),
3195 O3, O3.getValueType());
3196 setValue(&I, L);
3197 DAG.setRoot(L.getValue(1));
3198 return 0;
3199 }
3200 case Intrinsic::atomic_las: {
3201 SDOperand Root = getRoot();
3202 SDOperand O2 = getValue(I.getOperand(2));
3203 SDOperand L = DAG.getAtomic(ISD::ATOMIC_LAS, Root,
3204 getValue(I.getOperand(1)),
3205 O2, O2.getValueType());
3206 setValue(&I, L);
3207 DAG.setRoot(L.getValue(1));
3208 return 0;
3209 }
3210 case Intrinsic::atomic_swap: {
3211 SDOperand Root = getRoot();
3212 SDOperand O2 = getValue(I.getOperand(2));
3213 SDOperand L = DAG.getAtomic(ISD::ATOMIC_SWAP, Root,
3214 getValue(I.getOperand(1)),
3215 O2, O2.getValueType());
3216 setValue(&I, L);
3217 DAG.setRoot(L.getValue(1));
3218 return 0;
3219 }
3220
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003221 }
3222}
3223
3224
Duncan Sands6f74b482007-12-19 09:48:52 +00003225void SelectionDAGLowering::LowerCallTo(CallSite CS, SDOperand Callee,
Jim Laskey1da20a72007-02-23 21:45:01 +00003226 bool IsTailCall,
Anton Korobeynikov070280e2007-05-23 11:08:31 +00003227 MachineBasicBlock *LandingPad) {
Duncan Sands6f74b482007-12-19 09:48:52 +00003228 const PointerType *PT = cast<PointerType>(CS.getCalledValue()->getType());
Jim Laskey735b6f82007-02-22 15:38:06 +00003229 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
Anton Korobeynikov070280e2007-05-23 11:08:31 +00003230 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3231 unsigned BeginLabel = 0, EndLabel = 0;
Duncan Sands6f74b482007-12-19 09:48:52 +00003232
Jim Laskey735b6f82007-02-22 15:38:06 +00003233 TargetLowering::ArgListTy Args;
3234 TargetLowering::ArgListEntry Entry;
Duncan Sands6f74b482007-12-19 09:48:52 +00003235 Args.reserve(CS.arg_size());
3236 for (CallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
3237 i != e; ++i) {
3238 SDOperand ArgNode = getValue(*i);
3239 Entry.Node = ArgNode; Entry.Ty = (*i)->getType();
Duncan Sands4fee7032007-05-07 20:49:28 +00003240
Duncan Sands6f74b482007-12-19 09:48:52 +00003241 unsigned attrInd = i - CS.arg_begin() + 1;
3242 Entry.isSExt = CS.paramHasAttr(attrInd, ParamAttr::SExt);
3243 Entry.isZExt = CS.paramHasAttr(attrInd, ParamAttr::ZExt);
3244 Entry.isInReg = CS.paramHasAttr(attrInd, ParamAttr::InReg);
3245 Entry.isSRet = CS.paramHasAttr(attrInd, ParamAttr::StructRet);
3246 Entry.isNest = CS.paramHasAttr(attrInd, ParamAttr::Nest);
3247 Entry.isByVal = CS.paramHasAttr(attrInd, ParamAttr::ByVal);
Dale Johannesen08e78b12008-02-22 17:49:45 +00003248 Entry.Alignment = CS.getParamAlignment(attrInd);
Jim Laskey735b6f82007-02-22 15:38:06 +00003249 Args.push_back(Entry);
3250 }
3251
Dale Johannesen1532f3d2008-04-02 00:25:04 +00003252 if (LandingPad && MMI) {
Anton Korobeynikov070280e2007-05-23 11:08:31 +00003253 // Insert a label before the invoke call to mark the try range. This can be
3254 // used to detect deletion of the invoke via the MachineModuleInfo.
3255 BeginLabel = MMI->NextLabelID();
Dale Johannesena4091d32008-04-04 23:48:31 +00003256 // Both PendingLoads and PendingExports must be flushed here;
3257 // this call might not return.
3258 (void)getRoot();
3259 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, getControlRoot(),
Evan Chengbb81d972008-01-31 09:59:15 +00003260 DAG.getConstant(BeginLabel, MVT::i32),
3261 DAG.getConstant(1, MVT::i32)));
Anton Korobeynikov070280e2007-05-23 11:08:31 +00003262 }
Duncan Sands6f74b482007-12-19 09:48:52 +00003263
Jim Laskey735b6f82007-02-22 15:38:06 +00003264 std::pair<SDOperand,SDOperand> Result =
Duncan Sands6f74b482007-12-19 09:48:52 +00003265 TLI.LowerCallTo(getRoot(), CS.getType(),
3266 CS.paramHasAttr(0, ParamAttr::SExt),
Duncan Sands00fee652008-02-14 17:28:50 +00003267 CS.paramHasAttr(0, ParamAttr::ZExt),
Duncan Sands6f74b482007-12-19 09:48:52 +00003268 FTy->isVarArg(), CS.getCallingConv(), IsTailCall,
Jim Laskey735b6f82007-02-22 15:38:06 +00003269 Callee, Args, DAG);
Duncan Sands6f74b482007-12-19 09:48:52 +00003270 if (CS.getType() != Type::VoidTy)
3271 setValue(CS.getInstruction(), Result.first);
Jim Laskey735b6f82007-02-22 15:38:06 +00003272 DAG.setRoot(Result.second);
Anton Korobeynikov070280e2007-05-23 11:08:31 +00003273
Dale Johannesen1532f3d2008-04-02 00:25:04 +00003274 if (LandingPad && MMI) {
Anton Korobeynikov070280e2007-05-23 11:08:31 +00003275 // Insert a label at the end of the invoke call to mark the try range. This
3276 // can be used to detect deletion of the invoke via the MachineModuleInfo.
3277 EndLabel = MMI->NextLabelID();
3278 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, getRoot(),
Evan Chengbb81d972008-01-31 09:59:15 +00003279 DAG.getConstant(EndLabel, MVT::i32),
3280 DAG.getConstant(1, MVT::i32)));
Anton Korobeynikov070280e2007-05-23 11:08:31 +00003281
Duncan Sands6f74b482007-12-19 09:48:52 +00003282 // Inform MachineModuleInfo of range.
Anton Korobeynikov070280e2007-05-23 11:08:31 +00003283 MMI->addInvoke(LandingPad, BeginLabel, EndLabel);
3284 }
Jim Laskey735b6f82007-02-22 15:38:06 +00003285}
3286
3287
Chris Lattner1c08c712005-01-07 07:47:53 +00003288void SelectionDAGLowering::visitCall(CallInst &I) {
Chris Lattner64e14b12005-01-08 22:48:57 +00003289 const char *RenameFn = 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003290 if (Function *F = I.getCalledFunction()) {
Chris Lattner87b51bc2007-09-10 21:15:22 +00003291 if (F->isDeclaration()) {
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003292 if (unsigned IID = F->getIntrinsicID()) {
3293 RenameFn = visitIntrinsicCall(I, IID);
3294 if (!RenameFn)
3295 return;
Chris Lattner87b51bc2007-09-10 21:15:22 +00003296 }
3297 }
3298
3299 // Check for well-known libc/libm calls. If the function is internal, it
3300 // can't be a library call.
3301 unsigned NameLen = F->getNameLen();
3302 if (!F->hasInternalLinkage() && NameLen) {
3303 const char *NameStr = F->getNameStart();
3304 if (NameStr[0] == 'c' &&
3305 ((NameLen == 8 && !strcmp(NameStr, "copysign")) ||
3306 (NameLen == 9 && !strcmp(NameStr, "copysignf")))) {
3307 if (I.getNumOperands() == 3 && // Basic sanity checks.
3308 I.getOperand(1)->getType()->isFloatingPoint() &&
3309 I.getType() == I.getOperand(1)->getType() &&
3310 I.getType() == I.getOperand(2)->getType()) {
3311 SDOperand LHS = getValue(I.getOperand(1));
3312 SDOperand RHS = getValue(I.getOperand(2));
3313 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, LHS.getValueType(),
3314 LHS, RHS));
3315 return;
3316 }
3317 } else if (NameStr[0] == 'f' &&
3318 ((NameLen == 4 && !strcmp(NameStr, "fabs")) ||
Dale Johannesen2f429012007-09-26 21:10:55 +00003319 (NameLen == 5 && !strcmp(NameStr, "fabsf")) ||
3320 (NameLen == 5 && !strcmp(NameStr, "fabsl")))) {
Chris Lattner87b51bc2007-09-10 21:15:22 +00003321 if (I.getNumOperands() == 2 && // Basic sanity checks.
3322 I.getOperand(1)->getType()->isFloatingPoint() &&
3323 I.getType() == I.getOperand(1)->getType()) {
3324 SDOperand Tmp = getValue(I.getOperand(1));
3325 setValue(&I, DAG.getNode(ISD::FABS, Tmp.getValueType(), Tmp));
3326 return;
3327 }
3328 } else if (NameStr[0] == 's' &&
3329 ((NameLen == 3 && !strcmp(NameStr, "sin")) ||
Dale Johannesen2f429012007-09-26 21:10:55 +00003330 (NameLen == 4 && !strcmp(NameStr, "sinf")) ||
3331 (NameLen == 4 && !strcmp(NameStr, "sinl")))) {
Chris Lattner87b51bc2007-09-10 21:15:22 +00003332 if (I.getNumOperands() == 2 && // Basic sanity checks.
3333 I.getOperand(1)->getType()->isFloatingPoint() &&
3334 I.getType() == I.getOperand(1)->getType()) {
3335 SDOperand Tmp = getValue(I.getOperand(1));
3336 setValue(&I, DAG.getNode(ISD::FSIN, Tmp.getValueType(), Tmp));
3337 return;
3338 }
3339 } else if (NameStr[0] == 'c' &&
3340 ((NameLen == 3 && !strcmp(NameStr, "cos")) ||
Dale Johannesen2f429012007-09-26 21:10:55 +00003341 (NameLen == 4 && !strcmp(NameStr, "cosf")) ||
3342 (NameLen == 4 && !strcmp(NameStr, "cosl")))) {
Chris Lattner87b51bc2007-09-10 21:15:22 +00003343 if (I.getNumOperands() == 2 && // Basic sanity checks.
3344 I.getOperand(1)->getType()->isFloatingPoint() &&
3345 I.getType() == I.getOperand(1)->getType()) {
3346 SDOperand Tmp = getValue(I.getOperand(1));
3347 setValue(&I, DAG.getNode(ISD::FCOS, Tmp.getValueType(), Tmp));
3348 return;
Chris Lattnerf76e7dc2005-04-30 04:43:14 +00003349 }
Chris Lattner1ca85d52005-05-14 13:56:55 +00003350 }
Chris Lattner87b51bc2007-09-10 21:15:22 +00003351 }
Chris Lattnerce7518c2006-01-26 22:24:51 +00003352 } else if (isa<InlineAsm>(I.getOperand(0))) {
Duncan Sandsfd7b3262007-12-17 18:08:19 +00003353 visitInlineAsm(&I);
Chris Lattnerce7518c2006-01-26 22:24:51 +00003354 return;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00003355 }
Misha Brukmanedf128a2005-04-21 22:36:52 +00003356
Chris Lattner64e14b12005-01-08 22:48:57 +00003357 SDOperand Callee;
3358 if (!RenameFn)
3359 Callee = getValue(I.getOperand(0));
3360 else
3361 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
Anton Korobeynikov070280e2007-05-23 11:08:31 +00003362
Duncan Sands6f74b482007-12-19 09:48:52 +00003363 LowerCallTo(&I, Callee, I.isTailCall());
Chris Lattner1c08c712005-01-07 07:47:53 +00003364}
3365
Jim Laskey735b6f82007-02-22 15:38:06 +00003366
Dan Gohmanef5d1942008-03-11 21:11:25 +00003367void SelectionDAGLowering::visitGetResult(GetResultInst &I) {
Dan Gohman67780f12008-04-23 20:25:16 +00003368 if (isa<UndefValue>(I.getOperand(0))) {
Dan Gohman3dc34f62008-04-23 20:21:29 +00003369 SDOperand Undef = DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType()));
3370 setValue(&I, Undef);
3371 } else {
3372 SDOperand Call = getValue(I.getOperand(0));
Dan Gohman23ce5022008-04-25 18:27:55 +00003373
3374 // To add support for individual return values with aggregate types,
3375 // we'd need a way to take a getresult index and determine which
3376 // values of the Call SDNode are associated with it.
3377 assert(TLI.getValueType(I.getType(), true) != MVT::Other &&
3378 "Individual return values must not be aggregates!");
3379
Dan Gohman3dc34f62008-04-23 20:21:29 +00003380 setValue(&I, SDOperand(Call.Val, I.getIndex()));
3381 }
Dan Gohmanef5d1942008-03-11 21:11:25 +00003382}
3383
3384
Dan Gohmanb6f5b002007-06-28 23:29:44 +00003385/// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
3386/// this value and returns the result as a ValueVT value. This uses
3387/// Chain/Flag as the input and updates them for the output Chain/Flag.
3388/// If the Flag pointer is NULL, no flag is used.
3389SDOperand RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
3390 SDOperand &Chain, SDOperand *Flag)const{
Dan Gohman23ce5022008-04-25 18:27:55 +00003391 // Assemble the legal parts into the final values.
3392 SmallVector<SDOperand, 4> Values(ValueVTs.size());
3393 for (unsigned Value = 0, Part = 0; Value != ValueVTs.size(); ++Value) {
3394 // Copy the legal parts from the registers.
3395 MVT::ValueType ValueVT = ValueVTs[Value];
3396 unsigned NumRegs = TLI->getNumRegisters(ValueVT);
3397 MVT::ValueType RegisterVT = RegVTs[Value];
3398
3399 SmallVector<SDOperand, 8> Parts(NumRegs);
3400 for (unsigned i = 0; i != NumRegs; ++i) {
3401 SDOperand P = Flag ?
3402 DAG.getCopyFromReg(Chain, Regs[Part+i], RegisterVT, *Flag) :
3403 DAG.getCopyFromReg(Chain, Regs[Part+i], RegisterVT);
3404 Chain = P.getValue(1);
3405 if (Flag)
3406 *Flag = P.getValue(2);
3407 Parts[Part+i] = P;
3408 }
Chris Lattner5df99b32007-03-25 05:00:54 +00003409
Dan Gohman23ce5022008-04-25 18:27:55 +00003410 Values[Value] = getCopyFromParts(DAG, &Parts[Part], NumRegs, RegisterVT,
3411 ValueVT);
3412 Part += NumRegs;
3413 }
3414 return DAG.getNode(ISD::MERGE_VALUES,
3415 DAG.getVTList(&ValueVTs[0], ValueVTs.size()),
3416 &Values[0], ValueVTs.size());
Chris Lattner864635a2006-02-22 22:37:12 +00003417}
3418
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00003419/// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
3420/// specified value into the registers specified by this object. This uses
3421/// Chain/Flag as the input and updates them for the output Chain/Flag.
Dan Gohmanb6f5b002007-06-28 23:29:44 +00003422/// If the Flag pointer is NULL, no flag is used.
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00003423void RegsForValue::getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
Dan Gohmanb6f5b002007-06-28 23:29:44 +00003424 SDOperand &Chain, SDOperand *Flag) const {
Dan Gohmanb6f5b002007-06-28 23:29:44 +00003425 // Get the list of the values's legal parts.
Dan Gohman23ce5022008-04-25 18:27:55 +00003426 unsigned NumRegs = Regs.size();
3427 SmallVector<SDOperand, 8> Parts(NumRegs);
3428 for (unsigned Value = 0, Part = 0; Value != ValueVTs.size(); ++Value) {
3429 MVT::ValueType ValueVT = ValueVTs[Value];
3430 unsigned NumParts = TLI->getNumRegisters(ValueVT);
3431 MVT::ValueType RegisterVT = RegVTs[Value];
3432
3433 getCopyToParts(DAG, Val.getValue(Val.ResNo + Value),
3434 &Parts[Part], NumParts, RegisterVT);
3435 Part += NumParts;
3436 }
Dan Gohmanb6f5b002007-06-28 23:29:44 +00003437
3438 // Copy the parts into the registers.
Dan Gohman23ce5022008-04-25 18:27:55 +00003439 SmallVector<SDOperand, 8> Chains(NumRegs);
3440 for (unsigned i = 0; i != NumRegs; ++i) {
Dan Gohmanb6f5b002007-06-28 23:29:44 +00003441 SDOperand Part = Flag ?
Dan Gohman532dc2e2007-07-09 20:59:04 +00003442 DAG.getCopyToReg(Chain, Regs[i], Parts[i], *Flag) :
3443 DAG.getCopyToReg(Chain, Regs[i], Parts[i]);
Dan Gohman23ce5022008-04-25 18:27:55 +00003444 Chains[i] = Part.getValue(0);
Dan Gohmanb6f5b002007-06-28 23:29:44 +00003445 if (Flag)
3446 *Flag = Part.getValue(1);
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00003447 }
Dan Gohman23ce5022008-04-25 18:27:55 +00003448 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other, &Chains[0], NumRegs);
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00003449}
Chris Lattner864635a2006-02-22 22:37:12 +00003450
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00003451/// AddInlineAsmOperands - Add this value to the specified inlineasm node
3452/// operand list. This adds the code marker and includes the number of
3453/// values added into it.
3454void RegsForValue::AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
Chris Lattner9f6637d2006-02-23 20:06:57 +00003455 std::vector<SDOperand> &Ops) const {
Chris Lattner4b993b12007-04-09 00:33:58 +00003456 MVT::ValueType IntPtrTy = DAG.getTargetLoweringInfo().getPointerTy();
3457 Ops.push_back(DAG.getTargetConstant(Code | (Regs.size() << 3), IntPtrTy));
Dan Gohman23ce5022008-04-25 18:27:55 +00003458 for (unsigned Value = 0, Reg = 0; Value != ValueVTs.size(); ++Value) {
3459 MVT::ValueType ValueVT = ValueVTs[Value];
3460 unsigned NumRegs = TLI->getNumRegisters(ValueVT);
3461 MVT::ValueType RegisterVT = RegVTs[Value];
3462 for (unsigned i = 0; i != NumRegs; ++i) {
3463 SDOperand RegOp = DAG.getRegister(Regs[Reg+i], RegisterVT);
3464 Ops.push_back(RegOp);
3465 }
3466 Reg += NumRegs;
3467 }
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00003468}
Chris Lattner864635a2006-02-22 22:37:12 +00003469
3470/// isAllocatableRegister - If the specified register is safe to allocate,
3471/// i.e. it isn't a stack pointer or some other special register, return the
3472/// register class for the register. Otherwise, return null.
3473static const TargetRegisterClass *
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00003474isAllocatableRegister(unsigned Reg, MachineFunction &MF,
Dan Gohman6f0d0242008-02-10 18:45:23 +00003475 const TargetLowering &TLI,
3476 const TargetRegisterInfo *TRI) {
Chris Lattnerf8814cf2006-04-02 00:24:45 +00003477 MVT::ValueType FoundVT = MVT::Other;
3478 const TargetRegisterClass *FoundRC = 0;
Dan Gohman6f0d0242008-02-10 18:45:23 +00003479 for (TargetRegisterInfo::regclass_iterator RCI = TRI->regclass_begin(),
3480 E = TRI->regclass_end(); RCI != E; ++RCI) {
Chris Lattnerf8814cf2006-04-02 00:24:45 +00003481 MVT::ValueType ThisVT = MVT::Other;
3482
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00003483 const TargetRegisterClass *RC = *RCI;
3484 // If none of the the value types for this register class are valid, we
3485 // can't use it. For example, 64-bit reg classes on 32-bit targets.
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00003486 for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
3487 I != E; ++I) {
3488 if (TLI.isTypeLegal(*I)) {
Chris Lattnerf8814cf2006-04-02 00:24:45 +00003489 // If we have already found this register in a different register class,
3490 // choose the one with the largest VT specified. For example, on
3491 // PowerPC, we favor f64 register classes over f32.
3492 if (FoundVT == MVT::Other ||
3493 MVT::getSizeInBits(FoundVT) < MVT::getSizeInBits(*I)) {
3494 ThisVT = *I;
3495 break;
3496 }
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00003497 }
3498 }
3499
Chris Lattnerf8814cf2006-04-02 00:24:45 +00003500 if (ThisVT == MVT::Other) continue;
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00003501
Chris Lattner864635a2006-02-22 22:37:12 +00003502 // NOTE: This isn't ideal. In particular, this might allocate the
3503 // frame pointer in functions that need it (due to them not being taken
3504 // out of allocation, because a variable sized allocation hasn't been seen
3505 // yet). This is a slight code pessimization, but should still work.
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00003506 for (TargetRegisterClass::iterator I = RC->allocation_order_begin(MF),
3507 E = RC->allocation_order_end(MF); I != E; ++I)
Chris Lattnerf8814cf2006-04-02 00:24:45 +00003508 if (*I == Reg) {
3509 // We found a matching register class. Keep looking at others in case
3510 // we find one with larger registers that this physreg is also in.
3511 FoundRC = RC;
3512 FoundVT = ThisVT;
3513 break;
3514 }
Chris Lattner4e4b5762006-02-01 18:59:47 +00003515 }
Chris Lattnerf8814cf2006-04-02 00:24:45 +00003516 return FoundRC;
Chris Lattner864635a2006-02-22 22:37:12 +00003517}
3518
Chris Lattner4e4b5762006-02-01 18:59:47 +00003519
Chris Lattner0c583402007-04-28 20:49:53 +00003520namespace {
3521/// AsmOperandInfo - This contains information for each constraint that we are
3522/// lowering.
Evan Cheng5c807602008-02-26 02:33:44 +00003523struct SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo {
3524 /// CallOperand - If this is the result output operand or a clobber
3525 /// this is null, otherwise it is the incoming operand to the CallInst.
3526 /// This gets modified as the asm is processed.
Chris Lattner0c583402007-04-28 20:49:53 +00003527 SDOperand CallOperand;
Evan Cheng5c807602008-02-26 02:33:44 +00003528
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003529 /// AssignedRegs - If this is a register or register class operand, this
3530 /// contains the set of register corresponding to the operand.
3531 RegsForValue AssignedRegs;
3532
Dan Gohman23ce5022008-04-25 18:27:55 +00003533 explicit SDISelAsmOperandInfo(const InlineAsm::ConstraintInfo &info)
Evan Cheng5c807602008-02-26 02:33:44 +00003534 : TargetLowering::AsmOperandInfo(info), CallOperand(0,0) {
Chris Lattner0c583402007-04-28 20:49:53 +00003535 }
Chris Lattner3ff90dc2007-04-30 17:16:27 +00003536
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003537 /// MarkAllocatedRegs - Once AssignedRegs is set, mark the assigned registers
3538 /// busy in OutputRegs/InputRegs.
3539 void MarkAllocatedRegs(bool isOutReg, bool isInReg,
3540 std::set<unsigned> &OutputRegs,
Chris Lattner7cbeb242008-02-21 04:55:52 +00003541 std::set<unsigned> &InputRegs,
3542 const TargetRegisterInfo &TRI) const {
3543 if (isOutReg) {
3544 for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i)
3545 MarkRegAndAliases(AssignedRegs.Regs[i], OutputRegs, TRI);
3546 }
3547 if (isInReg) {
3548 for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i)
3549 MarkRegAndAliases(AssignedRegs.Regs[i], InputRegs, TRI);
3550 }
3551 }
3552
3553private:
3554 /// MarkRegAndAliases - Mark the specified register and all aliases in the
3555 /// specified set.
3556 static void MarkRegAndAliases(unsigned Reg, std::set<unsigned> &Regs,
3557 const TargetRegisterInfo &TRI) {
3558 assert(TargetRegisterInfo::isPhysicalRegister(Reg) && "Isn't a physreg");
3559 Regs.insert(Reg);
3560 if (const unsigned *Aliases = TRI.getAliasSet(Reg))
3561 for (; *Aliases; ++Aliases)
3562 Regs.insert(*Aliases);
3563 }
Chris Lattner0c583402007-04-28 20:49:53 +00003564};
3565} // end anon namespace.
Chris Lattner864635a2006-02-22 22:37:12 +00003566
Chris Lattner3ff90dc2007-04-30 17:16:27 +00003567
Chris Lattner0fe71e92008-02-21 19:43:13 +00003568/// GetRegistersForValue - Assign registers (virtual or physical) for the
3569/// specified operand. We prefer to assign virtual registers, to allow the
3570/// register allocator handle the assignment process. However, if the asm uses
3571/// features that we can't model on machineinstrs, we have SDISel do the
3572/// allocation. This produces generally horrible, but correct, code.
3573///
3574/// OpInfo describes the operand.
3575/// HasEarlyClobber is true if there are any early clobber constraints (=&r)
3576/// or any explicitly clobbered registers.
3577/// Input and OutputRegs are the set of already allocated physical registers.
3578///
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003579void SelectionDAGLowering::
Evan Cheng5c807602008-02-26 02:33:44 +00003580GetRegistersForValue(SDISelAsmOperandInfo &OpInfo, bool HasEarlyClobber,
Chris Lattnerbf996f12007-04-30 17:29:31 +00003581 std::set<unsigned> &OutputRegs,
3582 std::set<unsigned> &InputRegs) {
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003583 // Compute whether this value requires an input register, an output register,
3584 // or both.
3585 bool isOutReg = false;
3586 bool isInReg = false;
3587 switch (OpInfo.Type) {
3588 case InlineAsm::isOutput:
3589 isOutReg = true;
3590
3591 // If this is an early-clobber output, or if there is an input
3592 // constraint that matches this, we need to reserve the input register
3593 // so no other inputs allocate to it.
3594 isInReg = OpInfo.isEarlyClobber || OpInfo.hasMatchingInput;
3595 break;
3596 case InlineAsm::isInput:
3597 isInReg = true;
3598 isOutReg = false;
3599 break;
3600 case InlineAsm::isClobber:
3601 isOutReg = true;
3602 isInReg = true;
3603 break;
3604 }
3605
3606
3607 MachineFunction &MF = DAG.getMachineFunction();
Chris Lattnerb606dba2008-04-28 06:44:42 +00003608 SmallVector<unsigned, 4> Regs;
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003609
3610 // If this is a constraint for a single physreg, or a constraint for a
3611 // register class, find it.
3612 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
3613 TLI.getRegForInlineAsmConstraint(OpInfo.ConstraintCode,
3614 OpInfo.ConstraintVT);
Chris Lattnerbf996f12007-04-30 17:29:31 +00003615
3616 unsigned NumRegs = 1;
3617 if (OpInfo.ConstraintVT != MVT::Other)
Dan Gohmanb9f10192007-06-21 14:42:22 +00003618 NumRegs = TLI.getNumRegisters(OpInfo.ConstraintVT);
Chris Lattnerbf996f12007-04-30 17:29:31 +00003619 MVT::ValueType RegVT;
3620 MVT::ValueType ValueVT = OpInfo.ConstraintVT;
3621
Chris Lattnerbf996f12007-04-30 17:29:31 +00003622
3623 // If this is a constraint for a specific physical register, like {r17},
3624 // assign it now.
3625 if (PhysReg.first) {
3626 if (OpInfo.ConstraintVT == MVT::Other)
3627 ValueVT = *PhysReg.second->vt_begin();
3628
3629 // Get the actual register value type. This is important, because the user
3630 // may have asked for (e.g.) the AX register in i32 type. We need to
3631 // remember that AX is actually i16 to get the right extension.
3632 RegVT = *PhysReg.second->vt_begin();
3633
3634 // This is a explicit reference to a physical register.
3635 Regs.push_back(PhysReg.first);
3636
3637 // If this is an expanded reference, add the rest of the regs to Regs.
3638 if (NumRegs != 1) {
3639 TargetRegisterClass::iterator I = PhysReg.second->begin();
3640 TargetRegisterClass::iterator E = PhysReg.second->end();
3641 for (; *I != PhysReg.first; ++I)
3642 assert(I != E && "Didn't find reg!");
3643
3644 // Already added the first reg.
3645 --NumRegs; ++I;
3646 for (; NumRegs; --NumRegs, ++I) {
3647 assert(I != E && "Ran out of registers to allocate!");
3648 Regs.push_back(*I);
3649 }
3650 }
Dan Gohman23ce5022008-04-25 18:27:55 +00003651 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, RegVT, ValueVT);
Chris Lattner7cbeb242008-02-21 04:55:52 +00003652 const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
3653 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TRI);
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003654 return;
Chris Lattnerbf996f12007-04-30 17:29:31 +00003655 }
3656
3657 // Otherwise, if this was a reference to an LLVM register class, create vregs
3658 // for this reference.
3659 std::vector<unsigned> RegClassRegs;
Chris Lattnerc2c28fc2007-06-15 19:11:01 +00003660 const TargetRegisterClass *RC = PhysReg.second;
3661 if (RC) {
Chris Lattnerbf996f12007-04-30 17:29:31 +00003662 // If this is an early clobber or tied register, our regalloc doesn't know
3663 // how to maintain the constraint. If it isn't, go ahead and create vreg
3664 // and let the regalloc do the right thing.
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003665 if (!OpInfo.hasMatchingInput && !OpInfo.isEarlyClobber &&
3666 // If there is some other early clobber and this is an input register,
3667 // then we are forced to pre-allocate the input reg so it doesn't
3668 // conflict with the earlyclobber.
3669 !(OpInfo.Type == InlineAsm::isInput && HasEarlyClobber)) {
Chris Lattnerbf996f12007-04-30 17:29:31 +00003670 RegVT = *PhysReg.second->vt_begin();
3671
3672 if (OpInfo.ConstraintVT == MVT::Other)
3673 ValueVT = RegVT;
3674
3675 // Create the appropriate number of virtual registers.
Chris Lattner84bc5422007-12-31 04:13:23 +00003676 MachineRegisterInfo &RegInfo = MF.getRegInfo();
Chris Lattnerbf996f12007-04-30 17:29:31 +00003677 for (; NumRegs; --NumRegs)
Chris Lattner84bc5422007-12-31 04:13:23 +00003678 Regs.push_back(RegInfo.createVirtualRegister(PhysReg.second));
Chris Lattnerbf996f12007-04-30 17:29:31 +00003679
Dan Gohman23ce5022008-04-25 18:27:55 +00003680 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, RegVT, ValueVT);
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003681 return;
Chris Lattnerbf996f12007-04-30 17:29:31 +00003682 }
3683
3684 // Otherwise, we can't allocate it. Let the code below figure out how to
3685 // maintain these constraints.
3686 RegClassRegs.assign(PhysReg.second->begin(), PhysReg.second->end());
3687
3688 } else {
3689 // This is a reference to a register class that doesn't directly correspond
3690 // to an LLVM register class. Allocate NumRegs consecutive, available,
3691 // registers from the class.
3692 RegClassRegs = TLI.getRegClassForInlineAsmConstraint(OpInfo.ConstraintCode,
3693 OpInfo.ConstraintVT);
3694 }
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003695
Dan Gohman6f0d0242008-02-10 18:45:23 +00003696 const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
Chris Lattnerbf996f12007-04-30 17:29:31 +00003697 unsigned NumAllocated = 0;
3698 for (unsigned i = 0, e = RegClassRegs.size(); i != e; ++i) {
3699 unsigned Reg = RegClassRegs[i];
3700 // See if this register is available.
3701 if ((isOutReg && OutputRegs.count(Reg)) || // Already used.
3702 (isInReg && InputRegs.count(Reg))) { // Already used.
3703 // Make sure we find consecutive registers.
3704 NumAllocated = 0;
3705 continue;
3706 }
3707
3708 // Check to see if this register is allocatable (i.e. don't give out the
3709 // stack pointer).
Chris Lattnerc2c28fc2007-06-15 19:11:01 +00003710 if (RC == 0) {
Dan Gohman6f0d0242008-02-10 18:45:23 +00003711 RC = isAllocatableRegister(Reg, MF, TLI, TRI);
Chris Lattnerc2c28fc2007-06-15 19:11:01 +00003712 if (!RC) { // Couldn't allocate this register.
3713 // Reset NumAllocated to make sure we return consecutive registers.
3714 NumAllocated = 0;
3715 continue;
3716 }
Chris Lattnerbf996f12007-04-30 17:29:31 +00003717 }
3718
3719 // Okay, this register is good, we can use it.
3720 ++NumAllocated;
3721
3722 // If we allocated enough consecutive registers, succeed.
3723 if (NumAllocated == NumRegs) {
3724 unsigned RegStart = (i-NumAllocated)+1;
3725 unsigned RegEnd = i+1;
3726 // Mark all of the allocated registers used.
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003727 for (unsigned i = RegStart; i != RegEnd; ++i)
3728 Regs.push_back(RegClassRegs[i]);
Chris Lattnerbf996f12007-04-30 17:29:31 +00003729
Dan Gohman23ce5022008-04-25 18:27:55 +00003730 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, *RC->vt_begin(),
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003731 OpInfo.ConstraintVT);
Chris Lattner7cbeb242008-02-21 04:55:52 +00003732 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TRI);
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003733 return;
Chris Lattnerbf996f12007-04-30 17:29:31 +00003734 }
3735 }
3736
3737 // Otherwise, we couldn't allocate enough registers for this.
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003738 return;
Chris Lattnerbf996f12007-04-30 17:29:31 +00003739}
3740
3741
Chris Lattnerce7518c2006-01-26 22:24:51 +00003742/// visitInlineAsm - Handle a call to an InlineAsm object.
3743///
Duncan Sandsfd7b3262007-12-17 18:08:19 +00003744void SelectionDAGLowering::visitInlineAsm(CallSite CS) {
3745 InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
Chris Lattnerce7518c2006-01-26 22:24:51 +00003746
Chris Lattner0c583402007-04-28 20:49:53 +00003747 /// ConstraintOperands - Information about all of the constraints.
Evan Cheng5c807602008-02-26 02:33:44 +00003748 std::vector<SDISelAsmOperandInfo> ConstraintOperands;
Chris Lattnerce7518c2006-01-26 22:24:51 +00003749
3750 SDOperand Chain = getRoot();
3751 SDOperand Flag;
3752
Chris Lattner4e4b5762006-02-01 18:59:47 +00003753 std::set<unsigned> OutputRegs, InputRegs;
Chris Lattner1efa40f2006-02-22 00:56:39 +00003754
Chris Lattner0c583402007-04-28 20:49:53 +00003755 // Do a prepass over the constraints, canonicalizing them, and building up the
3756 // ConstraintOperands list.
3757 std::vector<InlineAsm::ConstraintInfo>
3758 ConstraintInfos = IA->ParseConstraints();
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003759
3760 // SawEarlyClobber - Keep track of whether we saw an earlyclobber output
3761 // constraint. If so, we can't let the register allocator allocate any input
3762 // registers, because it will not know to avoid the earlyclobbered output reg.
3763 bool SawEarlyClobber = false;
3764
Duncan Sandsfd7b3262007-12-17 18:08:19 +00003765 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst.
Chris Lattneracf8b012008-04-27 23:44:28 +00003766 unsigned ResNo = 0; // ResNo - The result number of the next output.
Chris Lattner0c583402007-04-28 20:49:53 +00003767 for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) {
Evan Cheng5c807602008-02-26 02:33:44 +00003768 ConstraintOperands.push_back(SDISelAsmOperandInfo(ConstraintInfos[i]));
3769 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
Chris Lattner0c583402007-04-28 20:49:53 +00003770
Chris Lattner0c583402007-04-28 20:49:53 +00003771 MVT::ValueType OpVT = MVT::Other;
3772
3773 // Compute the value type for each operand.
3774 switch (OpInfo.Type) {
Chris Lattner1efa40f2006-02-22 00:56:39 +00003775 case InlineAsm::isOutput:
Chris Lattneracf8b012008-04-27 23:44:28 +00003776 // Indirect outputs just consume an argument.
3777 if (OpInfo.isIndirect) {
Duncan Sandsfd7b3262007-12-17 18:08:19 +00003778 OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
Chris Lattneracf8b012008-04-27 23:44:28 +00003779 break;
Chris Lattner1efa40f2006-02-22 00:56:39 +00003780 }
Chris Lattneracf8b012008-04-27 23:44:28 +00003781 // The return value of the call is this value. As such, there is no
3782 // corresponding argument.
3783 assert(CS.getType() != Type::VoidTy && "Bad inline asm!");
3784 if (const StructType *STy = dyn_cast<StructType>(CS.getType())) {
3785 OpVT = TLI.getValueType(STy->getElementType(ResNo));
3786 } else {
3787 assert(ResNo == 0 && "Asm only has one result!");
3788 OpVT = TLI.getValueType(CS.getType());
3789 }
3790 ++ResNo;
Chris Lattner1efa40f2006-02-22 00:56:39 +00003791 break;
3792 case InlineAsm::isInput:
Duncan Sandsfd7b3262007-12-17 18:08:19 +00003793 OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
Chris Lattner1efa40f2006-02-22 00:56:39 +00003794 break;
3795 case InlineAsm::isClobber:
Chris Lattner0c583402007-04-28 20:49:53 +00003796 // Nothing to do.
Chris Lattner1efa40f2006-02-22 00:56:39 +00003797 break;
3798 }
Chris Lattner1efa40f2006-02-22 00:56:39 +00003799
Chris Lattner0c583402007-04-28 20:49:53 +00003800 // If this is an input or an indirect output, process the call argument.
Dale Johanneseneb57ea72007-11-05 21:20:28 +00003801 // BasicBlocks are labels, currently appearing only in asm's.
Chris Lattner0c583402007-04-28 20:49:53 +00003802 if (OpInfo.CallOperandVal) {
Chris Lattner507ffd22008-04-27 00:16:18 +00003803 if (BasicBlock *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal))
3804 OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
Dale Johanneseneb57ea72007-11-05 21:20:28 +00003805 else {
3806 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
3807 const Type *OpTy = OpInfo.CallOperandVal->getType();
3808 // If this is an indirect operand, the operand is a pointer to the
3809 // accessed type.
3810 if (OpInfo.isIndirect)
3811 OpTy = cast<PointerType>(OpTy)->getElementType();
3812
3813 // If OpTy is not a first-class value, it may be a struct/union that we
3814 // can tile with integers.
3815 if (!OpTy->isFirstClassType() && OpTy->isSized()) {
3816 unsigned BitSize = TD->getTypeSizeInBits(OpTy);
3817 switch (BitSize) {
3818 default: break;
3819 case 1:
3820 case 8:
3821 case 16:
3822 case 32:
3823 case 64:
3824 OpTy = IntegerType::get(BitSize);
3825 break;
3826 }
Chris Lattner6995cf62007-04-29 18:58:03 +00003827 }
Dale Johanneseneb57ea72007-11-05 21:20:28 +00003828
3829 OpVT = TLI.getValueType(OpTy, true);
Chris Lattner0c583402007-04-28 20:49:53 +00003830 }
3831 }
3832
3833 OpInfo.ConstraintVT = OpVT;
Chris Lattner2a600be2007-04-28 21:01:43 +00003834
Chris Lattner3ff90dc2007-04-30 17:16:27 +00003835 // Compute the constraint code and ConstraintType to use.
Chris Lattner5a096902008-04-27 00:37:18 +00003836 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
Chris Lattner0c583402007-04-28 20:49:53 +00003837
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003838 // Keep track of whether we see an earlyclobber.
3839 SawEarlyClobber |= OpInfo.isEarlyClobber;
Chris Lattner09e4b7e2007-04-28 21:12:06 +00003840
Chris Lattner0fe71e92008-02-21 19:43:13 +00003841 // If we see a clobber of a register, it is an early clobber.
Chris Lattner69e6a8d2008-02-21 20:54:31 +00003842 if (!SawEarlyClobber &&
3843 OpInfo.Type == InlineAsm::isClobber &&
3844 OpInfo.ConstraintType == TargetLowering::C_Register) {
3845 // Note that we want to ignore things that we don't trick here, like
3846 // dirflag, fpsr, flags, etc.
3847 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
3848 TLI.getRegForInlineAsmConstraint(OpInfo.ConstraintCode,
3849 OpInfo.ConstraintVT);
3850 if (PhysReg.first || PhysReg.second) {
3851 // This is a register we know of.
3852 SawEarlyClobber = true;
3853 }
3854 }
Chris Lattner0fe71e92008-02-21 19:43:13 +00003855
Chris Lattner09e4b7e2007-04-28 21:12:06 +00003856 // If this is a memory input, and if the operand is not indirect, do what we
3857 // need to to provide an address for the memory input.
3858 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
3859 !OpInfo.isIndirect) {
3860 assert(OpInfo.Type == InlineAsm::isInput &&
3861 "Can only indirectify direct input operands!");
3862
3863 // Memory operands really want the address of the value. If we don't have
3864 // an indirect input, put it in the constpool if we can, otherwise spill
3865 // it to a stack slot.
3866
3867 // If the operand is a float, integer, or vector constant, spill to a
3868 // constant pool entry to get its address.
3869 Value *OpVal = OpInfo.CallOperandVal;
3870 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
3871 isa<ConstantVector>(OpVal)) {
3872 OpInfo.CallOperand = DAG.getConstantPool(cast<Constant>(OpVal),
3873 TLI.getPointerTy());
3874 } else {
3875 // Otherwise, create a stack slot and emit a store to it before the
3876 // asm.
3877 const Type *Ty = OpVal->getType();
Duncan Sands514ab342007-11-01 20:53:16 +00003878 uint64_t TySize = TLI.getTargetData()->getABITypeSize(Ty);
Chris Lattner09e4b7e2007-04-28 21:12:06 +00003879 unsigned Align = TLI.getTargetData()->getPrefTypeAlignment(Ty);
3880 MachineFunction &MF = DAG.getMachineFunction();
3881 int SSFI = MF.getFrameInfo()->CreateStackObject(TySize, Align);
3882 SDOperand StackSlot = DAG.getFrameIndex(SSFI, TLI.getPointerTy());
3883 Chain = DAG.getStore(Chain, OpInfo.CallOperand, StackSlot, NULL, 0);
3884 OpInfo.CallOperand = StackSlot;
3885 }
3886
3887 // There is no longer a Value* corresponding to this operand.
3888 OpInfo.CallOperandVal = 0;
3889 // It is now an indirect operand.
3890 OpInfo.isIndirect = true;
3891 }
3892
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003893 // If this constraint is for a specific register, allocate it before
3894 // anything else.
3895 if (OpInfo.ConstraintType == TargetLowering::C_Register)
3896 GetRegistersForValue(OpInfo, SawEarlyClobber, OutputRegs, InputRegs);
Chris Lattner0c583402007-04-28 20:49:53 +00003897 }
Chris Lattner0c583402007-04-28 20:49:53 +00003898 ConstraintInfos.clear();
3899
3900
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003901 // Second pass - Loop over all of the operands, assigning virtual or physregs
3902 // to registerclass operands.
3903 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
Evan Cheng5c807602008-02-26 02:33:44 +00003904 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003905
3906 // C_Register operands have already been allocated, Other/Memory don't need
3907 // to be.
3908 if (OpInfo.ConstraintType == TargetLowering::C_RegisterClass)
3909 GetRegistersForValue(OpInfo, SawEarlyClobber, OutputRegs, InputRegs);
3910 }
3911
Chris Lattner0c583402007-04-28 20:49:53 +00003912 // AsmNodeOperands - The operands for the ISD::INLINEASM node.
3913 std::vector<SDOperand> AsmNodeOperands;
3914 AsmNodeOperands.push_back(SDOperand()); // reserve space for input chain
3915 AsmNodeOperands.push_back(
3916 DAG.getTargetExternalSymbol(IA->getAsmString().c_str(), MVT::Other));
3917
Chris Lattner2cc2f662006-02-01 01:28:23 +00003918
Chris Lattner0f0b7d42006-02-21 23:12:12 +00003919 // Loop over all of the inputs, copying the operand values into the
3920 // appropriate registers and processing the output regs.
Chris Lattner864635a2006-02-22 22:37:12 +00003921 RegsForValue RetValRegs;
Chris Lattner0f0b7d42006-02-21 23:12:12 +00003922
Chris Lattner0c583402007-04-28 20:49:53 +00003923 // IndirectStoresToEmit - The set of stores to emit after the inline asm node.
3924 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
3925
3926 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
Evan Cheng5c807602008-02-26 02:33:44 +00003927 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
Chris Lattner1efa40f2006-02-22 00:56:39 +00003928
Chris Lattner0c583402007-04-28 20:49:53 +00003929 switch (OpInfo.Type) {
Chris Lattner2cc2f662006-02-01 01:28:23 +00003930 case InlineAsm::isOutput: {
Chris Lattnerc83994e2007-04-28 21:03:16 +00003931 if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass &&
3932 OpInfo.ConstraintType != TargetLowering::C_Register) {
Chris Lattnerf2f3cd52007-04-28 06:08:13 +00003933 // Memory output, or 'other' output (e.g. 'X' constraint).
Chris Lattner09e4b7e2007-04-28 21:12:06 +00003934 assert(OpInfo.isIndirect && "Memory output must be indirect operand");
Chris Lattner22873462006-02-27 23:45:39 +00003935
Chris Lattner22873462006-02-27 23:45:39 +00003936 // Add information to the INLINEASM node to know about this output.
3937 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
Chris Lattnerc90233b2007-05-15 01:33:58 +00003938 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
3939 TLI.getPointerTy()));
Chris Lattner09e4b7e2007-04-28 21:12:06 +00003940 AsmNodeOperands.push_back(OpInfo.CallOperand);
Chris Lattner22873462006-02-27 23:45:39 +00003941 break;
3942 }
3943
Chris Lattner2a600be2007-04-28 21:01:43 +00003944 // Otherwise, this is a register or register class output.
Chris Lattner22873462006-02-27 23:45:39 +00003945
Chris Lattner864635a2006-02-22 22:37:12 +00003946 // Copy the output from the appropriate register. Find a register that
Chris Lattner1efa40f2006-02-22 00:56:39 +00003947 // we can use.
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003948 if (OpInfo.AssignedRegs.Regs.empty()) {
Bill Wendling832171c2006-12-07 20:04:42 +00003949 cerr << "Couldn't allocate output reg for contraint '"
Chris Lattner0c583402007-04-28 20:49:53 +00003950 << OpInfo.ConstraintCode << "'!\n";
Chris Lattnerd03f1582006-10-31 07:33:13 +00003951 exit(1);
3952 }
Chris Lattner1efa40f2006-02-22 00:56:39 +00003953
Chris Lattner0c583402007-04-28 20:49:53 +00003954 if (!OpInfo.isIndirect) {
3955 // This is the result value of the call.
Chris Lattner864635a2006-02-22 22:37:12 +00003956 assert(RetValRegs.Regs.empty() &&
Chris Lattner2cc2f662006-02-01 01:28:23 +00003957 "Cannot have multiple output constraints yet!");
Duncan Sandsfd7b3262007-12-17 18:08:19 +00003958 assert(CS.getType() != Type::VoidTy && "Bad inline asm!");
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003959 RetValRegs = OpInfo.AssignedRegs;
Chris Lattner2cc2f662006-02-01 01:28:23 +00003960 } else {
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003961 IndirectStoresToEmit.push_back(std::make_pair(OpInfo.AssignedRegs,
Chris Lattner0c583402007-04-28 20:49:53 +00003962 OpInfo.CallOperandVal));
Chris Lattner2cc2f662006-02-01 01:28:23 +00003963 }
Chris Lattner6656dd12006-01-31 02:03:41 +00003964
3965 // Add information to the INLINEASM node to know that this register is
3966 // set.
Chris Lattnere7cf56a2007-04-30 21:11:17 +00003967 OpInfo.AssignedRegs.AddInlineAsmOperands(2 /*REGDEF*/, DAG,
3968 AsmNodeOperands);
Chris Lattner6656dd12006-01-31 02:03:41 +00003969 break;
3970 }
3971 case InlineAsm::isInput: {
Chris Lattner0c583402007-04-28 20:49:53 +00003972 SDOperand InOperandVal = OpInfo.CallOperand;
Chris Lattner3d81fee2006-02-04 02:16:44 +00003973
Chris Lattner0c583402007-04-28 20:49:53 +00003974 if (isdigit(OpInfo.ConstraintCode[0])) { // Matching constraint?
Chris Lattner2223aea2006-02-02 00:25:23 +00003975 // If this is required to match an output register we have already set,
3976 // just use its register.
Chris Lattner0c583402007-04-28 20:49:53 +00003977 unsigned OperandNo = atoi(OpInfo.ConstraintCode.c_str());
Chris Lattner3d81fee2006-02-04 02:16:44 +00003978
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00003979 // Scan until we find the definition we already emitted of this operand.
3980 // When we find it, create a RegsForValue operand.
3981 unsigned CurOp = 2; // The first operand.
3982 for (; OperandNo; --OperandNo) {
3983 // Advance to the next operand.
3984 unsigned NumOps =
3985 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
Chris Lattnera15cf702006-07-20 19:02:21 +00003986 assert(((NumOps & 7) == 2 /*REGDEF*/ ||
3987 (NumOps & 7) == 4 /*MEM*/) &&
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00003988 "Skipped past definitions?");
3989 CurOp += (NumOps>>3)+1;
3990 }
3991
3992 unsigned NumOps =
3993 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
Chris Lattner527fae12007-02-01 01:21:12 +00003994 if ((NumOps & 7) == 2 /*REGDEF*/) {
3995 // Add NumOps>>3 registers to MatchedRegs.
3996 RegsForValue MatchedRegs;
Dan Gohman23ce5022008-04-25 18:27:55 +00003997 MatchedRegs.TLI = &TLI;
3998 MatchedRegs.ValueVTs.resize(1, InOperandVal.getValueType());
3999 MatchedRegs.RegVTs.resize(1, AsmNodeOperands[CurOp+1].getValueType());
Chris Lattner527fae12007-02-01 01:21:12 +00004000 for (unsigned i = 0, e = NumOps>>3; i != e; ++i) {
4001 unsigned Reg =
4002 cast<RegisterSDNode>(AsmNodeOperands[++CurOp])->getReg();
4003 MatchedRegs.Regs.push_back(Reg);
4004 }
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00004005
Chris Lattner527fae12007-02-01 01:21:12 +00004006 // Use the produced MatchedRegs object to
Dan Gohmanb6f5b002007-06-28 23:29:44 +00004007 MatchedRegs.getCopyToRegs(InOperandVal, DAG, Chain, &Flag);
Chris Lattner527fae12007-02-01 01:21:12 +00004008 MatchedRegs.AddInlineAsmOperands(1 /*REGUSE*/, DAG, AsmNodeOperands);
4009 break;
4010 } else {
4011 assert((NumOps & 7) == 4/*MEM*/ && "Unknown matching constraint!");
Chris Lattnerf9853bc2008-02-21 05:27:19 +00004012 assert((NumOps >> 3) == 1 && "Unexpected number of operands");
4013 // Add information to the INLINEASM node to know about this input.
4014 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
4015 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
4016 TLI.getPointerTy()));
4017 AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
4018 break;
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00004019 }
Chris Lattner2223aea2006-02-02 00:25:23 +00004020 }
Chris Lattner87bc3bd2006-02-24 01:11:24 +00004021
Chris Lattner2a600be2007-04-28 21:01:43 +00004022 if (OpInfo.ConstraintType == TargetLowering::C_Other) {
Chris Lattner0c583402007-04-28 20:49:53 +00004023 assert(!OpInfo.isIndirect &&
Chris Lattner44b2c502007-04-28 06:42:38 +00004024 "Don't know how to handle indirect other inputs yet!");
4025
Chris Lattner48884cd2007-08-25 00:47:38 +00004026 std::vector<SDOperand> Ops;
4027 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode[0],
4028 Ops, DAG);
4029 if (Ops.empty()) {
Bill Wendling832171c2006-12-07 20:04:42 +00004030 cerr << "Invalid operand for inline asm constraint '"
Chris Lattner0c583402007-04-28 20:49:53 +00004031 << OpInfo.ConstraintCode << "'!\n";
Chris Lattner53069fb2006-10-31 19:41:18 +00004032 exit(1);
4033 }
Chris Lattner87bc3bd2006-02-24 01:11:24 +00004034
4035 // Add information to the INLINEASM node to know about this input.
Chris Lattner48884cd2007-08-25 00:47:38 +00004036 unsigned ResOpType = 3 /*IMM*/ | (Ops.size() << 3);
Chris Lattnerc90233b2007-05-15 01:33:58 +00004037 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
4038 TLI.getPointerTy()));
Chris Lattner48884cd2007-08-25 00:47:38 +00004039 AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end());
Chris Lattner87bc3bd2006-02-24 01:11:24 +00004040 break;
Chris Lattner2a600be2007-04-28 21:01:43 +00004041 } else if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
Chris Lattner09e4b7e2007-04-28 21:12:06 +00004042 assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
Chris Lattner44b2c502007-04-28 06:42:38 +00004043 assert(InOperandVal.getValueType() == TLI.getPointerTy() &&
4044 "Memory operands expect pointer values");
4045
Chris Lattner87bc3bd2006-02-24 01:11:24 +00004046 // Add information to the INLINEASM node to know about this input.
4047 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
Chris Lattnerc90233b2007-05-15 01:33:58 +00004048 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
4049 TLI.getPointerTy()));
Chris Lattner87bc3bd2006-02-24 01:11:24 +00004050 AsmNodeOperands.push_back(InOperandVal);
4051 break;
4052 }
4053
Chris Lattner2a600be2007-04-28 21:01:43 +00004054 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
4055 OpInfo.ConstraintType == TargetLowering::C_Register) &&
4056 "Unknown constraint type!");
Chris Lattner0c583402007-04-28 20:49:53 +00004057 assert(!OpInfo.isIndirect &&
Chris Lattner44b2c502007-04-28 06:42:38 +00004058 "Don't know how to handle indirect register inputs yet!");
Chris Lattner87bc3bd2006-02-24 01:11:24 +00004059
4060 // Copy the input into the appropriate registers.
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004061 assert(!OpInfo.AssignedRegs.Regs.empty() &&
4062 "Couldn't allocate input reg!");
Chris Lattner87bc3bd2006-02-24 01:11:24 +00004063
Dan Gohmanb6f5b002007-06-28 23:29:44 +00004064 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, Chain, &Flag);
Chris Lattner87bc3bd2006-02-24 01:11:24 +00004065
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004066 OpInfo.AssignedRegs.AddInlineAsmOperands(1/*REGUSE*/, DAG,
4067 AsmNodeOperands);
Chris Lattner6656dd12006-01-31 02:03:41 +00004068 break;
4069 }
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00004070 case InlineAsm::isClobber: {
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00004071 // Add the clobbered value to the operand list, so that the register
4072 // allocator is aware that the physreg got clobbered.
Chris Lattnere7cf56a2007-04-30 21:11:17 +00004073 if (!OpInfo.AssignedRegs.Regs.empty())
4074 OpInfo.AssignedRegs.AddInlineAsmOperands(2/*REGDEF*/, DAG,
4075 AsmNodeOperands);
Chris Lattner6656dd12006-01-31 02:03:41 +00004076 break;
4077 }
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00004078 }
Chris Lattner6656dd12006-01-31 02:03:41 +00004079 }
Chris Lattnerce7518c2006-01-26 22:24:51 +00004080
4081 // Finish up input operands.
4082 AsmNodeOperands[0] = Chain;
4083 if (Flag.Val) AsmNodeOperands.push_back(Flag);
4084
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00004085 Chain = DAG.getNode(ISD::INLINEASM,
4086 DAG.getNodeValueTypes(MVT::Other, MVT::Flag), 2,
Chris Lattnerbd564bf2006-08-08 02:23:42 +00004087 &AsmNodeOperands[0], AsmNodeOperands.size());
Chris Lattnerce7518c2006-01-26 22:24:51 +00004088 Flag = Chain.getValue(1);
4089
Chris Lattner6656dd12006-01-31 02:03:41 +00004090 // If this asm returns a register value, copy the result from that register
4091 // and set it as the value of the call.
Chris Lattner3a508c92007-04-12 06:00:20 +00004092 if (!RetValRegs.Regs.empty()) {
Dan Gohmanb6f5b002007-06-28 23:29:44 +00004093 SDOperand Val = RetValRegs.getCopyFromRegs(DAG, Chain, &Flag);
Chris Lattner3a508c92007-04-12 06:00:20 +00004094
4095 // If the result of the inline asm is a vector, it may have the wrong
4096 // width/num elts. Make sure to convert it to the right type with
Dan Gohman7f321562007-06-25 16:23:39 +00004097 // bit_convert.
4098 if (MVT::isVector(Val.getValueType())) {
Duncan Sandsfd7b3262007-12-17 18:08:19 +00004099 const VectorType *VTy = cast<VectorType>(CS.getType());
Dan Gohman7f321562007-06-25 16:23:39 +00004100 MVT::ValueType DesiredVT = TLI.getValueType(VTy);
Chris Lattner3a508c92007-04-12 06:00:20 +00004101
Dan Gohman7f321562007-06-25 16:23:39 +00004102 Val = DAG.getNode(ISD::BIT_CONVERT, DesiredVT, Val);
Chris Lattner3a508c92007-04-12 06:00:20 +00004103 }
4104
Duncan Sandsfd7b3262007-12-17 18:08:19 +00004105 setValue(CS.getInstruction(), Val);
Chris Lattner3a508c92007-04-12 06:00:20 +00004106 }
Chris Lattnerce7518c2006-01-26 22:24:51 +00004107
Chris Lattner6656dd12006-01-31 02:03:41 +00004108 std::vector<std::pair<SDOperand, Value*> > StoresToEmit;
4109
4110 // Process indirect outputs, first output all of the flagged copies out of
4111 // physregs.
4112 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
Chris Lattner864635a2006-02-22 22:37:12 +00004113 RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
Chris Lattner6656dd12006-01-31 02:03:41 +00004114 Value *Ptr = IndirectStoresToEmit[i].second;
Dan Gohmanb6f5b002007-06-28 23:29:44 +00004115 SDOperand OutVal = OutRegs.getCopyFromRegs(DAG, Chain, &Flag);
Chris Lattner864635a2006-02-22 22:37:12 +00004116 StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
Chris Lattner6656dd12006-01-31 02:03:41 +00004117 }
4118
4119 // Emit the non-flagged stores from the physregs.
Chris Lattnerbd564bf2006-08-08 02:23:42 +00004120 SmallVector<SDOperand, 8> OutChains;
Chris Lattner6656dd12006-01-31 02:03:41 +00004121 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i)
Chris Lattner0c583402007-04-28 20:49:53 +00004122 OutChains.push_back(DAG.getStore(Chain, StoresToEmit[i].first,
Chris Lattner6656dd12006-01-31 02:03:41 +00004123 getValue(StoresToEmit[i].second),
Evan Cheng8b2794a2006-10-13 21:14:26 +00004124 StoresToEmit[i].second, 0));
Chris Lattner6656dd12006-01-31 02:03:41 +00004125 if (!OutChains.empty())
Chris Lattnerbd564bf2006-08-08 02:23:42 +00004126 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
4127 &OutChains[0], OutChains.size());
Chris Lattnerce7518c2006-01-26 22:24:51 +00004128 DAG.setRoot(Chain);
4129}
4130
4131
Chris Lattner1c08c712005-01-07 07:47:53 +00004132void SelectionDAGLowering::visitMalloc(MallocInst &I) {
4133 SDOperand Src = getValue(I.getOperand(0));
4134
4135 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattner68cd65e2005-01-22 23:04:37 +00004136
4137 if (IntPtr < Src.getValueType())
4138 Src = DAG.getNode(ISD::TRUNCATE, IntPtr, Src);
4139 else if (IntPtr > Src.getValueType())
4140 Src = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, Src);
Chris Lattner1c08c712005-01-07 07:47:53 +00004141
4142 // Scale the source by the type size.
Duncan Sands514ab342007-11-01 20:53:16 +00004143 uint64_t ElementSize = TD->getABITypeSize(I.getType()->getElementType());
Chris Lattner1c08c712005-01-07 07:47:53 +00004144 Src = DAG.getNode(ISD::MUL, Src.getValueType(),
Chris Lattner0bd48932008-01-17 07:00:52 +00004145 Src, DAG.getIntPtrConstant(ElementSize));
Chris Lattner1c08c712005-01-07 07:47:53 +00004146
Reid Spencer47857812006-12-31 05:55:36 +00004147 TargetLowering::ArgListTy Args;
4148 TargetLowering::ArgListEntry Entry;
4149 Entry.Node = Src;
4150 Entry.Ty = TLI.getTargetData()->getIntPtrType();
Reid Spencer47857812006-12-31 05:55:36 +00004151 Args.push_back(Entry);
Chris Lattnercf5734d2005-01-08 19:26:18 +00004152
4153 std::pair<SDOperand,SDOperand> Result =
Duncan Sands00fee652008-02-14 17:28:50 +00004154 TLI.LowerCallTo(getRoot(), I.getType(), false, false, false, CallingConv::C,
4155 true, DAG.getExternalSymbol("malloc", IntPtr), Args, DAG);
Chris Lattnercf5734d2005-01-08 19:26:18 +00004156 setValue(&I, Result.first); // Pointers always fit in registers
4157 DAG.setRoot(Result.second);
Chris Lattner1c08c712005-01-07 07:47:53 +00004158}
4159
4160void SelectionDAGLowering::visitFree(FreeInst &I) {
Reid Spencer47857812006-12-31 05:55:36 +00004161 TargetLowering::ArgListTy Args;
4162 TargetLowering::ArgListEntry Entry;
4163 Entry.Node = getValue(I.getOperand(0));
4164 Entry.Ty = TLI.getTargetData()->getIntPtrType();
Reid Spencer47857812006-12-31 05:55:36 +00004165 Args.push_back(Entry);
Chris Lattner1c08c712005-01-07 07:47:53 +00004166 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattnercf5734d2005-01-08 19:26:18 +00004167 std::pair<SDOperand,SDOperand> Result =
Duncan Sands00fee652008-02-14 17:28:50 +00004168 TLI.LowerCallTo(getRoot(), Type::VoidTy, false, false, false,
4169 CallingConv::C, true,
Chris Lattnercf5734d2005-01-08 19:26:18 +00004170 DAG.getExternalSymbol("free", IntPtr), Args, DAG);
4171 DAG.setRoot(Result.second);
Chris Lattner1c08c712005-01-07 07:47:53 +00004172}
4173
Evan Chengff9b3732008-01-30 18:18:23 +00004174// EmitInstrWithCustomInserter - This method should be implemented by targets
4175// that mark instructions with the 'usesCustomDAGSchedInserter' flag. These
Chris Lattner025c39b2005-08-26 20:54:47 +00004176// instructions are special in various ways, which require special support to
4177// insert. The specified MachineInstr is created but not inserted into any
4178// basic blocks, and the scheduler passes ownership of it to this method.
Evan Chengff9b3732008-01-30 18:18:23 +00004179MachineBasicBlock *TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
Chris Lattner025c39b2005-08-26 20:54:47 +00004180 MachineBasicBlock *MBB) {
Bill Wendling832171c2006-12-07 20:04:42 +00004181 cerr << "If a target marks an instruction with "
4182 << "'usesCustomDAGSchedInserter', it must implement "
Evan Chengff9b3732008-01-30 18:18:23 +00004183 << "TargetLowering::EmitInstrWithCustomInserter!\n";
Chris Lattner025c39b2005-08-26 20:54:47 +00004184 abort();
4185 return 0;
4186}
4187
Chris Lattner39ae3622005-01-09 00:00:49 +00004188void SelectionDAGLowering::visitVAStart(CallInst &I) {
Nate Begemanacc398c2006-01-25 18:21:52 +00004189 DAG.setRoot(DAG.getNode(ISD::VASTART, MVT::Other, getRoot(),
4190 getValue(I.getOperand(1)),
4191 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner39ae3622005-01-09 00:00:49 +00004192}
4193
4194void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
Nate Begemanacc398c2006-01-25 18:21:52 +00004195 SDOperand V = DAG.getVAArg(TLI.getValueType(I.getType()), getRoot(),
4196 getValue(I.getOperand(0)),
4197 DAG.getSrcValue(I.getOperand(0)));
4198 setValue(&I, V);
4199 DAG.setRoot(V.getValue(1));
Chris Lattner1c08c712005-01-07 07:47:53 +00004200}
4201
4202void SelectionDAGLowering::visitVAEnd(CallInst &I) {
Nate Begemanacc398c2006-01-25 18:21:52 +00004203 DAG.setRoot(DAG.getNode(ISD::VAEND, MVT::Other, getRoot(),
4204 getValue(I.getOperand(1)),
4205 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner1c08c712005-01-07 07:47:53 +00004206}
4207
4208void SelectionDAGLowering::visitVACopy(CallInst &I) {
Nate Begemanacc398c2006-01-25 18:21:52 +00004209 DAG.setRoot(DAG.getNode(ISD::VACOPY, MVT::Other, getRoot(),
4210 getValue(I.getOperand(1)),
4211 getValue(I.getOperand(2)),
4212 DAG.getSrcValue(I.getOperand(1)),
4213 DAG.getSrcValue(I.getOperand(2))));
Chris Lattner1c08c712005-01-07 07:47:53 +00004214}
4215
Chris Lattnerfdfded52006-04-12 16:20:43 +00004216/// TargetLowering::LowerArguments - This is the default LowerArguments
4217/// implementation, which just inserts a FORMAL_ARGUMENTS node. FIXME: When all
Chris Lattnerf4ec8172006-05-16 22:53:20 +00004218/// targets are migrated to using FORMAL_ARGUMENTS, this hook should be
4219/// integrated into SDISel.
Chris Lattnerfdfded52006-04-12 16:20:43 +00004220std::vector<SDOperand>
4221TargetLowering::LowerArguments(Function &F, SelectionDAG &DAG) {
4222 // Add CC# and isVararg as operands to the FORMAL_ARGUMENTS node.
4223 std::vector<SDOperand> Ops;
Chris Lattner8c0c10c2006-05-16 06:45:34 +00004224 Ops.push_back(DAG.getRoot());
Chris Lattnerfdfded52006-04-12 16:20:43 +00004225 Ops.push_back(DAG.getConstant(F.getCallingConv(), getPointerTy()));
4226 Ops.push_back(DAG.getConstant(F.isVarArg(), getPointerTy()));
4227
4228 // Add one result value for each formal argument.
4229 std::vector<MVT::ValueType> RetVals;
Anton Korobeynikov6aa279d2007-01-28 18:01:49 +00004230 unsigned j = 1;
Anton Korobeynikovac2b2cf2007-01-28 16:04:40 +00004231 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end();
4232 I != E; ++I, ++j) {
Chris Lattnerfdfded52006-04-12 16:20:43 +00004233 MVT::ValueType VT = getValueType(I->getType());
Duncan Sands276dcbd2008-03-21 09:14:45 +00004234 ISD::ArgFlagsTy Flags;
Lauro Ramos Venancio7aa47b62007-02-13 13:50:08 +00004235 unsigned OriginalAlignment =
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00004236 getTargetData()->getABITypeAlignment(I->getType());
Lauro Ramos Venancio7aa47b62007-02-13 13:50:08 +00004237
Duncan Sandsafa3b6d2007-11-28 17:07:01 +00004238 if (F.paramHasAttr(j, ParamAttr::ZExt))
Duncan Sands276dcbd2008-03-21 09:14:45 +00004239 Flags.setZExt();
Duncan Sandsafa3b6d2007-11-28 17:07:01 +00004240 if (F.paramHasAttr(j, ParamAttr::SExt))
Duncan Sands276dcbd2008-03-21 09:14:45 +00004241 Flags.setSExt();
Duncan Sandsafa3b6d2007-11-28 17:07:01 +00004242 if (F.paramHasAttr(j, ParamAttr::InReg))
Duncan Sands276dcbd2008-03-21 09:14:45 +00004243 Flags.setInReg();
Duncan Sandsafa3b6d2007-11-28 17:07:01 +00004244 if (F.paramHasAttr(j, ParamAttr::StructRet))
Duncan Sands276dcbd2008-03-21 09:14:45 +00004245 Flags.setSRet();
Duncan Sandsafa3b6d2007-11-28 17:07:01 +00004246 if (F.paramHasAttr(j, ParamAttr::ByVal)) {
Duncan Sands276dcbd2008-03-21 09:14:45 +00004247 Flags.setByVal();
Rafael Espindola594d37e2007-08-10 14:44:42 +00004248 const PointerType *Ty = cast<PointerType>(I->getType());
Duncan Sandsa41d7192008-01-13 21:19:59 +00004249 const Type *ElementTy = Ty->getElementType();
Duncan Sands276dcbd2008-03-21 09:14:45 +00004250 unsigned FrameAlign = getByValTypeAlignment(ElementTy);
Duncan Sandsa41d7192008-01-13 21:19:59 +00004251 unsigned FrameSize = getTargetData()->getABITypeSize(ElementTy);
Dale Johannesen08e78b12008-02-22 17:49:45 +00004252 // For ByVal, alignment should be passed from FE. BE will guess if
4253 // this info is not there but there are cases it cannot get right.
4254 if (F.getParamAlignment(j))
Duncan Sands276dcbd2008-03-21 09:14:45 +00004255 FrameAlign = F.getParamAlignment(j);
4256 Flags.setByValAlign(FrameAlign);
4257 Flags.setByValSize(FrameSize);
Rafael Espindola594d37e2007-08-10 14:44:42 +00004258 }
Duncan Sandsafa3b6d2007-11-28 17:07:01 +00004259 if (F.paramHasAttr(j, ParamAttr::Nest))
Duncan Sands276dcbd2008-03-21 09:14:45 +00004260 Flags.setNest();
4261 Flags.setOrigAlign(OriginalAlignment);
Duncan Sandsb988bac2008-02-11 20:58:28 +00004262
4263 MVT::ValueType RegisterVT = getRegisterType(VT);
4264 unsigned NumRegs = getNumRegisters(VT);
4265 for (unsigned i = 0; i != NumRegs; ++i) {
4266 RetVals.push_back(RegisterVT);
Nicolas Geoffray9701c8a2008-04-14 17:17:14 +00004267 ISD::ArgFlagsTy MyFlags = Flags;
Nicolas Geoffrayc0cb28f2008-04-13 13:40:22 +00004268 if (NumRegs > 1 && i == 0)
Nicolas Geoffray6ccbbd82008-04-15 08:08:50 +00004269 MyFlags.setSplit();
Duncan Sandsb988bac2008-02-11 20:58:28 +00004270 // if it isn't first piece, alignment must be 1
Nicolas Geoffrayc0cb28f2008-04-13 13:40:22 +00004271 else if (i > 0)
Nicolas Geoffray9701c8a2008-04-14 17:17:14 +00004272 MyFlags.setOrigAlign(1);
4273 Ops.push_back(DAG.getArgFlags(MyFlags));
Dan Gohmanb6f5b002007-06-28 23:29:44 +00004274 }
Chris Lattnerfdfded52006-04-12 16:20:43 +00004275 }
Evan Cheng3b0d2862006-04-25 23:03:35 +00004276
Chris Lattner8c0c10c2006-05-16 06:45:34 +00004277 RetVals.push_back(MVT::Other);
Chris Lattnerfdfded52006-04-12 16:20:43 +00004278
4279 // Create the node.
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00004280 SDNode *Result = DAG.getNode(ISD::FORMAL_ARGUMENTS,
Chris Lattner86ca3ca2008-02-13 07:39:09 +00004281 DAG.getVTList(&RetVals[0], RetVals.size()),
Chris Lattnerbd564bf2006-08-08 02:23:42 +00004282 &Ops[0], Ops.size()).Val;
Chris Lattner86ca3ca2008-02-13 07:39:09 +00004283
4284 // Prelower FORMAL_ARGUMENTS. This isn't required for functionality, but
4285 // allows exposing the loads that may be part of the argument access to the
4286 // first DAGCombiner pass.
4287 SDOperand TmpRes = LowerOperation(SDOperand(Result, 0), DAG);
4288
4289 // The number of results should match up, except that the lowered one may have
4290 // an extra flag result.
4291 assert((Result->getNumValues() == TmpRes.Val->getNumValues() ||
4292 (Result->getNumValues()+1 == TmpRes.Val->getNumValues() &&
4293 TmpRes.getValue(Result->getNumValues()).getValueType() == MVT::Flag))
4294 && "Lowering produced unexpected number of results!");
4295 Result = TmpRes.Val;
4296
Dan Gohman27a70be2007-07-02 16:18:06 +00004297 unsigned NumArgRegs = Result->getNumValues() - 1;
4298 DAG.setRoot(SDOperand(Result, NumArgRegs));
Chris Lattnerfdfded52006-04-12 16:20:43 +00004299
4300 // Set up the return result vector.
4301 Ops.clear();
4302 unsigned i = 0;
Reid Spencer47857812006-12-31 05:55:36 +00004303 unsigned Idx = 1;
4304 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E;
4305 ++I, ++Idx) {
Chris Lattnerfdfded52006-04-12 16:20:43 +00004306 MVT::ValueType VT = getValueType(I->getType());
Duncan Sandsb988bac2008-02-11 20:58:28 +00004307 MVT::ValueType PartVT = getRegisterType(VT);
4308
4309 unsigned NumParts = getNumRegisters(VT);
4310 SmallVector<SDOperand, 4> Parts(NumParts);
4311 for (unsigned j = 0; j != NumParts; ++j)
4312 Parts[j] = SDOperand(Result, i++);
4313
4314 ISD::NodeType AssertOp = ISD::DELETED_NODE;
4315 if (F.paramHasAttr(Idx, ParamAttr::SExt))
4316 AssertOp = ISD::AssertSext;
4317 else if (F.paramHasAttr(Idx, ParamAttr::ZExt))
4318 AssertOp = ISD::AssertZext;
4319
4320 Ops.push_back(getCopyFromParts(DAG, &Parts[0], NumParts, PartVT, VT,
Chris Lattner4468c1f2008-03-09 09:38:46 +00004321 AssertOp));
Chris Lattnerfdfded52006-04-12 16:20:43 +00004322 }
Dan Gohman27a70be2007-07-02 16:18:06 +00004323 assert(i == NumArgRegs && "Argument register count mismatch!");
Chris Lattnerfdfded52006-04-12 16:20:43 +00004324 return Ops;
4325}
4326
Chris Lattnerf4ec8172006-05-16 22:53:20 +00004327
4328/// TargetLowering::LowerCallTo - This is the default LowerCallTo
4329/// implementation, which just inserts an ISD::CALL node, which is later custom
4330/// lowered by the target to something concrete. FIXME: When all targets are
4331/// migrated to using ISD::CALL, this hook should be integrated into SDISel.
4332std::pair<SDOperand, SDOperand>
Duncan Sands00fee652008-02-14 17:28:50 +00004333TargetLowering::LowerCallTo(SDOperand Chain, const Type *RetTy,
4334 bool RetSExt, bool RetZExt, bool isVarArg,
4335 unsigned CallingConv, bool isTailCall,
Chris Lattnerf4ec8172006-05-16 22:53:20 +00004336 SDOperand Callee,
4337 ArgListTy &Args, SelectionDAG &DAG) {
Chris Lattnerbe384162006-08-16 22:57:46 +00004338 SmallVector<SDOperand, 32> Ops;
Chris Lattnerf4ec8172006-05-16 22:53:20 +00004339 Ops.push_back(Chain); // Op#0 - Chain
4340 Ops.push_back(DAG.getConstant(CallingConv, getPointerTy())); // Op#1 - CC
4341 Ops.push_back(DAG.getConstant(isVarArg, getPointerTy())); // Op#2 - VarArg
4342 Ops.push_back(DAG.getConstant(isTailCall, getPointerTy())); // Op#3 - Tail
4343 Ops.push_back(Callee);
4344
4345 // Handle all of the outgoing arguments.
4346 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
Reid Spencer47857812006-12-31 05:55:36 +00004347 MVT::ValueType VT = getValueType(Args[i].Ty);
4348 SDOperand Op = Args[i].Node;
Duncan Sands276dcbd2008-03-21 09:14:45 +00004349 ISD::ArgFlagsTy Flags;
Lauro Ramos Venancio7aa47b62007-02-13 13:50:08 +00004350 unsigned OriginalAlignment =
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00004351 getTargetData()->getABITypeAlignment(Args[i].Ty);
Duncan Sands276dcbd2008-03-21 09:14:45 +00004352
Anton Korobeynikovd0b82b32007-03-07 16:25:09 +00004353 if (Args[i].isZExt)
Duncan Sands276dcbd2008-03-21 09:14:45 +00004354 Flags.setZExt();
4355 if (Args[i].isSExt)
4356 Flags.setSExt();
Anton Korobeynikov0db79d82007-03-06 06:10:33 +00004357 if (Args[i].isInReg)
Duncan Sands276dcbd2008-03-21 09:14:45 +00004358 Flags.setInReg();
Anton Korobeynikov0db79d82007-03-06 06:10:33 +00004359 if (Args[i].isSRet)
Duncan Sands276dcbd2008-03-21 09:14:45 +00004360 Flags.setSRet();
Rafael Espindola21485be2007-08-20 15:18:24 +00004361 if (Args[i].isByVal) {
Duncan Sands276dcbd2008-03-21 09:14:45 +00004362 Flags.setByVal();
Rafael Espindola21485be2007-08-20 15:18:24 +00004363 const PointerType *Ty = cast<PointerType>(Args[i].Ty);
Duncan Sandsa41d7192008-01-13 21:19:59 +00004364 const Type *ElementTy = Ty->getElementType();
Duncan Sands276dcbd2008-03-21 09:14:45 +00004365 unsigned FrameAlign = getByValTypeAlignment(ElementTy);
Duncan Sandsa41d7192008-01-13 21:19:59 +00004366 unsigned FrameSize = getTargetData()->getABITypeSize(ElementTy);
Dale Johannesen08e78b12008-02-22 17:49:45 +00004367 // For ByVal, alignment should come from FE. BE will guess if this
4368 // info is not there but there are cases it cannot get right.
4369 if (Args[i].Alignment)
Duncan Sands276dcbd2008-03-21 09:14:45 +00004370 FrameAlign = Args[i].Alignment;
4371 Flags.setByValAlign(FrameAlign);
4372 Flags.setByValSize(FrameSize);
Rafael Espindola21485be2007-08-20 15:18:24 +00004373 }
Duncan Sands36397f52007-07-27 12:58:54 +00004374 if (Args[i].isNest)
Duncan Sands276dcbd2008-03-21 09:14:45 +00004375 Flags.setNest();
4376 Flags.setOrigAlign(OriginalAlignment);
Dan Gohman27a70be2007-07-02 16:18:06 +00004377
Duncan Sandsb988bac2008-02-11 20:58:28 +00004378 MVT::ValueType PartVT = getRegisterType(VT);
4379 unsigned NumParts = getNumRegisters(VT);
4380 SmallVector<SDOperand, 4> Parts(NumParts);
4381 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
4382
4383 if (Args[i].isSExt)
4384 ExtendKind = ISD::SIGN_EXTEND;
4385 else if (Args[i].isZExt)
4386 ExtendKind = ISD::ZERO_EXTEND;
4387
4388 getCopyToParts(DAG, Op, &Parts[0], NumParts, PartVT, ExtendKind);
4389
4390 for (unsigned i = 0; i != NumParts; ++i) {
4391 // if it isn't first piece, alignment must be 1
Duncan Sands276dcbd2008-03-21 09:14:45 +00004392 ISD::ArgFlagsTy MyFlags = Flags;
Nicolas Geoffrayc0cb28f2008-04-13 13:40:22 +00004393 if (NumParts > 1 && i == 0)
Nicolas Geoffray6ccbbd82008-04-15 08:08:50 +00004394 MyFlags.setSplit();
Nicolas Geoffrayc0cb28f2008-04-13 13:40:22 +00004395 else if (i != 0)
Duncan Sands276dcbd2008-03-21 09:14:45 +00004396 MyFlags.setOrigAlign(1);
Duncan Sandsb988bac2008-02-11 20:58:28 +00004397
4398 Ops.push_back(Parts[i]);
Duncan Sands276dcbd2008-03-21 09:14:45 +00004399 Ops.push_back(DAG.getArgFlags(MyFlags));
Dan Gohman27a70be2007-07-02 16:18:06 +00004400 }
Chris Lattnerf4ec8172006-05-16 22:53:20 +00004401 }
4402
Dan Gohmanef5d1942008-03-11 21:11:25 +00004403 // Figure out the result value types. We start by making a list of
Dan Gohman23ce5022008-04-25 18:27:55 +00004404 // the potentially illegal return value types.
Dan Gohmanef5d1942008-03-11 21:11:25 +00004405 SmallVector<MVT::ValueType, 4> LoweredRetTys;
4406 SmallVector<MVT::ValueType, 4> RetTys;
Dan Gohman23ce5022008-04-25 18:27:55 +00004407 ComputeValueVTs(*this, RetTy, RetTys);
Dan Gohmanef5d1942008-03-11 21:11:25 +00004408
Dan Gohman23ce5022008-04-25 18:27:55 +00004409 // Then we translate that to a list of legal types.
4410 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
4411 MVT::ValueType VT = RetTys[I];
Dan Gohmanef5d1942008-03-11 21:11:25 +00004412 MVT::ValueType RegisterVT = getRegisterType(VT);
4413 unsigned NumRegs = getNumRegisters(VT);
4414 for (unsigned i = 0; i != NumRegs; ++i)
4415 LoweredRetTys.push_back(RegisterVT);
4416 }
Chris Lattnerf4ec8172006-05-16 22:53:20 +00004417
Dan Gohmanef5d1942008-03-11 21:11:25 +00004418 LoweredRetTys.push_back(MVT::Other); // Always has a chain.
Chris Lattnerf4ec8172006-05-16 22:53:20 +00004419
Dan Gohmanb6f5b002007-06-28 23:29:44 +00004420 // Create the CALL node.
Chris Lattnerbe384162006-08-16 22:57:46 +00004421 SDOperand Res = DAG.getNode(ISD::CALL,
Dan Gohmanef5d1942008-03-11 21:11:25 +00004422 DAG.getVTList(&LoweredRetTys[0],
4423 LoweredRetTys.size()),
Chris Lattnerbe384162006-08-16 22:57:46 +00004424 &Ops[0], Ops.size());
Dan Gohmanef5d1942008-03-11 21:11:25 +00004425 Chain = Res.getValue(LoweredRetTys.size() - 1);
Dan Gohmanb6f5b002007-06-28 23:29:44 +00004426
4427 // Gather up the call result into a single value.
4428 if (RetTy != Type::VoidTy) {
Duncan Sands00fee652008-02-14 17:28:50 +00004429 ISD::NodeType AssertOp = ISD::DELETED_NODE;
4430
4431 if (RetSExt)
4432 AssertOp = ISD::AssertSext;
4433 else if (RetZExt)
Dan Gohmanb6f5b002007-06-28 23:29:44 +00004434 AssertOp = ISD::AssertZext;
Duncan Sands00fee652008-02-14 17:28:50 +00004435
Dan Gohmanef5d1942008-03-11 21:11:25 +00004436 SmallVector<SDOperand, 4> ReturnValues;
4437 unsigned RegNo = 0;
Dan Gohman23ce5022008-04-25 18:27:55 +00004438 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
4439 MVT::ValueType VT = RetTys[I];
Dan Gohmanef5d1942008-03-11 21:11:25 +00004440 MVT::ValueType RegisterVT = getRegisterType(VT);
4441 unsigned NumRegs = getNumRegisters(VT);
4442 unsigned RegNoEnd = NumRegs + RegNo;
4443 SmallVector<SDOperand, 4> Results;
4444 for (; RegNo != RegNoEnd; ++RegNo)
4445 Results.push_back(Res.getValue(RegNo));
4446 SDOperand ReturnValue =
4447 getCopyFromParts(DAG, &Results[0], NumRegs, RegisterVT, VT,
4448 AssertOp);
4449 ReturnValues.push_back(ReturnValue);
4450 }
4451 Res = ReturnValues.size() == 1 ? ReturnValues.front() :
4452 DAG.getNode(ISD::MERGE_VALUES,
4453 DAG.getVTList(&RetTys[0], RetTys.size()),
4454 &ReturnValues[0], ReturnValues.size());
Chris Lattnerf4ec8172006-05-16 22:53:20 +00004455 }
Dan Gohmanb6f5b002007-06-28 23:29:44 +00004456
4457 return std::make_pair(Res, Chain);
Chris Lattnerf4ec8172006-05-16 22:53:20 +00004458}
4459
Chris Lattner50381b62005-05-14 05:50:48 +00004460SDOperand TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
Chris Lattner171453a2005-01-16 07:28:41 +00004461 assert(0 && "LowerOperation not implemented for this target!");
4462 abort();
Misha Brukmand3f03e42005-02-17 21:39:27 +00004463 return SDOperand();
Chris Lattner171453a2005-01-16 07:28:41 +00004464}
4465
Nate Begeman0aed7842006-01-28 03:14:31 +00004466SDOperand TargetLowering::CustomPromoteOperation(SDOperand Op,
4467 SelectionDAG &DAG) {
4468 assert(0 && "CustomPromoteOperation not implemented for this target!");
4469 abort();
4470 return SDOperand();
4471}
4472
Chris Lattner7041ee32005-01-11 05:56:49 +00004473//===----------------------------------------------------------------------===//
4474// SelectionDAGISel code
4475//===----------------------------------------------------------------------===//
Chris Lattner1c08c712005-01-07 07:47:53 +00004476
4477unsigned SelectionDAGISel::MakeReg(MVT::ValueType VT) {
Chris Lattner84bc5422007-12-31 04:13:23 +00004478 return RegInfo->createVirtualRegister(TLI.getRegClassFor(VT));
Chris Lattner1c08c712005-01-07 07:47:53 +00004479}
4480
Chris Lattner495a0b52005-08-17 06:37:43 +00004481void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const {
Jim Laskeyc7c3f112006-10-16 20:52:31 +00004482 AU.addRequired<AliasAnalysis>();
Gordon Henriksence224772008-01-07 01:30:38 +00004483 AU.addRequired<CollectorModuleMetadata>();
Chris Lattnerc8d288f2007-03-31 04:18:03 +00004484 AU.setPreservesAll();
Chris Lattner495a0b52005-08-17 06:37:43 +00004485}
Chris Lattner1c08c712005-01-07 07:47:53 +00004486
Chris Lattnerc88d8e92005-12-05 07:10:48 +00004487
Chris Lattnerbad7f482006-10-28 19:22:10 +00004488
Chris Lattner1c08c712005-01-07 07:47:53 +00004489bool SelectionDAGISel::runOnFunction(Function &Fn) {
Dan Gohman5f43f922007-08-27 16:26:13 +00004490 // Get alias analysis for load/store combining.
4491 AA = &getAnalysis<AliasAnalysis>();
4492
Chris Lattner1c08c712005-01-07 07:47:53 +00004493 MachineFunction &MF = MachineFunction::construct(&Fn, TLI.getTargetMachine());
Gordon Henriksence224772008-01-07 01:30:38 +00004494 if (MF.getFunction()->hasCollector())
4495 GCI = &getAnalysis<CollectorModuleMetadata>().get(*MF.getFunction());
4496 else
4497 GCI = 0;
Chris Lattner84bc5422007-12-31 04:13:23 +00004498 RegInfo = &MF.getRegInfo();
Bill Wendling832171c2006-12-07 20:04:42 +00004499 DOUT << "\n\n\n=== " << Fn.getName() << "\n";
Chris Lattner1c08c712005-01-07 07:47:53 +00004500
4501 FunctionLoweringInfo FuncInfo(TLI, Fn, MF);
4502
Dale Johannesen1532f3d2008-04-02 00:25:04 +00004503 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
4504 if (InvokeInst *Invoke = dyn_cast<InvokeInst>(I->getTerminator()))
4505 // Mark landing pad.
4506 FuncInfo.MBBMap[Invoke->getSuccessor(1)]->setIsLandingPad();
Duncan Sands9fac0b52007-06-06 10:05:18 +00004507
4508 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
Chris Lattner1c08c712005-01-07 07:47:53 +00004509 SelectBasicBlock(I, MF, FuncInfo);
Misha Brukmanedf128a2005-04-21 22:36:52 +00004510
Evan Chengad2070c2007-02-10 02:43:39 +00004511 // Add function live-ins to entry block live-in set.
4512 BasicBlock *EntryBB = &Fn.getEntryBlock();
4513 BB = FuncInfo.MBBMap[EntryBB];
Chris Lattner84bc5422007-12-31 04:13:23 +00004514 if (!RegInfo->livein_empty())
4515 for (MachineRegisterInfo::livein_iterator I = RegInfo->livein_begin(),
4516 E = RegInfo->livein_end(); I != E; ++I)
Evan Chengad2070c2007-02-10 02:43:39 +00004517 BB->addLiveIn(I->first);
4518
Duncan Sandsf4070822007-06-15 19:04:19 +00004519#ifndef NDEBUG
4520 assert(FuncInfo.CatchInfoFound.size() == FuncInfo.CatchInfoLost.size() &&
4521 "Not all catch info was assigned to a landing pad!");
4522#endif
4523
Chris Lattner1c08c712005-01-07 07:47:53 +00004524 return true;
4525}
4526
Dan Gohman86e1ebf2008-03-27 19:56:19 +00004527void SelectionDAGLowering::CopyValueToVirtualRegister(Value *V,
4528 unsigned Reg) {
Chris Lattner571e4342006-10-27 21:36:01 +00004529 SDOperand Op = getValue(V);
Chris Lattner18c2f132005-01-13 20:50:02 +00004530 assert((Op.getOpcode() != ISD::CopyFromReg ||
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00004531 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
Chris Lattner18c2f132005-01-13 20:50:02 +00004532 "Copy from a reg to the same reg!");
Dan Gohman86e1ebf2008-03-27 19:56:19 +00004533 assert(!TargetRegisterInfo::isPhysicalRegister(Reg) && "Is a physreg");
Dan Gohmanb6f5b002007-06-28 23:29:44 +00004534
Dan Gohman23ce5022008-04-25 18:27:55 +00004535 RegsForValue RFV(TLI, Reg, V->getType());
4536 SDOperand Chain = DAG.getEntryNode();
4537 RFV.getCopyToRegs(Op, DAG, Chain, 0);
4538 PendingExports.push_back(Chain);
Chris Lattner1c08c712005-01-07 07:47:53 +00004539}
4540
Chris Lattner068a81e2005-01-17 17:15:02 +00004541void SelectionDAGISel::
Dan Gohman86e1ebf2008-03-27 19:56:19 +00004542LowerArguments(BasicBlock *LLVMBB, SelectionDAGLowering &SDL) {
Chris Lattner068a81e2005-01-17 17:15:02 +00004543 // If this is the entry block, emit arguments.
Evan Cheng15699fc2007-02-10 01:08:18 +00004544 Function &F = *LLVMBB->getParent();
Chris Lattner0afa8e32005-01-17 17:55:19 +00004545 FunctionLoweringInfo &FuncInfo = SDL.FuncInfo;
Chris Lattnerbf209482005-10-30 19:42:35 +00004546 SDOperand OldRoot = SDL.DAG.getRoot();
4547 std::vector<SDOperand> Args = TLI.LowerArguments(F, SDL.DAG);
Chris Lattner068a81e2005-01-17 17:15:02 +00004548
Chris Lattnerbf209482005-10-30 19:42:35 +00004549 unsigned a = 0;
4550 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
4551 AI != E; ++AI, ++a)
4552 if (!AI->use_empty()) {
4553 SDL.setValue(AI, Args[a]);
Evan Chengf7179bb2006-04-27 08:29:42 +00004554
Chris Lattnerbf209482005-10-30 19:42:35 +00004555 // If this argument is live outside of the entry block, insert a copy from
4556 // whereever we got it to the vreg that other BB's will reference it as.
Chris Lattner251db182007-02-25 18:40:32 +00004557 DenseMap<const Value*, unsigned>::iterator VMI=FuncInfo.ValueMap.find(AI);
4558 if (VMI != FuncInfo.ValueMap.end()) {
Dan Gohman86e1ebf2008-03-27 19:56:19 +00004559 SDL.CopyValueToVirtualRegister(AI, VMI->second);
Chris Lattnerbf209482005-10-30 19:42:35 +00004560 }
Chris Lattner0afa8e32005-01-17 17:55:19 +00004561 }
Chris Lattnerbf209482005-10-30 19:42:35 +00004562
Chris Lattnerbf209482005-10-30 19:42:35 +00004563 // Finally, if the target has anything special to do, allow it to do so.
Chris Lattner96645412006-05-16 06:10:58 +00004564 // FIXME: this should insert code into the DAG!
Chris Lattnerbf209482005-10-30 19:42:35 +00004565 EmitFunctionEntryCode(F, SDL.DAG.getMachineFunction());
Chris Lattner068a81e2005-01-17 17:15:02 +00004566}
4567
Duncan Sandsf4070822007-06-15 19:04:19 +00004568static void copyCatchInfo(BasicBlock *SrcBB, BasicBlock *DestBB,
4569 MachineModuleInfo *MMI, FunctionLoweringInfo &FLI) {
Duncan Sandsf4070822007-06-15 19:04:19 +00004570 for (BasicBlock::iterator I = SrcBB->begin(), E = --SrcBB->end(); I != E; ++I)
Duncan Sandscf26d7c2007-07-04 20:52:51 +00004571 if (isSelector(I)) {
Duncan Sandsf4070822007-06-15 19:04:19 +00004572 // Apply the catch info to DestBB.
4573 addCatchInfo(cast<CallInst>(*I), MMI, FLI.MBBMap[DestBB]);
4574#ifndef NDEBUG
Duncan Sands560a7372007-11-15 09:54:37 +00004575 if (!FLI.MBBMap[SrcBB]->isLandingPad())
4576 FLI.CatchInfoFound.insert(I);
Duncan Sandsf4070822007-06-15 19:04:19 +00004577#endif
4578 }
4579}
4580
Arnold Schwaighoferc85e1712007-10-11 19:40:01 +00004581/// CheckDAGForTailCallsAndFixThem - This Function looks for CALL nodes in the
Arnold Schwaighofer48abc5c2007-10-12 21:30:57 +00004582/// DAG and fixes their tailcall attribute operand.
Arnold Schwaighoferc85e1712007-10-11 19:40:01 +00004583static void CheckDAGForTailCallsAndFixThem(SelectionDAG &DAG,
4584 TargetLowering& TLI) {
4585 SDNode * Ret = NULL;
4586 SDOperand Terminator = DAG.getRoot();
4587
4588 // Find RET node.
4589 if (Terminator.getOpcode() == ISD::RET) {
4590 Ret = Terminator.Val;
4591 }
4592
4593 // Fix tail call attribute of CALL nodes.
4594 for (SelectionDAG::allnodes_iterator BE = DAG.allnodes_begin(),
4595 BI = prior(DAG.allnodes_end()); BI != BE; --BI) {
4596 if (BI->getOpcode() == ISD::CALL) {
4597 SDOperand OpRet(Ret, 0);
4598 SDOperand OpCall(static_cast<SDNode*>(BI), 0);
4599 bool isMarkedTailCall =
4600 cast<ConstantSDNode>(OpCall.getOperand(3))->getValue() != 0;
4601 // If CALL node has tail call attribute set to true and the call is not
4602 // eligible (no RET or the target rejects) the attribute is fixed to
Arnold Schwaighofer48abc5c2007-10-12 21:30:57 +00004603 // false. The TargetLowering::IsEligibleForTailCallOptimization function
Arnold Schwaighoferc85e1712007-10-11 19:40:01 +00004604 // must correctly identify tail call optimizable calls.
4605 if (isMarkedTailCall &&
4606 (Ret==NULL ||
4607 !TLI.IsEligibleForTailCallOptimization(OpCall, OpRet, DAG))) {
4608 SmallVector<SDOperand, 32> Ops;
4609 unsigned idx=0;
4610 for(SDNode::op_iterator I =OpCall.Val->op_begin(),
4611 E=OpCall.Val->op_end(); I!=E; I++, idx++) {
4612 if (idx!=3)
4613 Ops.push_back(*I);
4614 else
4615 Ops.push_back(DAG.getConstant(false, TLI.getPointerTy()));
4616 }
4617 DAG.UpdateNodeOperands(OpCall, Ops.begin(), Ops.size());
4618 }
4619 }
4620 }
4621}
4622
Chris Lattner1c08c712005-01-07 07:47:53 +00004623void SelectionDAGISel::BuildSelectionDAG(SelectionDAG &DAG, BasicBlock *LLVMBB,
4624 std::vector<std::pair<MachineInstr*, unsigned> > &PHINodesToUpdate,
Nate Begemanf15485a2006-03-27 01:32:24 +00004625 FunctionLoweringInfo &FuncInfo) {
Gordon Henriksence224772008-01-07 01:30:38 +00004626 SelectionDAGLowering SDL(DAG, TLI, *AA, FuncInfo, GCI);
Chris Lattnerddb870b2005-01-13 17:59:43 +00004627
Chris Lattnerbf209482005-10-30 19:42:35 +00004628 // Lower any arguments needed in this block if this is the entry block.
Dan Gohmanecb7a772007-03-22 16:38:57 +00004629 if (LLVMBB == &LLVMBB->getParent()->getEntryBlock())
Dan Gohman86e1ebf2008-03-27 19:56:19 +00004630 LowerArguments(LLVMBB, SDL);
Chris Lattner1c08c712005-01-07 07:47:53 +00004631
4632 BB = FuncInfo.MBBMap[LLVMBB];
4633 SDL.setCurrentBasicBlock(BB);
4634
Duncan Sandsf4070822007-06-15 19:04:19 +00004635 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Duncan Sands9fac0b52007-06-06 10:05:18 +00004636
Dale Johannesen1532f3d2008-04-02 00:25:04 +00004637 if (MMI && BB->isLandingPad()) {
Duncan Sandsf4070822007-06-15 19:04:19 +00004638 // Add a label to mark the beginning of the landing pad. Deletion of the
4639 // landing pad can thus be detected via the MachineModuleInfo.
4640 unsigned LabelID = MMI->addLandingPad(BB);
4641 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, DAG.getEntryNode(),
Evan Chengbb81d972008-01-31 09:59:15 +00004642 DAG.getConstant(LabelID, MVT::i32),
4643 DAG.getConstant(1, MVT::i32)));
Duncan Sandsf4070822007-06-15 19:04:19 +00004644
Evan Chenge47c3332007-06-27 18:45:32 +00004645 // Mark exception register as live in.
4646 unsigned Reg = TLI.getExceptionAddressRegister();
4647 if (Reg) BB->addLiveIn(Reg);
4648
4649 // Mark exception selector register as live in.
4650 Reg = TLI.getExceptionSelectorRegister();
4651 if (Reg) BB->addLiveIn(Reg);
4652
Duncan Sandsf4070822007-06-15 19:04:19 +00004653 // FIXME: Hack around an exception handling flaw (PR1508): the personality
4654 // function and list of typeids logically belong to the invoke (or, if you
4655 // like, the basic block containing the invoke), and need to be associated
4656 // with it in the dwarf exception handling tables. Currently however the
Duncan Sandscf26d7c2007-07-04 20:52:51 +00004657 // information is provided by an intrinsic (eh.selector) that can be moved
4658 // to unexpected places by the optimizers: if the unwind edge is critical,
4659 // then breaking it can result in the intrinsics being in the successor of
4660 // the landing pad, not the landing pad itself. This results in exceptions
4661 // not being caught because no typeids are associated with the invoke.
4662 // This may not be the only way things can go wrong, but it is the only way
4663 // we try to work around for the moment.
Duncan Sandsf4070822007-06-15 19:04:19 +00004664 BranchInst *Br = dyn_cast<BranchInst>(LLVMBB->getTerminator());
4665
4666 if (Br && Br->isUnconditional()) { // Critical edge?
4667 BasicBlock::iterator I, E;
4668 for (I = LLVMBB->begin(), E = --LLVMBB->end(); I != E; ++I)
Duncan Sandscf26d7c2007-07-04 20:52:51 +00004669 if (isSelector(I))
Duncan Sandsf4070822007-06-15 19:04:19 +00004670 break;
4671
4672 if (I == E)
4673 // No catch info found - try to extract some from the successor.
4674 copyCatchInfo(Br->getSuccessor(0), LLVMBB, MMI, FuncInfo);
Duncan Sands9fac0b52007-06-06 10:05:18 +00004675 }
4676 }
4677
Chris Lattner1c08c712005-01-07 07:47:53 +00004678 // Lower all of the non-terminator instructions.
4679 for (BasicBlock::iterator I = LLVMBB->begin(), E = --LLVMBB->end();
4680 I != E; ++I)
4681 SDL.visit(*I);
Duncan Sandsf19f6bb2007-06-13 05:51:31 +00004682
Chris Lattner1c08c712005-01-07 07:47:53 +00004683 // Ensure that all instructions which are used outside of their defining
Duncan Sandsf19f6bb2007-06-13 05:51:31 +00004684 // blocks are available as virtual registers. Invoke is handled elsewhere.
Chris Lattner1c08c712005-01-07 07:47:53 +00004685 for (BasicBlock::iterator I = LLVMBB->begin(), E = LLVMBB->end(); I != E;++I)
Duncan Sandsf19f6bb2007-06-13 05:51:31 +00004686 if (!I->use_empty() && !isa<PHINode>(I) && !isa<InvokeInst>(I)) {
Chris Lattner9f24ad72007-02-04 01:35:11 +00004687 DenseMap<const Value*, unsigned>::iterator VMI =FuncInfo.ValueMap.find(I);
Chris Lattner1c08c712005-01-07 07:47:53 +00004688 if (VMI != FuncInfo.ValueMap.end())
Dan Gohman86e1ebf2008-03-27 19:56:19 +00004689 SDL.CopyValueToVirtualRegister(I, VMI->second);
Chris Lattner1c08c712005-01-07 07:47:53 +00004690 }
4691
4692 // Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
4693 // ensure constants are generated when needed. Remember the virtual registers
4694 // that need to be added to the Machine PHI nodes as input. We cannot just
4695 // directly add them, because expansion might result in multiple MBB's for one
4696 // BB. As such, the start of the BB might correspond to a different MBB than
4697 // the end.
Misha Brukmanedf128a2005-04-21 22:36:52 +00004698 //
Chris Lattner8c494ab2006-10-27 23:50:33 +00004699 TerminatorInst *TI = LLVMBB->getTerminator();
Chris Lattner1c08c712005-01-07 07:47:53 +00004700
4701 // Emit constants only once even if used by multiple PHI nodes.
4702 std::map<Constant*, unsigned> ConstantsOut;
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004703
Chris Lattner8c494ab2006-10-27 23:50:33 +00004704 // Vector bool would be better, but vector<bool> is really slow.
4705 std::vector<unsigned char> SuccsHandled;
4706 if (TI->getNumSuccessors())
4707 SuccsHandled.resize(BB->getParent()->getNumBlockIDs());
4708
Dan Gohman532dc2e2007-07-09 20:59:04 +00004709 // Check successor nodes' PHI nodes that expect a constant to be available
4710 // from this block.
Chris Lattner1c08c712005-01-07 07:47:53 +00004711 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
4712 BasicBlock *SuccBB = TI->getSuccessor(succ);
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004713 if (!isa<PHINode>(SuccBB->begin())) continue;
Chris Lattner8c494ab2006-10-27 23:50:33 +00004714 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004715
Chris Lattner8c494ab2006-10-27 23:50:33 +00004716 // If this terminator has multiple identical successors (common for
4717 // switches), only handle each succ once.
4718 unsigned SuccMBBNo = SuccMBB->getNumber();
4719 if (SuccsHandled[SuccMBBNo]) continue;
4720 SuccsHandled[SuccMBBNo] = true;
4721
4722 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
Chris Lattner1c08c712005-01-07 07:47:53 +00004723 PHINode *PN;
4724
4725 // At this point we know that there is a 1-1 correspondence between LLVM PHI
4726 // nodes and Machine PHI nodes, but the incoming operands have not been
4727 // emitted yet.
4728 for (BasicBlock::iterator I = SuccBB->begin();
Chris Lattner8c494ab2006-10-27 23:50:33 +00004729 (PN = dyn_cast<PHINode>(I)); ++I) {
4730 // Ignore dead phi's.
4731 if (PN->use_empty()) continue;
4732
4733 unsigned Reg;
4734 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
Chris Lattner3f7927c2006-11-29 01:12:32 +00004735
Chris Lattner8c494ab2006-10-27 23:50:33 +00004736 if (Constant *C = dyn_cast<Constant>(PHIOp)) {
4737 unsigned &RegOut = ConstantsOut[C];
4738 if (RegOut == 0) {
4739 RegOut = FuncInfo.CreateRegForValue(C);
Dan Gohman86e1ebf2008-03-27 19:56:19 +00004740 SDL.CopyValueToVirtualRegister(C, RegOut);
Chris Lattner1c08c712005-01-07 07:47:53 +00004741 }
Chris Lattner8c494ab2006-10-27 23:50:33 +00004742 Reg = RegOut;
4743 } else {
4744 Reg = FuncInfo.ValueMap[PHIOp];
4745 if (Reg == 0) {
4746 assert(isa<AllocaInst>(PHIOp) &&
4747 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
4748 "Didn't codegen value into a register!??");
4749 Reg = FuncInfo.CreateRegForValue(PHIOp);
Dan Gohman86e1ebf2008-03-27 19:56:19 +00004750 SDL.CopyValueToVirtualRegister(PHIOp, Reg);
Chris Lattner7e021512006-03-31 02:12:18 +00004751 }
Chris Lattner1c08c712005-01-07 07:47:53 +00004752 }
Chris Lattner8c494ab2006-10-27 23:50:33 +00004753
4754 // Remember that this register needs to added to the machine PHI node as
4755 // the input for this MBB.
4756 MVT::ValueType VT = TLI.getValueType(PN->getType());
Dan Gohman7f321562007-06-25 16:23:39 +00004757 unsigned NumRegisters = TLI.getNumRegisters(VT);
Dan Gohmanb9f10192007-06-21 14:42:22 +00004758 for (unsigned i = 0, e = NumRegisters; i != e; ++i)
Chris Lattner8c494ab2006-10-27 23:50:33 +00004759 PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
4760 }
Chris Lattner1c08c712005-01-07 07:47:53 +00004761 }
4762 ConstantsOut.clear();
4763
4764 // Lower the terminator after the copies are emitted.
Duncan Sandsf19f6bb2007-06-13 05:51:31 +00004765 SDL.visit(*LLVMBB->getTerminator());
Chris Lattnera651cf62005-01-17 19:43:36 +00004766
Nate Begemanf15485a2006-03-27 01:32:24 +00004767 // Copy over any CaseBlock records that may now exist due to SwitchInst
Nate Begeman37efe672006-04-22 18:53:45 +00004768 // lowering, as well as any jump table information.
Nate Begemanf15485a2006-03-27 01:32:24 +00004769 SwitchCases.clear();
4770 SwitchCases = SDL.SwitchCases;
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00004771 JTCases.clear();
4772 JTCases = SDL.JTCases;
Anton Korobeynikov4198c582007-04-09 12:31:58 +00004773 BitTestCases.clear();
4774 BitTestCases = SDL.BitTestCases;
4775
Chris Lattnera651cf62005-01-17 19:43:36 +00004776 // Make sure the root of the DAG is up-to-date.
Dan Gohman86e1ebf2008-03-27 19:56:19 +00004777 DAG.setRoot(SDL.getControlRoot());
Arnold Schwaighoferc85e1712007-10-11 19:40:01 +00004778
4779 // Check whether calls in this block are real tail calls. Fix up CALL nodes
4780 // with correct tailcall attribute so that the target can rely on the tailcall
4781 // attribute indicating whether the call is really eligible for tail call
4782 // optimization.
4783 CheckDAGForTailCallsAndFixThem(DAG, TLI);
Chris Lattner1c08c712005-01-07 07:47:53 +00004784}
4785
Nate Begemanf15485a2006-03-27 01:32:24 +00004786void SelectionDAGISel::CodeGenAndEmitDAG(SelectionDAG &DAG) {
Dan Gohman417e11b2007-10-08 15:12:17 +00004787 DOUT << "Lowered selection DAG:\n";
4788 DEBUG(DAG.dump());
4789
Chris Lattneraf21d552005-10-10 16:47:10 +00004790 // Run the DAG combiner in pre-legalize mode.
Dan Gohman5f43f922007-08-27 16:26:13 +00004791 DAG.Combine(false, *AA);
Nate Begeman2300f552005-09-07 00:15:36 +00004792
Dan Gohman417e11b2007-10-08 15:12:17 +00004793 DOUT << "Optimized lowered selection DAG:\n";
Chris Lattner1c08c712005-01-07 07:47:53 +00004794 DEBUG(DAG.dump());
Nate Begemanf15485a2006-03-27 01:32:24 +00004795
Chris Lattner1c08c712005-01-07 07:47:53 +00004796 // Second step, hack on the DAG until it only uses operations and types that
4797 // the target supports.
Chris Lattner01d029b2007-10-15 06:10:22 +00004798#if 0 // Enable this some day.
4799 DAG.LegalizeTypes();
4800 // Someday even later, enable a dag combine pass here.
4801#endif
Chris Lattnerac9dc082005-01-23 04:36:26 +00004802 DAG.Legalize();
Nate Begemanf15485a2006-03-27 01:32:24 +00004803
Bill Wendling832171c2006-12-07 20:04:42 +00004804 DOUT << "Legalized selection DAG:\n";
Chris Lattner1c08c712005-01-07 07:47:53 +00004805 DEBUG(DAG.dump());
Nate Begemanf15485a2006-03-27 01:32:24 +00004806
Chris Lattneraf21d552005-10-10 16:47:10 +00004807 // Run the DAG combiner in post-legalize mode.
Dan Gohman5f43f922007-08-27 16:26:13 +00004808 DAG.Combine(true, *AA);
Nate Begeman2300f552005-09-07 00:15:36 +00004809
Dan Gohman417e11b2007-10-08 15:12:17 +00004810 DOUT << "Optimized legalized selection DAG:\n";
4811 DEBUG(DAG.dump());
4812
Evan Chenga9c20912006-01-21 02:32:06 +00004813 if (ViewISelDAGs) DAG.viewGraph();
Evan Cheng552c4a82006-04-28 02:09:19 +00004814
Chris Lattnera33ef482005-03-30 01:10:47 +00004815 // Third, instruction select all of the operations to machine code, adding the
4816 // code to the MachineBasicBlock.
Chris Lattner1c08c712005-01-07 07:47:53 +00004817 InstructionSelectBasicBlock(DAG);
Nate Begemanf15485a2006-03-27 01:32:24 +00004818
Bill Wendling832171c2006-12-07 20:04:42 +00004819 DOUT << "Selected machine code:\n";
Chris Lattner1c08c712005-01-07 07:47:53 +00004820 DEBUG(BB->dump());
Nate Begemanf15485a2006-03-27 01:32:24 +00004821}
Chris Lattner1c08c712005-01-07 07:47:53 +00004822
Nate Begemanf15485a2006-03-27 01:32:24 +00004823void SelectionDAGISel::SelectBasicBlock(BasicBlock *LLVMBB, MachineFunction &MF,
4824 FunctionLoweringInfo &FuncInfo) {
4825 std::vector<std::pair<MachineInstr*, unsigned> > PHINodesToUpdate;
4826 {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00004827 SelectionDAG DAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
Nate Begemanf15485a2006-03-27 01:32:24 +00004828 CurDAG = &DAG;
4829
4830 // First step, lower LLVM code to some DAG. This DAG may use operations and
4831 // types that are not supported by the target.
4832 BuildSelectionDAG(DAG, LLVMBB, PHINodesToUpdate, FuncInfo);
4833
4834 // Second step, emit the lowered DAG as machine code.
4835 CodeGenAndEmitDAG(DAG);
4836 }
Anton Korobeynikov4198c582007-04-09 12:31:58 +00004837
4838 DOUT << "Total amount of phi nodes to update: "
4839 << PHINodesToUpdate.size() << "\n";
4840 DEBUG(for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i)
4841 DOUT << "Node " << i << " : (" << PHINodesToUpdate[i].first
4842 << ", " << PHINodesToUpdate[i].second << ")\n";);
Nate Begemanf15485a2006-03-27 01:32:24 +00004843
Chris Lattnera33ef482005-03-30 01:10:47 +00004844 // Next, now that we know what the last MBB the LLVM BB expanded is, update
Chris Lattner1c08c712005-01-07 07:47:53 +00004845 // PHI nodes in successors.
Anton Korobeynikov4198c582007-04-09 12:31:58 +00004846 if (SwitchCases.empty() && JTCases.empty() && BitTestCases.empty()) {
Nate Begemanf15485a2006-03-27 01:32:24 +00004847 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
4848 MachineInstr *PHI = PHINodesToUpdate[i].first;
4849 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
4850 "This is not a machine PHI node that we are updating!");
Chris Lattner9ce2e9d2007-12-30 00:57:42 +00004851 PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[i].second,
4852 false));
4853 PHI->addOperand(MachineOperand::CreateMBB(BB));
Nate Begemanf15485a2006-03-27 01:32:24 +00004854 }
4855 return;
Chris Lattner1c08c712005-01-07 07:47:53 +00004856 }
Anton Korobeynikov4198c582007-04-09 12:31:58 +00004857
4858 for (unsigned i = 0, e = BitTestCases.size(); i != e; ++i) {
4859 // Lower header first, if it wasn't already lowered
4860 if (!BitTestCases[i].Emitted) {
4861 SelectionDAG HSDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
4862 CurDAG = &HSDAG;
Gordon Henriksence224772008-01-07 01:30:38 +00004863 SelectionDAGLowering HSDL(HSDAG, TLI, *AA, FuncInfo, GCI);
Anton Korobeynikov4198c582007-04-09 12:31:58 +00004864 // Set the current basic block to the mbb we wish to insert the code into
4865 BB = BitTestCases[i].Parent;
4866 HSDL.setCurrentBasicBlock(BB);
4867 // Emit the code
4868 HSDL.visitBitTestHeader(BitTestCases[i]);
4869 HSDAG.setRoot(HSDL.getRoot());
4870 CodeGenAndEmitDAG(HSDAG);
4871 }
4872
4873 for (unsigned j = 0, ej = BitTestCases[i].Cases.size(); j != ej; ++j) {
4874 SelectionDAG BSDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
4875 CurDAG = &BSDAG;
Gordon Henriksence224772008-01-07 01:30:38 +00004876 SelectionDAGLowering BSDL(BSDAG, TLI, *AA, FuncInfo, GCI);
Anton Korobeynikov4198c582007-04-09 12:31:58 +00004877 // Set the current basic block to the mbb we wish to insert the code into
4878 BB = BitTestCases[i].Cases[j].ThisBB;
4879 BSDL.setCurrentBasicBlock(BB);
4880 // Emit the code
4881 if (j+1 != ej)
4882 BSDL.visitBitTestCase(BitTestCases[i].Cases[j+1].ThisBB,
4883 BitTestCases[i].Reg,
4884 BitTestCases[i].Cases[j]);
4885 else
4886 BSDL.visitBitTestCase(BitTestCases[i].Default,
4887 BitTestCases[i].Reg,
4888 BitTestCases[i].Cases[j]);
4889
4890
4891 BSDAG.setRoot(BSDL.getRoot());
4892 CodeGenAndEmitDAG(BSDAG);
4893 }
4894
4895 // Update PHI Nodes
4896 for (unsigned pi = 0, pe = PHINodesToUpdate.size(); pi != pe; ++pi) {
4897 MachineInstr *PHI = PHINodesToUpdate[pi].first;
4898 MachineBasicBlock *PHIBB = PHI->getParent();
4899 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
4900 "This is not a machine PHI node that we are updating!");
4901 // This is "default" BB. We have two jumps to it. From "header" BB and
4902 // from last "case" BB.
4903 if (PHIBB == BitTestCases[i].Default) {
Chris Lattner9ce2e9d2007-12-30 00:57:42 +00004904 PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[pi].second,
4905 false));
4906 PHI->addOperand(MachineOperand::CreateMBB(BitTestCases[i].Parent));
4907 PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[pi].second,
4908 false));
4909 PHI->addOperand(MachineOperand::CreateMBB(BitTestCases[i].Cases.
4910 back().ThisBB));
Anton Korobeynikov4198c582007-04-09 12:31:58 +00004911 }
4912 // One of "cases" BB.
4913 for (unsigned j = 0, ej = BitTestCases[i].Cases.size(); j != ej; ++j) {
4914 MachineBasicBlock* cBB = BitTestCases[i].Cases[j].ThisBB;
4915 if (cBB->succ_end() !=
4916 std::find(cBB->succ_begin(),cBB->succ_end(), PHIBB)) {
Chris Lattner9ce2e9d2007-12-30 00:57:42 +00004917 PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[pi].second,
4918 false));
4919 PHI->addOperand(MachineOperand::CreateMBB(cBB));
Anton Korobeynikov4198c582007-04-09 12:31:58 +00004920 }
4921 }
4922 }
4923 }
4924
Nate Begeman9453eea2006-04-23 06:26:20 +00004925 // If the JumpTable record is filled in, then we need to emit a jump table.
4926 // Updating the PHI nodes is tricky in this case, since we need to determine
4927 // whether the PHI is a successor of the range check MBB or the jump table MBB
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00004928 for (unsigned i = 0, e = JTCases.size(); i != e; ++i) {
4929 // Lower header first, if it wasn't already lowered
4930 if (!JTCases[i].first.Emitted) {
4931 SelectionDAG HSDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
4932 CurDAG = &HSDAG;
Gordon Henriksence224772008-01-07 01:30:38 +00004933 SelectionDAGLowering HSDL(HSDAG, TLI, *AA, FuncInfo, GCI);
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00004934 // Set the current basic block to the mbb we wish to insert the code into
4935 BB = JTCases[i].first.HeaderBB;
4936 HSDL.setCurrentBasicBlock(BB);
4937 // Emit the code
4938 HSDL.visitJumpTableHeader(JTCases[i].second, JTCases[i].first);
4939 HSDAG.setRoot(HSDL.getRoot());
4940 CodeGenAndEmitDAG(HSDAG);
Anton Korobeynikov4198c582007-04-09 12:31:58 +00004941 }
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00004942
4943 SelectionDAG JSDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
4944 CurDAG = &JSDAG;
Gordon Henriksence224772008-01-07 01:30:38 +00004945 SelectionDAGLowering JSDL(JSDAG, TLI, *AA, FuncInfo, GCI);
Nate Begeman37efe672006-04-22 18:53:45 +00004946 // Set the current basic block to the mbb we wish to insert the code into
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00004947 BB = JTCases[i].second.MBB;
4948 JSDL.setCurrentBasicBlock(BB);
Nate Begeman37efe672006-04-22 18:53:45 +00004949 // Emit the code
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00004950 JSDL.visitJumpTable(JTCases[i].second);
4951 JSDAG.setRoot(JSDL.getRoot());
4952 CodeGenAndEmitDAG(JSDAG);
4953
Nate Begeman37efe672006-04-22 18:53:45 +00004954 // Update PHI Nodes
4955 for (unsigned pi = 0, pe = PHINodesToUpdate.size(); pi != pe; ++pi) {
4956 MachineInstr *PHI = PHINodesToUpdate[pi].first;
4957 MachineBasicBlock *PHIBB = PHI->getParent();
4958 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
4959 "This is not a machine PHI node that we are updating!");
Anton Korobeynikov4198c582007-04-09 12:31:58 +00004960 // "default" BB. We can go there only from header BB.
Anton Korobeynikov3a84b9b2007-03-25 15:07:15 +00004961 if (PHIBB == JTCases[i].second.Default) {
Chris Lattner9ce2e9d2007-12-30 00:57:42 +00004962 PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[pi].second,
4963 false));
4964 PHI->addOperand(MachineOperand::CreateMBB(JTCases[i].first.HeaderBB));
Nate Begemanf4360a42006-05-03 03:48:02 +00004965 }
Anton Korobeynikov4198c582007-04-09 12:31:58 +00004966 // JT BB. Just iterate over successors here
Nate Begemanf4360a42006-05-03 03:48:02 +00004967 if (BB->succ_end() != std::find(BB->succ_begin(),BB->succ_end(), PHIBB)) {
Chris Lattner9ce2e9d2007-12-30 00:57:42 +00004968 PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[pi].second,
4969 false));
4970 PHI->addOperand(MachineOperand::CreateMBB(BB));
Nate Begeman37efe672006-04-22 18:53:45 +00004971 }
4972 }
Nate Begeman37efe672006-04-22 18:53:45 +00004973 }
4974
Chris Lattnerb2e806e2006-10-22 23:00:53 +00004975 // If the switch block involved a branch to one of the actual successors, we
4976 // need to update PHI nodes in that block.
4977 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
4978 MachineInstr *PHI = PHINodesToUpdate[i].first;
4979 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
4980 "This is not a machine PHI node that we are updating!");
4981 if (BB->isSuccessor(PHI->getParent())) {
Chris Lattner9ce2e9d2007-12-30 00:57:42 +00004982 PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[i].second,
4983 false));
4984 PHI->addOperand(MachineOperand::CreateMBB(BB));
Chris Lattnerb2e806e2006-10-22 23:00:53 +00004985 }
4986 }
4987
Nate Begemanf15485a2006-03-27 01:32:24 +00004988 // If we generated any switch lowering information, build and codegen any
4989 // additional DAGs necessary.
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004990 for (unsigned i = 0, e = SwitchCases.size(); i != e; ++i) {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00004991 SelectionDAG SDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
Nate Begemanf15485a2006-03-27 01:32:24 +00004992 CurDAG = &SDAG;
Gordon Henriksence224772008-01-07 01:30:38 +00004993 SelectionDAGLowering SDL(SDAG, TLI, *AA, FuncInfo, GCI);
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004994
Nate Begemanf15485a2006-03-27 01:32:24 +00004995 // Set the current basic block to the mbb we wish to insert the code into
4996 BB = SwitchCases[i].ThisBB;
4997 SDL.setCurrentBasicBlock(BB);
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004998
Nate Begemanf15485a2006-03-27 01:32:24 +00004999 // Emit the code
5000 SDL.visitSwitchCase(SwitchCases[i]);
5001 SDAG.setRoot(SDL.getRoot());
5002 CodeGenAndEmitDAG(SDAG);
Chris Lattnerd5e93c02006-09-07 01:59:34 +00005003
5004 // Handle any PHI nodes in successors of this chunk, as if we were coming
5005 // from the original BB before switch expansion. Note that PHI nodes can
5006 // occur multiple times in PHINodesToUpdate. We have to be very careful to
5007 // handle them the right number of times.
Chris Lattner57ab6592006-10-24 17:57:59 +00005008 while ((BB = SwitchCases[i].TrueBB)) { // Handle LHS and RHS.
Chris Lattnerd5e93c02006-09-07 01:59:34 +00005009 for (MachineBasicBlock::iterator Phi = BB->begin();
5010 Phi != BB->end() && Phi->getOpcode() == TargetInstrInfo::PHI; ++Phi){
5011 // This value for this PHI node is recorded in PHINodesToUpdate, get it.
5012 for (unsigned pn = 0; ; ++pn) {
5013 assert(pn != PHINodesToUpdate.size() && "Didn't find PHI entry!");
5014 if (PHINodesToUpdate[pn].first == Phi) {
Chris Lattner9ce2e9d2007-12-30 00:57:42 +00005015 Phi->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[pn].
5016 second, false));
5017 Phi->addOperand(MachineOperand::CreateMBB(SwitchCases[i].ThisBB));
Chris Lattnerd5e93c02006-09-07 01:59:34 +00005018 break;
5019 }
5020 }
Nate Begemanf15485a2006-03-27 01:32:24 +00005021 }
Chris Lattnerd5e93c02006-09-07 01:59:34 +00005022
5023 // Don't process RHS if same block as LHS.
Chris Lattner57ab6592006-10-24 17:57:59 +00005024 if (BB == SwitchCases[i].FalseBB)
5025 SwitchCases[i].FalseBB = 0;
Chris Lattnerd5e93c02006-09-07 01:59:34 +00005026
5027 // If we haven't handled the RHS, do so now. Otherwise, we're done.
Chris Lattner24525952006-10-24 18:07:37 +00005028 SwitchCases[i].TrueBB = SwitchCases[i].FalseBB;
Chris Lattner57ab6592006-10-24 17:57:59 +00005029 SwitchCases[i].FalseBB = 0;
Nate Begemanf15485a2006-03-27 01:32:24 +00005030 }
Chris Lattner57ab6592006-10-24 17:57:59 +00005031 assert(SwitchCases[i].TrueBB == 0 && SwitchCases[i].FalseBB == 0);
Chris Lattnera33ef482005-03-30 01:10:47 +00005032 }
Chris Lattner1c08c712005-01-07 07:47:53 +00005033}
Evan Chenga9c20912006-01-21 02:32:06 +00005034
Jim Laskey13ec7022006-08-01 14:21:23 +00005035
Evan Chenga9c20912006-01-21 02:32:06 +00005036//===----------------------------------------------------------------------===//
5037/// ScheduleAndEmitDAG - Pick a safe ordering and emit instructions for each
5038/// target node in the graph.
5039void SelectionDAGISel::ScheduleAndEmitDAG(SelectionDAG &DAG) {
5040 if (ViewSchedDAGs) DAG.viewGraph();
Evan Cheng4ef10862006-01-23 07:01:07 +00005041
Jim Laskeyeb577ba2006-08-02 12:30:23 +00005042 RegisterScheduler::FunctionPassCtor Ctor = RegisterScheduler::getDefault();
Jim Laskey13ec7022006-08-01 14:21:23 +00005043
5044 if (!Ctor) {
Jim Laskeyeb577ba2006-08-02 12:30:23 +00005045 Ctor = ISHeuristic;
Jim Laskey9373beb2006-08-01 19:14:14 +00005046 RegisterScheduler::setDefault(Ctor);
Evan Cheng4ef10862006-01-23 07:01:07 +00005047 }
Jim Laskey13ec7022006-08-01 14:21:23 +00005048
Jim Laskey9ff542f2006-08-01 18:29:48 +00005049 ScheduleDAG *SL = Ctor(this, &DAG, BB);
Chris Lattnera3818e62006-01-21 19:12:11 +00005050 BB = SL->Run();
Dan Gohman3e1a7ae2007-08-28 20:32:58 +00005051
5052 if (ViewSUnitDAGs) SL->viewGraph();
5053
Evan Chengcccf1232006-02-04 06:49:00 +00005054 delete SL;
Evan Chenga9c20912006-01-21 02:32:06 +00005055}
Chris Lattner0e43f2b2006-02-24 02:13:54 +00005056
Chris Lattner03fc53c2006-03-06 00:22:00 +00005057
Jim Laskey9ff542f2006-08-01 18:29:48 +00005058HazardRecognizer *SelectionDAGISel::CreateTargetHazardRecognizer() {
5059 return new HazardRecognizer();
5060}
5061
Chris Lattner75548062006-10-11 03:58:02 +00005062//===----------------------------------------------------------------------===//
5063// Helper functions used by the generated instruction selector.
5064//===----------------------------------------------------------------------===//
5065// Calls to these methods are generated by tblgen.
5066
5067/// CheckAndMask - The isel is trying to match something like (and X, 255). If
5068/// the dag combiner simplified the 255, we still want to match. RHS is the
5069/// actual value in the DAG on the RHS of an AND, and DesiredMaskS is the value
5070/// specified in the .td file (e.g. 255).
5071bool SelectionDAGISel::CheckAndMask(SDOperand LHS, ConstantSDNode *RHS,
Dan Gohmandc9b3d02007-07-24 23:00:27 +00005072 int64_t DesiredMaskS) const {
Dan Gohman2e68b6f2008-02-25 21:11:39 +00005073 const APInt &ActualMask = RHS->getAPIntValue();
5074 const APInt &DesiredMask = APInt(LHS.getValueSizeInBits(), DesiredMaskS);
Chris Lattner75548062006-10-11 03:58:02 +00005075
5076 // If the actual mask exactly matches, success!
5077 if (ActualMask == DesiredMask)
5078 return true;
5079
5080 // If the actual AND mask is allowing unallowed bits, this doesn't match.
Dan Gohman2e68b6f2008-02-25 21:11:39 +00005081 if (ActualMask.intersects(~DesiredMask))
Chris Lattner75548062006-10-11 03:58:02 +00005082 return false;
5083
5084 // Otherwise, the DAG Combiner may have proven that the value coming in is
5085 // either already zero or is not demanded. Check for known zero input bits.
Dan Gohman2e68b6f2008-02-25 21:11:39 +00005086 APInt NeededMask = DesiredMask & ~ActualMask;
Dan Gohmanea859be2007-06-22 14:59:07 +00005087 if (CurDAG->MaskedValueIsZero(LHS, NeededMask))
Chris Lattner75548062006-10-11 03:58:02 +00005088 return true;
5089
5090 // TODO: check to see if missing bits are just not demanded.
5091
5092 // Otherwise, this pattern doesn't match.
5093 return false;
5094}
5095
5096/// CheckOrMask - The isel is trying to match something like (or X, 255). If
5097/// the dag combiner simplified the 255, we still want to match. RHS is the
5098/// actual value in the DAG on the RHS of an OR, and DesiredMaskS is the value
5099/// specified in the .td file (e.g. 255).
5100bool SelectionDAGISel::CheckOrMask(SDOperand LHS, ConstantSDNode *RHS,
Dan Gohman2e68b6f2008-02-25 21:11:39 +00005101 int64_t DesiredMaskS) const {
5102 const APInt &ActualMask = RHS->getAPIntValue();
5103 const APInt &DesiredMask = APInt(LHS.getValueSizeInBits(), DesiredMaskS);
Chris Lattner75548062006-10-11 03:58:02 +00005104
5105 // If the actual mask exactly matches, success!
5106 if (ActualMask == DesiredMask)
5107 return true;
5108
5109 // If the actual AND mask is allowing unallowed bits, this doesn't match.
Dan Gohman2e68b6f2008-02-25 21:11:39 +00005110 if (ActualMask.intersects(~DesiredMask))
Chris Lattner75548062006-10-11 03:58:02 +00005111 return false;
5112
5113 // Otherwise, the DAG Combiner may have proven that the value coming in is
5114 // either already zero or is not demanded. Check for known zero input bits.
Dan Gohman2e68b6f2008-02-25 21:11:39 +00005115 APInt NeededMask = DesiredMask & ~ActualMask;
Chris Lattner75548062006-10-11 03:58:02 +00005116
Dan Gohman2e68b6f2008-02-25 21:11:39 +00005117 APInt KnownZero, KnownOne;
Dan Gohmanea859be2007-06-22 14:59:07 +00005118 CurDAG->ComputeMaskedBits(LHS, NeededMask, KnownZero, KnownOne);
Chris Lattner75548062006-10-11 03:58:02 +00005119
5120 // If all the missing bits in the or are already known to be set, match!
5121 if ((NeededMask & KnownOne) == NeededMask)
5122 return true;
5123
5124 // TODO: check to see if missing bits are just not demanded.
5125
5126 // Otherwise, this pattern doesn't match.
5127 return false;
5128}
5129
Jim Laskey9ff542f2006-08-01 18:29:48 +00005130
Chris Lattner0e43f2b2006-02-24 02:13:54 +00005131/// SelectInlineAsmMemoryOperands - Calls to this are automatically generated
5132/// by tblgen. Others should not call it.
5133void SelectionDAGISel::
5134SelectInlineAsmMemoryOperands(std::vector<SDOperand> &Ops, SelectionDAG &DAG) {
5135 std::vector<SDOperand> InOps;
5136 std::swap(InOps, Ops);
5137
5138 Ops.push_back(InOps[0]); // input chain.
5139 Ops.push_back(InOps[1]); // input asm string.
5140
Chris Lattner0e43f2b2006-02-24 02:13:54 +00005141 unsigned i = 2, e = InOps.size();
5142 if (InOps[e-1].getValueType() == MVT::Flag)
5143 --e; // Don't process a flag operand if it is here.
5144
5145 while (i != e) {
5146 unsigned Flags = cast<ConstantSDNode>(InOps[i])->getValue();
5147 if ((Flags & 7) != 4 /*MEM*/) {
5148 // Just skip over this operand, copying the operands verbatim.
5149 Ops.insert(Ops.end(), InOps.begin()+i, InOps.begin()+i+(Flags >> 3) + 1);
5150 i += (Flags >> 3) + 1;
5151 } else {
5152 assert((Flags >> 3) == 1 && "Memory operand with multiple values?");
5153 // Otherwise, this is a memory operand. Ask the target to select it.
5154 std::vector<SDOperand> SelOps;
5155 if (SelectInlineAsmMemoryOperand(InOps[i+1], 'm', SelOps, DAG)) {
Bill Wendling832171c2006-12-07 20:04:42 +00005156 cerr << "Could not match memory address. Inline asm failure!\n";
Chris Lattner0e43f2b2006-02-24 02:13:54 +00005157 exit(1);
5158 }
5159
5160 // Add this to the output node.
Chris Lattner4b993b12007-04-09 00:33:58 +00005161 MVT::ValueType IntPtrTy = DAG.getTargetLoweringInfo().getPointerTy();
Chris Lattner36d43962006-12-16 21:14:48 +00005162 Ops.push_back(DAG.getTargetConstant(4/*MEM*/ | (SelOps.size() << 3),
Chris Lattner4b993b12007-04-09 00:33:58 +00005163 IntPtrTy));
Chris Lattner0e43f2b2006-02-24 02:13:54 +00005164 Ops.insert(Ops.end(), SelOps.begin(), SelOps.end());
5165 i += 2;
5166 }
5167 }
5168
5169 // Add the flag input back if present.
5170 if (e != InOps.size())
5171 Ops.push_back(InOps.back());
5172}
Devang Patel794fd752007-05-01 21:15:47 +00005173
Devang Patel19974732007-05-03 01:11:54 +00005174char SelectionDAGISel::ID = 0;