blob: d810615f4c545800907f19a49f25c69de20d6a42 [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//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source 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"
Jim Laskeyc7c3f112006-10-16 20:52:31 +000015#include "llvm/Analysis/AliasAnalysis.h"
Evan Cheng3cd4e502007-03-16 08:46:27 +000016#include "llvm/Analysis/LoopInfo.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"
Chris Lattneradf6a962005-05-13 18:50:42 +000019#include "llvm/CallingConv.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000020#include "llvm/Constants.h"
21#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"
Jim Laskey44c3b9f2007-01-26 21:22:28 +000028#include "llvm/CodeGen/MachineModuleInfo.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000029#include "llvm/CodeGen/MachineFunction.h"
30#include "llvm/CodeGen/MachineFrameInfo.h"
Nate Begeman37efe672006-04-22 18:53:45 +000031#include "llvm/CodeGen/MachineJumpTableInfo.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000032#include "llvm/CodeGen/MachineInstrBuilder.h"
Jim Laskeyeb577ba2006-08-02 12:30:23 +000033#include "llvm/CodeGen/SchedulerRegistry.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000034#include "llvm/CodeGen/SelectionDAG.h"
35#include "llvm/CodeGen/SSARegMap.h"
Chris Lattnerfa577022005-09-13 19:30:54 +000036#include "llvm/Target/MRegisterInfo.h"
Chris Lattner3f7927c2006-11-29 01:12:32 +000037#include "llvm/Target/TargetAsmInfo.h"
Chris Lattner1c08c712005-01-07 07:47:53 +000038#include "llvm/Target/TargetData.h"
39#include "llvm/Target/TargetFrameInfo.h"
40#include "llvm/Target/TargetInstrInfo.h"
41#include "llvm/Target/TargetLowering.h"
42#include "llvm/Target/TargetMachine.h"
Vladimir Prus12472912006-05-23 13:43:15 +000043#include "llvm/Target/TargetOptions.h"
Chris Lattner495a0b52005-08-17 06:37:43 +000044#include "llvm/Transforms/Utils/BasicBlockUtils.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"));
Chris Lattner7944d9d2005-01-12 03:41:21 +000058#else
Chris Lattner5e46a192006-04-02 03:07:27 +000059static const bool ViewISelDAGs = 0, ViewSchedDAGs = 0;
Chris Lattner7944d9d2005-01-12 03:41:21 +000060#endif
61
Evan Cheng3cd4e502007-03-16 08:46:27 +000062static cl::opt<bool>
63EnableGEPIndexSink("enable-gep-index-sinking", cl::Hidden,
64 cl::desc("Sink invariant GEP index computation into use blocks"));
Jim Laskeyeb577ba2006-08-02 12:30:23 +000065
66//===---------------------------------------------------------------------===//
67///
68/// RegisterScheduler class - Track the registration of instruction schedulers.
69///
70//===---------------------------------------------------------------------===//
71MachinePassRegistry RegisterScheduler::Registry;
72
73//===---------------------------------------------------------------------===//
74///
75/// ISHeuristic command line option for instruction schedulers.
76///
77//===---------------------------------------------------------------------===//
Evan Cheng4ef10862006-01-23 07:01:07 +000078namespace {
Jim Laskeyeb577ba2006-08-02 12:30:23 +000079 cl::opt<RegisterScheduler::FunctionPassCtor, false,
80 RegisterPassParser<RegisterScheduler> >
Jim Laskey13ec7022006-08-01 14:21:23 +000081 ISHeuristic("sched",
Chris Lattner3700f902006-08-03 00:18:59 +000082 cl::init(&createDefaultScheduler),
Jim Laskey13ec7022006-08-01 14:21:23 +000083 cl::desc("Instruction schedulers available:"));
84
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
Chris Lattner864635a2006-02-22 22:37:12 +000090namespace {
91 /// RegsForValue - This struct represents the physical registers that a
92 /// particular value is assigned and the type information about the value.
93 /// This is needed because values can be promoted into larger registers and
94 /// expanded into multiple smaller registers than the value.
Chris Lattner95255282006-06-28 23:17:24 +000095 struct VISIBILITY_HIDDEN RegsForValue {
Chris Lattner864635a2006-02-22 22:37:12 +000096 /// Regs - This list hold the register (for legal and promoted values)
97 /// or register set (for expanded values) that the value should be assigned
98 /// to.
99 std::vector<unsigned> Regs;
100
101 /// RegVT - The value type of each register.
102 ///
103 MVT::ValueType RegVT;
104
105 /// ValueVT - The value type of the LLVM value, which may be promoted from
106 /// RegVT or made from merging the two expanded parts.
107 MVT::ValueType ValueVT;
108
109 RegsForValue() : RegVT(MVT::Other), ValueVT(MVT::Other) {}
110
111 RegsForValue(unsigned Reg, MVT::ValueType regvt, MVT::ValueType valuevt)
112 : RegVT(regvt), ValueVT(valuevt) {
113 Regs.push_back(Reg);
114 }
115 RegsForValue(const std::vector<unsigned> &regs,
116 MVT::ValueType regvt, MVT::ValueType valuevt)
117 : Regs(regs), RegVT(regvt), ValueVT(valuevt) {
118 }
119
120 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
121 /// this value and returns the result as a ValueVT value. This uses
122 /// Chain/Flag as the input and updates them for the output Chain/Flag.
123 SDOperand getCopyFromRegs(SelectionDAG &DAG,
Chris Lattner9f6637d2006-02-23 20:06:57 +0000124 SDOperand &Chain, SDOperand &Flag) const;
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +0000125
126 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
127 /// specified value into the registers specified by this object. This uses
128 /// Chain/Flag as the input and updates them for the output Chain/Flag.
129 void getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
Evan Chenga8441262006-06-15 08:11:54 +0000130 SDOperand &Chain, SDOperand &Flag,
131 MVT::ValueType PtrVT) const;
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +0000132
133 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
134 /// operand list. This adds the code marker and includes the number of
135 /// values added into it.
136 void AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
Chris Lattner9f6637d2006-02-23 20:06:57 +0000137 std::vector<SDOperand> &Ops) const;
Chris Lattner864635a2006-02-22 22:37:12 +0000138 };
139}
Evan Cheng4ef10862006-01-23 07:01:07 +0000140
Chris Lattner1c08c712005-01-07 07:47:53 +0000141namespace llvm {
142 //===--------------------------------------------------------------------===//
Jim Laskey9373beb2006-08-01 19:14:14 +0000143 /// createDefaultScheduler - This creates an instruction scheduler appropriate
144 /// for the target.
145 ScheduleDAG* createDefaultScheduler(SelectionDAGISel *IS,
146 SelectionDAG *DAG,
147 MachineBasicBlock *BB) {
148 TargetLowering &TLI = IS->getTargetLowering();
149
150 if (TLI.getSchedulingPreference() == TargetLowering::SchedulingForLatency) {
151 return createTDListDAGScheduler(IS, DAG, BB);
152 } else {
153 assert(TLI.getSchedulingPreference() ==
154 TargetLowering::SchedulingForRegPressure && "Unknown sched type!");
155 return createBURRListDAGScheduler(IS, DAG, BB);
156 }
157 }
158
159
160 //===--------------------------------------------------------------------===//
Chris Lattner1c08c712005-01-07 07:47:53 +0000161 /// FunctionLoweringInfo - This contains information that is global to a
162 /// function that is used when lowering a region of the function.
Chris Lattnerf26bc8e2005-01-08 19:52:31 +0000163 class FunctionLoweringInfo {
164 public:
Chris Lattner1c08c712005-01-07 07:47:53 +0000165 TargetLowering &TLI;
166 Function &Fn;
167 MachineFunction &MF;
168 SSARegMap *RegMap;
169
170 FunctionLoweringInfo(TargetLowering &TLI, Function &Fn,MachineFunction &MF);
171
172 /// MBBMap - A mapping from LLVM basic blocks to their machine code entry.
173 std::map<const BasicBlock*, MachineBasicBlock *> MBBMap;
174
175 /// ValueMap - Since we emit code for the function a basic block at a time,
176 /// we must remember which virtual registers hold the values for
177 /// cross-basic-block values.
Chris Lattner9f24ad72007-02-04 01:35:11 +0000178 DenseMap<const Value*, unsigned> ValueMap;
Chris Lattner1c08c712005-01-07 07:47:53 +0000179
180 /// StaticAllocaMap - Keep track of frame indices for fixed sized allocas in
181 /// the entry block. This allows the allocas to be efficiently referenced
182 /// anywhere in the function.
183 std::map<const AllocaInst*, int> StaticAllocaMap;
184
185 unsigned MakeReg(MVT::ValueType VT) {
186 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
187 }
Chris Lattner571e4342006-10-27 21:36:01 +0000188
189 /// isExportedInst - Return true if the specified value is an instruction
190 /// exported from its block.
191 bool isExportedInst(const Value *V) {
192 return ValueMap.count(V);
193 }
Misha Brukmanedf128a2005-04-21 22:36:52 +0000194
Chris Lattner3c384492006-03-16 19:51:18 +0000195 unsigned CreateRegForValue(const Value *V);
196
Chris Lattner1c08c712005-01-07 07:47:53 +0000197 unsigned InitializeRegForValue(const Value *V) {
198 unsigned &R = ValueMap[V];
199 assert(R == 0 && "Already initialized this value register!");
200 return R = CreateRegForValue(V);
201 }
202 };
203}
204
205/// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by
Nate Begemanf15485a2006-03-27 01:32:24 +0000206/// PHI nodes or outside of the basic block that defines it, or used by a
207/// switch instruction, which may expand to multiple basic blocks.
Chris Lattner1c08c712005-01-07 07:47:53 +0000208static bool isUsedOutsideOfDefiningBlock(Instruction *I) {
209 if (isa<PHINode>(I)) return true;
210 BasicBlock *BB = I->getParent();
211 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; ++UI)
Nate Begemanf15485a2006-03-27 01:32:24 +0000212 if (cast<Instruction>(*UI)->getParent() != BB || isa<PHINode>(*UI) ||
Chris Lattner571e4342006-10-27 21:36:01 +0000213 // FIXME: Remove switchinst special case.
Nate Begemanf15485a2006-03-27 01:32:24 +0000214 isa<SwitchInst>(*UI))
Chris Lattner1c08c712005-01-07 07:47:53 +0000215 return true;
216 return false;
217}
218
Chris Lattnerbf209482005-10-30 19:42:35 +0000219/// isOnlyUsedInEntryBlock - If the specified argument is only used in the
Nate Begemanf15485a2006-03-27 01:32:24 +0000220/// entry block, return true. This includes arguments used by switches, since
221/// the switch may expand into multiple basic blocks.
Chris Lattnerbf209482005-10-30 19:42:35 +0000222static bool isOnlyUsedInEntryBlock(Argument *A) {
223 BasicBlock *Entry = A->getParent()->begin();
224 for (Value::use_iterator UI = A->use_begin(), E = A->use_end(); UI != E; ++UI)
Nate Begemanf15485a2006-03-27 01:32:24 +0000225 if (cast<Instruction>(*UI)->getParent() != Entry || isa<SwitchInst>(*UI))
Chris Lattnerbf209482005-10-30 19:42:35 +0000226 return false; // Use not in entry block.
227 return true;
228}
229
Chris Lattner1c08c712005-01-07 07:47:53 +0000230FunctionLoweringInfo::FunctionLoweringInfo(TargetLowering &tli,
Misha Brukmanedf128a2005-04-21 22:36:52 +0000231 Function &fn, MachineFunction &mf)
Chris Lattner1c08c712005-01-07 07:47:53 +0000232 : TLI(tli), Fn(fn), MF(mf), RegMap(MF.getSSARegMap()) {
233
Chris Lattnerbf209482005-10-30 19:42:35 +0000234 // Create a vreg for each argument register that is not dead and is used
235 // outside of the entry block for the function.
236 for (Function::arg_iterator AI = Fn.arg_begin(), E = Fn.arg_end();
237 AI != E; ++AI)
238 if (!isOnlyUsedInEntryBlock(AI))
239 InitializeRegForValue(AI);
240
Chris Lattner1c08c712005-01-07 07:47:53 +0000241 // Initialize the mapping of values to registers. This is only set up for
242 // instruction values that are used outside of the block that defines
243 // them.
Jeff Cohen2aeaf4e2005-10-01 03:57:14 +0000244 Function::iterator BB = Fn.begin(), EB = Fn.end();
Chris Lattner1c08c712005-01-07 07:47:53 +0000245 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
246 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
Reid Spencerb83eb642006-10-20 07:07:24 +0000247 if (ConstantInt *CUI = dyn_cast<ConstantInt>(AI->getArraySize())) {
Chris Lattner1c08c712005-01-07 07:47:53 +0000248 const Type *Ty = AI->getAllocatedType();
Owen Andersona69571c2006-05-03 01:29:57 +0000249 uint64_t TySize = TLI.getTargetData()->getTypeSize(Ty);
Nate Begemanae232e72005-11-06 09:00:38 +0000250 unsigned Align =
Chris Lattnerd2b7cec2007-02-14 05:52:17 +0000251 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
Nate Begemanae232e72005-11-06 09:00:38 +0000252 AI->getAlignment());
Chris Lattnera8217e32005-05-13 23:14:17 +0000253
Reid Spencerb83eb642006-10-20 07:07:24 +0000254 TySize *= CUI->getZExtValue(); // Get total allocated size.
Chris Lattnerd222f6a2005-10-18 22:14:06 +0000255 if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
Chris Lattner1c08c712005-01-07 07:47:53 +0000256 StaticAllocaMap[AI] =
Chris Lattnerf26bc8e2005-01-08 19:52:31 +0000257 MF.getFrameInfo()->CreateStackObject((unsigned)TySize, Align);
Chris Lattner1c08c712005-01-07 07:47:53 +0000258 }
259
Jeff Cohen2aeaf4e2005-10-01 03:57:14 +0000260 for (; BB != EB; ++BB)
261 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
Chris Lattner1c08c712005-01-07 07:47:53 +0000262 if (!I->use_empty() && isUsedOutsideOfDefiningBlock(I))
263 if (!isa<AllocaInst>(I) ||
264 !StaticAllocaMap.count(cast<AllocaInst>(I)))
265 InitializeRegForValue(I);
266
267 // Create an initial MachineBasicBlock for each LLVM BasicBlock in F. This
268 // also creates the initial PHI MachineInstrs, though none of the input
269 // operands are populated.
Jeff Cohen2aeaf4e2005-10-01 03:57:14 +0000270 for (BB = Fn.begin(), EB = Fn.end(); BB != EB; ++BB) {
Chris Lattner1c08c712005-01-07 07:47:53 +0000271 MachineBasicBlock *MBB = new MachineBasicBlock(BB);
272 MBBMap[BB] = MBB;
273 MF.getBasicBlockList().push_back(MBB);
274
275 // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
276 // appropriate.
277 PHINode *PN;
Chris Lattner8c494ab2006-10-27 23:50:33 +0000278 for (BasicBlock::iterator I = BB->begin();(PN = dyn_cast<PHINode>(I)); ++I){
279 if (PN->use_empty()) continue;
280
281 MVT::ValueType VT = TLI.getValueType(PN->getType());
282 unsigned NumElements;
283 if (VT != MVT::Vector)
284 NumElements = TLI.getNumElements(VT);
285 else {
286 MVT::ValueType VT1,VT2;
287 NumElements =
Reid Spencer9d6565a2007-02-15 02:26:10 +0000288 TLI.getVectorTypeBreakdown(cast<VectorType>(PN->getType()),
Chris Lattner8c494ab2006-10-27 23:50:33 +0000289 VT1, VT2);
Chris Lattnerf44fd882005-01-07 21:34:19 +0000290 }
Chris Lattner8c494ab2006-10-27 23:50:33 +0000291 unsigned PHIReg = ValueMap[PN];
292 assert(PHIReg && "PHI node does not have an assigned virtual register!");
Evan Chengc0f64ff2006-11-27 23:37:22 +0000293 const TargetInstrInfo *TII = TLI.getTargetMachine().getInstrInfo();
Chris Lattner8c494ab2006-10-27 23:50:33 +0000294 for (unsigned i = 0; i != NumElements; ++i)
Evan Chengc0f64ff2006-11-27 23:37:22 +0000295 BuildMI(MBB, TII->get(TargetInstrInfo::PHI), PHIReg+i);
Chris Lattner8c494ab2006-10-27 23:50:33 +0000296 }
Chris Lattner1c08c712005-01-07 07:47:53 +0000297 }
298}
299
Chris Lattner3c384492006-03-16 19:51:18 +0000300/// CreateRegForValue - Allocate the appropriate number of virtual registers of
301/// the correctly promoted or expanded types. Assign these registers
302/// consecutive vreg numbers and return the first assigned number.
303unsigned FunctionLoweringInfo::CreateRegForValue(const Value *V) {
304 MVT::ValueType VT = TLI.getValueType(V->getType());
305
306 // The number of multiples of registers that we need, to, e.g., split up
307 // a <2 x int64> -> 4 x i32 registers.
308 unsigned NumVectorRegs = 1;
309
Reid Spencerac9dcb92007-02-15 03:39:18 +0000310 // If this is a vector type, figure out what type it will decompose into
Chris Lattner3c384492006-03-16 19:51:18 +0000311 // and how many of the elements it will use.
312 if (VT == MVT::Vector) {
Reid Spencer9d6565a2007-02-15 02:26:10 +0000313 const VectorType *PTy = cast<VectorType>(V->getType());
Chris Lattner3c384492006-03-16 19:51:18 +0000314 unsigned NumElts = PTy->getNumElements();
315 MVT::ValueType EltTy = TLI.getValueType(PTy->getElementType());
316
317 // Divide the input until we get to a supported size. This will always
318 // end with a scalar if the target doesn't support vectors.
319 while (NumElts > 1 && !TLI.isTypeLegal(getVectorType(EltTy, NumElts))) {
320 NumElts >>= 1;
321 NumVectorRegs <<= 1;
322 }
Chris Lattner6cb70042006-03-16 23:05:19 +0000323 if (NumElts == 1)
324 VT = EltTy;
325 else
326 VT = getVectorType(EltTy, NumElts);
Chris Lattner3c384492006-03-16 19:51:18 +0000327 }
328
329 // The common case is that we will only create one register for this
330 // value. If we have that case, create and return the virtual register.
331 unsigned NV = TLI.getNumElements(VT);
332 if (NV == 1) {
333 // If we are promoting this value, pick the next largest supported type.
334 MVT::ValueType PromotedType = TLI.getTypeToTransformTo(VT);
335 unsigned Reg = MakeReg(PromotedType);
336 // If this is a vector of supported or promoted types (e.g. 4 x i16),
337 // create all of the registers.
338 for (unsigned i = 1; i != NumVectorRegs; ++i)
339 MakeReg(PromotedType);
340 return Reg;
341 }
342
343 // If this value is represented with multiple target registers, make sure
344 // to create enough consecutive registers of the right (smaller) type.
Evan Cheng9f877882006-12-13 20:57:08 +0000345 VT = TLI.getTypeToExpandTo(VT);
346 unsigned R = MakeReg(VT);
Chris Lattner3c384492006-03-16 19:51:18 +0000347 for (unsigned i = 1; i != NV*NumVectorRegs; ++i)
Evan Cheng9f877882006-12-13 20:57:08 +0000348 MakeReg(VT);
Chris Lattner3c384492006-03-16 19:51:18 +0000349 return R;
350}
Chris Lattner1c08c712005-01-07 07:47:53 +0000351
352//===----------------------------------------------------------------------===//
353/// SelectionDAGLowering - This is the common target-independent lowering
354/// implementation that is parameterized by a TargetLowering object.
355/// Also, targets can overload any lowering method.
356///
357namespace llvm {
358class SelectionDAGLowering {
359 MachineBasicBlock *CurMBB;
360
Chris Lattner0da331f2007-02-04 01:31:47 +0000361 DenseMap<const Value*, SDOperand> NodeMap;
Chris Lattner1c08c712005-01-07 07:47:53 +0000362
Chris Lattnerd3948112005-01-17 22:19:26 +0000363 /// PendingLoads - Loads are not emitted to the program immediately. We bunch
364 /// them up and then emit token factor nodes when possible. This allows us to
365 /// get simple disambiguation between loads without worrying about alias
366 /// analysis.
367 std::vector<SDOperand> PendingLoads;
368
Nate Begemanf15485a2006-03-27 01:32:24 +0000369 /// Case - A pair of values to record the Value for a switch case, and the
370 /// case's target basic block.
371 typedef std::pair<Constant*, MachineBasicBlock*> Case;
372 typedef std::vector<Case>::iterator CaseItr;
373 typedef std::pair<CaseItr, CaseItr> CaseRange;
374
375 /// CaseRec - A struct with ctor used in lowering switches to a binary tree
376 /// of conditional branches.
377 struct CaseRec {
378 CaseRec(MachineBasicBlock *bb, Constant *lt, Constant *ge, CaseRange r) :
379 CaseBB(bb), LT(lt), GE(ge), Range(r) {}
380
381 /// CaseBB - The MBB in which to emit the compare and branch
382 MachineBasicBlock *CaseBB;
383 /// LT, GE - If nonzero, we know the current case value must be less-than or
384 /// greater-than-or-equal-to these Constants.
385 Constant *LT;
386 Constant *GE;
387 /// Range - A pair of iterators representing the range of case values to be
388 /// processed at this point in the binary search tree.
389 CaseRange Range;
390 };
391
392 /// The comparison function for sorting Case values.
393 struct CaseCmp {
394 bool operator () (const Case& C1, const Case& C2) {
Reid Spencer47857812006-12-31 05:55:36 +0000395 assert(isa<ConstantInt>(C1.first) && isa<ConstantInt>(C2.first));
Chris Lattnerae4f99d2007-02-13 20:09:07 +0000396 return cast<const ConstantInt>(C1.first)->getSExtValue() <
397 cast<const ConstantInt>(C2.first)->getSExtValue();
Nate Begemanf15485a2006-03-27 01:32:24 +0000398 }
399 };
400
Chris Lattner1c08c712005-01-07 07:47:53 +0000401public:
402 // TLI - This is information that describes the available target features we
403 // need for lowering. This indicates when operations are unavailable,
404 // implemented with a libcall, etc.
405 TargetLowering &TLI;
406 SelectionDAG &DAG;
Owen Andersona69571c2006-05-03 01:29:57 +0000407 const TargetData *TD;
Chris Lattner1c08c712005-01-07 07:47:53 +0000408
Nate Begemanf15485a2006-03-27 01:32:24 +0000409 /// SwitchCases - Vector of CaseBlock structures used to communicate
410 /// SwitchInst code generation information.
411 std::vector<SelectionDAGISel::CaseBlock> SwitchCases;
Nate Begeman37efe672006-04-22 18:53:45 +0000412 SelectionDAGISel::JumpTable JT;
Nate Begemanf15485a2006-03-27 01:32:24 +0000413
Chris Lattner1c08c712005-01-07 07:47:53 +0000414 /// FuncInfo - Information about the function as a whole.
415 ///
416 FunctionLoweringInfo &FuncInfo;
417
418 SelectionDAGLowering(SelectionDAG &dag, TargetLowering &tli,
Misha Brukmanedf128a2005-04-21 22:36:52 +0000419 FunctionLoweringInfo &funcinfo)
Chris Lattner1c08c712005-01-07 07:47:53 +0000420 : TLI(tli), DAG(dag), TD(DAG.getTarget().getTargetData()),
Nate Begeman9453eea2006-04-23 06:26:20 +0000421 JT(0,0,0,0), FuncInfo(funcinfo) {
Chris Lattner1c08c712005-01-07 07:47:53 +0000422 }
423
Chris Lattnera651cf62005-01-17 19:43:36 +0000424 /// getRoot - Return the current virtual root of the Selection DAG.
425 ///
426 SDOperand getRoot() {
Chris Lattnerd3948112005-01-17 22:19:26 +0000427 if (PendingLoads.empty())
428 return DAG.getRoot();
Misha Brukmanedf128a2005-04-21 22:36:52 +0000429
Chris Lattnerd3948112005-01-17 22:19:26 +0000430 if (PendingLoads.size() == 1) {
431 SDOperand Root = PendingLoads[0];
432 DAG.setRoot(Root);
433 PendingLoads.clear();
434 return Root;
435 }
436
437 // Otherwise, we have to make a token factor node.
Chris Lattnerbd564bf2006-08-08 02:23:42 +0000438 SDOperand Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
439 &PendingLoads[0], PendingLoads.size());
Chris Lattnerd3948112005-01-17 22:19:26 +0000440 PendingLoads.clear();
441 DAG.setRoot(Root);
442 return Root;
Chris Lattnera651cf62005-01-17 19:43:36 +0000443 }
444
Chris Lattner571e4342006-10-27 21:36:01 +0000445 SDOperand CopyValueToVirtualRegister(Value *V, unsigned Reg);
446
Chris Lattner1c08c712005-01-07 07:47:53 +0000447 void visit(Instruction &I) { visit(I.getOpcode(), I); }
448
449 void visit(unsigned Opcode, User &I) {
Chris Lattner1e7aa5c2006-11-10 04:41:34 +0000450 // Note: this doesn't use InstVisitor, because it has to work with
451 // ConstantExpr's in addition to instructions.
Chris Lattner1c08c712005-01-07 07:47:53 +0000452 switch (Opcode) {
453 default: assert(0 && "Unknown instruction type encountered!");
454 abort();
455 // Build the switch statement using the Instruction.def file.
456#define HANDLE_INST(NUM, OPCODE, CLASS) \
457 case Instruction::OPCODE:return visit##OPCODE((CLASS&)I);
458#include "llvm/Instruction.def"
459 }
460 }
461
462 void setCurrentBasicBlock(MachineBasicBlock *MBB) { CurMBB = MBB; }
463
Chris Lattner28b5b1c2006-03-15 22:19:46 +0000464 SDOperand getLoadFrom(const Type *Ty, SDOperand Ptr,
Evan Cheng466685d2006-10-09 20:57:25 +0000465 const Value *SV, SDOperand Root,
Chris Lattner28b5b1c2006-03-15 22:19:46 +0000466 bool isVolatile);
Chris Lattner1c08c712005-01-07 07:47:53 +0000467
468 SDOperand getIntPtrConstant(uint64_t Val) {
469 return DAG.getConstant(Val, TLI.getPointerTy());
470 }
471
Chris Lattner199862b2006-03-16 19:57:50 +0000472 SDOperand getValue(const Value *V);
Chris Lattner1c08c712005-01-07 07:47:53 +0000473
Chris Lattner0da331f2007-02-04 01:31:47 +0000474 void setValue(const Value *V, SDOperand NewN) {
Chris Lattner1c08c712005-01-07 07:47:53 +0000475 SDOperand &N = NodeMap[V];
476 assert(N.Val == 0 && "Already set a value for this node!");
Chris Lattner0da331f2007-02-04 01:31:47 +0000477 N = NewN;
Chris Lattner1c08c712005-01-07 07:47:53 +0000478 }
Chris Lattner4e4b5762006-02-01 18:59:47 +0000479
Chris Lattner864635a2006-02-22 22:37:12 +0000480 RegsForValue GetRegistersForValue(const std::string &ConstrCode,
481 MVT::ValueType VT,
482 bool OutReg, bool InReg,
483 std::set<unsigned> &OutputRegs,
484 std::set<unsigned> &InputRegs);
Nate Begemanf15485a2006-03-27 01:32:24 +0000485
Chris Lattner571e4342006-10-27 21:36:01 +0000486 void FindMergedConditions(Value *Cond, MachineBasicBlock *TBB,
487 MachineBasicBlock *FBB, MachineBasicBlock *CurBB,
488 unsigned Opc);
Chris Lattner8c494ab2006-10-27 23:50:33 +0000489 bool isExportableFromCurrentBlock(Value *V, const BasicBlock *FromBB);
Chris Lattner571e4342006-10-27 21:36:01 +0000490 void ExportFromCurrentBlock(Value *V);
Jim Laskey1da20a72007-02-23 21:45:01 +0000491 void LowerCallTo(Instruction &I,
492 const Type *CalledValueTy, unsigned CallingConv,
493 bool IsTailCall, SDOperand Callee, unsigned OpIdx);
Jim Laskey735b6f82007-02-22 15:38:06 +0000494
Chris Lattner1c08c712005-01-07 07:47:53 +0000495 // Terminator instructions.
496 void visitRet(ReturnInst &I);
497 void visitBr(BranchInst &I);
Nate Begemanf15485a2006-03-27 01:32:24 +0000498 void visitSwitch(SwitchInst &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000499 void visitUnreachable(UnreachableInst &I) { /* noop */ }
500
Nate Begemanf15485a2006-03-27 01:32:24 +0000501 // Helper for visitSwitch
502 void visitSwitchCase(SelectionDAGISel::CaseBlock &CB);
Nate Begeman37efe672006-04-22 18:53:45 +0000503 void visitJumpTable(SelectionDAGISel::JumpTable &JT);
Nate Begemanf15485a2006-03-27 01:32:24 +0000504
Chris Lattner1c08c712005-01-07 07:47:53 +0000505 // These all get lowered before this pass.
Jim Laskeyb180aa12007-02-21 22:53:45 +0000506 void visitInvoke(InvokeInst &I);
Jim Laskey183f47f2007-02-25 21:43:59 +0000507 void visitInvoke(InvokeInst &I, bool AsTerminator);
Jim Laskeyb180aa12007-02-21 22:53:45 +0000508 void visitUnwind(UnwindInst &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000509
Reid Spencer24d6da52007-01-21 00:29:26 +0000510 void visitScalarBinary(User &I, unsigned OpCode);
511 void visitVectorBinary(User &I, unsigned OpCode);
512 void visitEitherBinary(User &I, unsigned ScalarOp, unsigned VectorOp);
Nate Begemane21ea612005-11-18 07:42:56 +0000513 void visitShift(User &I, unsigned Opcode);
Nate Begeman5fbb5d22005-11-19 00:36:38 +0000514 void visitAdd(User &I) {
Reid Spencer9d6565a2007-02-15 02:26:10 +0000515 if (isa<VectorType>(I.getType()))
Reid Spencer24d6da52007-01-21 00:29:26 +0000516 visitVectorBinary(I, ISD::VADD);
517 else if (I.getType()->isFloatingPoint())
518 visitScalarBinary(I, ISD::FADD);
Reid Spencer1628cec2006-10-26 06:15:43 +0000519 else
Reid Spencer24d6da52007-01-21 00:29:26 +0000520 visitScalarBinary(I, ISD::ADD);
Chris Lattner01b3d732005-09-28 22:28:18 +0000521 }
Chris Lattnerb9fccc42005-04-02 05:04:50 +0000522 void visitSub(User &I);
Reid Spencer1628cec2006-10-26 06:15:43 +0000523 void visitMul(User &I) {
Reid Spencer9d6565a2007-02-15 02:26:10 +0000524 if (isa<VectorType>(I.getType()))
Reid Spencer24d6da52007-01-21 00:29:26 +0000525 visitVectorBinary(I, ISD::VMUL);
526 else if (I.getType()->isFloatingPoint())
527 visitScalarBinary(I, ISD::FMUL);
Reid Spencer1628cec2006-10-26 06:15:43 +0000528 else
Reid Spencer24d6da52007-01-21 00:29:26 +0000529 visitScalarBinary(I, ISD::MUL);
Chris Lattner01b3d732005-09-28 22:28:18 +0000530 }
Reid Spencer24d6da52007-01-21 00:29:26 +0000531 void visitURem(User &I) { visitScalarBinary(I, ISD::UREM); }
532 void visitSRem(User &I) { visitScalarBinary(I, ISD::SREM); }
533 void visitFRem(User &I) { visitScalarBinary(I, ISD::FREM); }
534 void visitUDiv(User &I) { visitEitherBinary(I, ISD::UDIV, ISD::VUDIV); }
535 void visitSDiv(User &I) { visitEitherBinary(I, ISD::SDIV, ISD::VSDIV); }
536 void visitFDiv(User &I) { visitEitherBinary(I, ISD::FDIV, ISD::VSDIV); }
537 void visitAnd (User &I) { visitEitherBinary(I, ISD::AND, ISD::VAND ); }
538 void visitOr (User &I) { visitEitherBinary(I, ISD::OR, ISD::VOR ); }
539 void visitXor (User &I) { visitEitherBinary(I, ISD::XOR, ISD::VXOR ); }
540 void visitShl (User &I) { visitShift(I, ISD::SHL); }
Reid Spencer3822ff52006-11-08 06:47:33 +0000541 void visitLShr(User &I) { visitShift(I, ISD::SRL); }
542 void visitAShr(User &I) { visitShift(I, ISD::SRA); }
Reid Spencer45fb3f32006-11-20 01:22:35 +0000543 void visitICmp(User &I);
544 void visitFCmp(User &I);
Reid Spencer3da59db2006-11-27 01:05:10 +0000545 // Visit the conversion instructions
546 void visitTrunc(User &I);
547 void visitZExt(User &I);
548 void visitSExt(User &I);
549 void visitFPTrunc(User &I);
550 void visitFPExt(User &I);
551 void visitFPToUI(User &I);
552 void visitFPToSI(User &I);
553 void visitUIToFP(User &I);
554 void visitSIToFP(User &I);
555 void visitPtrToInt(User &I);
556 void visitIntToPtr(User &I);
557 void visitBitCast(User &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000558
Chris Lattner2bbd8102006-03-29 00:11:43 +0000559 void visitExtractElement(User &I);
560 void visitInsertElement(User &I);
Chris Lattner3e104b12006-04-08 04:15:24 +0000561 void visitShuffleVector(User &I);
Chris Lattnerc7029802006-03-18 01:44:44 +0000562
Chris Lattner1c08c712005-01-07 07:47:53 +0000563 void visitGetElementPtr(User &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000564 void visitSelect(User &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000565
566 void visitMalloc(MallocInst &I);
567 void visitFree(FreeInst &I);
568 void visitAlloca(AllocaInst &I);
569 void visitLoad(LoadInst &I);
570 void visitStore(StoreInst &I);
571 void visitPHI(PHINode &I) { } // PHI nodes are handled specially.
572 void visitCall(CallInst &I);
Chris Lattnerce7518c2006-01-26 22:24:51 +0000573 void visitInlineAsm(CallInst &I);
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +0000574 const char *visitIntrinsicCall(CallInst &I, unsigned Intrinsic);
Chris Lattner0eade312006-03-24 02:22:33 +0000575 void visitTargetIntrinsic(CallInst &I, unsigned Intrinsic);
Chris Lattner1c08c712005-01-07 07:47:53 +0000576
Chris Lattner1c08c712005-01-07 07:47:53 +0000577 void visitVAStart(CallInst &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000578 void visitVAArg(VAArgInst &I);
579 void visitVAEnd(CallInst &I);
580 void visitVACopy(CallInst &I);
Chris Lattner1c08c712005-01-07 07:47:53 +0000581
Chris Lattner7041ee32005-01-11 05:56:49 +0000582 void visitMemIntrinsic(CallInst &I, unsigned Op);
Chris Lattner1c08c712005-01-07 07:47:53 +0000583
584 void visitUserOp1(Instruction &I) {
585 assert(0 && "UserOp1 should not exist at instruction selection time!");
586 abort();
587 }
588 void visitUserOp2(Instruction &I) {
589 assert(0 && "UserOp2 should not exist at instruction selection time!");
590 abort();
591 }
592};
593} // end namespace llvm
594
Chris Lattner199862b2006-03-16 19:57:50 +0000595SDOperand SelectionDAGLowering::getValue(const Value *V) {
596 SDOperand &N = NodeMap[V];
597 if (N.Val) return N;
598
599 const Type *VTy = V->getType();
600 MVT::ValueType VT = TLI.getValueType(VTy);
601 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V))) {
602 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
603 visit(CE->getOpcode(), *CE);
Chris Lattner0da331f2007-02-04 01:31:47 +0000604 SDOperand N1 = NodeMap[V];
605 assert(N1.Val && "visit didn't populate the ValueMap!");
606 return N1;
Chris Lattner199862b2006-03-16 19:57:50 +0000607 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(C)) {
608 return N = DAG.getGlobalAddress(GV, VT);
609 } else if (isa<ConstantPointerNull>(C)) {
610 return N = DAG.getConstant(0, TLI.getPointerTy());
611 } else if (isa<UndefValue>(C)) {
Reid Spencer9d6565a2007-02-15 02:26:10 +0000612 if (!isa<VectorType>(VTy))
Chris Lattner23d564c2006-03-19 00:20:20 +0000613 return N = DAG.getNode(ISD::UNDEF, VT);
614
Chris Lattnerb2827b02006-03-19 00:52:58 +0000615 // Create a VBUILD_VECTOR of undef nodes.
Reid Spencer9d6565a2007-02-15 02:26:10 +0000616 const VectorType *PTy = cast<VectorType>(VTy);
Chris Lattner23d564c2006-03-19 00:20:20 +0000617 unsigned NumElements = PTy->getNumElements();
618 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
619
Chris Lattnerbd564bf2006-08-08 02:23:42 +0000620 SmallVector<SDOperand, 8> Ops;
Chris Lattner23d564c2006-03-19 00:20:20 +0000621 Ops.assign(NumElements, DAG.getNode(ISD::UNDEF, PVT));
622
623 // Create a VConstant node with generic Vector type.
624 Ops.push_back(DAG.getConstant(NumElements, MVT::i32));
625 Ops.push_back(DAG.getValueType(PVT));
Chris Lattnerbd564bf2006-08-08 02:23:42 +0000626 return N = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector,
627 &Ops[0], Ops.size());
Chris Lattner199862b2006-03-16 19:57:50 +0000628 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
629 return N = DAG.getConstantFP(CFP->getValue(), VT);
Reid Spencer9d6565a2007-02-15 02:26:10 +0000630 } else if (const VectorType *PTy = dyn_cast<VectorType>(VTy)) {
Chris Lattner199862b2006-03-16 19:57:50 +0000631 unsigned NumElements = PTy->getNumElements();
632 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
Chris Lattner199862b2006-03-16 19:57:50 +0000633
634 // Now that we know the number and type of the elements, push a
635 // Constant or ConstantFP node onto the ops list for each element of
636 // the packed constant.
Chris Lattnerbd564bf2006-08-08 02:23:42 +0000637 SmallVector<SDOperand, 8> Ops;
Reid Spencer9d6565a2007-02-15 02:26:10 +0000638 if (ConstantVector *CP = dyn_cast<ConstantVector>(C)) {
Chris Lattner2bbd8102006-03-29 00:11:43 +0000639 for (unsigned i = 0; i != NumElements; ++i)
640 Ops.push_back(getValue(CP->getOperand(i)));
Chris Lattner199862b2006-03-16 19:57:50 +0000641 } else {
642 assert(isa<ConstantAggregateZero>(C) && "Unknown packed constant!");
643 SDOperand Op;
644 if (MVT::isFloatingPoint(PVT))
645 Op = DAG.getConstantFP(0, PVT);
646 else
647 Op = DAG.getConstant(0, PVT);
648 Ops.assign(NumElements, Op);
649 }
650
Chris Lattnerb2827b02006-03-19 00:52:58 +0000651 // Create a VBUILD_VECTOR node with generic Vector type.
Chris Lattner23d564c2006-03-19 00:20:20 +0000652 Ops.push_back(DAG.getConstant(NumElements, MVT::i32));
653 Ops.push_back(DAG.getValueType(PVT));
Chris Lattner0da331f2007-02-04 01:31:47 +0000654 return NodeMap[V] = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector, &Ops[0],
655 Ops.size());
Chris Lattner199862b2006-03-16 19:57:50 +0000656 } else {
657 // Canonicalize all constant ints to be unsigned.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000658 return N = DAG.getConstant(cast<ConstantInt>(C)->getZExtValue(),VT);
Chris Lattner199862b2006-03-16 19:57:50 +0000659 }
660 }
661
662 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
663 std::map<const AllocaInst*, int>::iterator SI =
664 FuncInfo.StaticAllocaMap.find(AI);
665 if (SI != FuncInfo.StaticAllocaMap.end())
666 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
667 }
668
Chris Lattner251db182007-02-25 18:40:32 +0000669 unsigned InReg = FuncInfo.ValueMap[V];
670 assert(InReg && "Value not in map!");
Chris Lattner199862b2006-03-16 19:57:50 +0000671
672 // If this type is not legal, make it so now.
Chris Lattner70c2a612006-03-31 02:06:56 +0000673 if (VT != MVT::Vector) {
Evan Cheng9f877882006-12-13 20:57:08 +0000674 if (TLI.getTypeAction(VT) == TargetLowering::Expand) {
Chris Lattner70c2a612006-03-31 02:06:56 +0000675 // Source must be expanded. This input value is actually coming from the
Chris Lattner251db182007-02-25 18:40:32 +0000676 // register pair InReg and InReg+1.
Evan Cheng9f877882006-12-13 20:57:08 +0000677 MVT::ValueType DestVT = TLI.getTypeToExpandTo(VT);
678 unsigned NumVals = TLI.getNumElements(VT);
679 N = DAG.getCopyFromReg(DAG.getEntryNode(), InReg, DestVT);
680 if (NumVals == 1)
681 N = DAG.getNode(ISD::BIT_CONVERT, VT, N);
682 else {
683 assert(NumVals == 2 && "1 to 4 (and more) expansion not implemented!");
684 N = DAG.getNode(ISD::BUILD_PAIR, VT, N,
685 DAG.getCopyFromReg(DAG.getEntryNode(), InReg+1, DestVT));
686 }
687 } else {
688 MVT::ValueType DestVT = TLI.getTypeToTransformTo(VT);
689 N = DAG.getCopyFromReg(DAG.getEntryNode(), InReg, DestVT);
690 if (TLI.getTypeAction(VT) == TargetLowering::Promote) // Promotion case
691 N = MVT::isFloatingPoint(VT)
692 ? DAG.getNode(ISD::FP_ROUND, VT, N)
693 : DAG.getNode(ISD::TRUNCATE, VT, N);
Chris Lattner199862b2006-03-16 19:57:50 +0000694 }
Chris Lattner70c2a612006-03-31 02:06:56 +0000695 } else {
696 // Otherwise, if this is a vector, make it available as a generic vector
697 // here.
698 MVT::ValueType PTyElementVT, PTyLegalElementVT;
Reid Spencer9d6565a2007-02-15 02:26:10 +0000699 const VectorType *PTy = cast<VectorType>(VTy);
700 unsigned NE = TLI.getVectorTypeBreakdown(PTy, PTyElementVT,
Chris Lattner70c2a612006-03-31 02:06:56 +0000701 PTyLegalElementVT);
702
703 // Build a VBUILD_VECTOR with the input registers.
Chris Lattnerbd564bf2006-08-08 02:23:42 +0000704 SmallVector<SDOperand, 8> Ops;
Chris Lattner70c2a612006-03-31 02:06:56 +0000705 if (PTyElementVT == PTyLegalElementVT) {
706 // If the value types are legal, just VBUILD the CopyFromReg nodes.
707 for (unsigned i = 0; i != NE; ++i)
708 Ops.push_back(DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
709 PTyElementVT));
710 } else if (PTyElementVT < PTyLegalElementVT) {
711 // If the register was promoted, use TRUNCATE of FP_ROUND as appropriate.
712 for (unsigned i = 0; i != NE; ++i) {
713 SDOperand Op = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
714 PTyElementVT);
715 if (MVT::isFloatingPoint(PTyElementVT))
716 Op = DAG.getNode(ISD::FP_ROUND, PTyElementVT, Op);
717 else
718 Op = DAG.getNode(ISD::TRUNCATE, PTyElementVT, Op);
719 Ops.push_back(Op);
720 }
721 } else {
722 // If the register was expanded, use BUILD_PAIR.
723 assert((NE & 1) == 0 && "Must expand into a multiple of 2 elements!");
724 for (unsigned i = 0; i != NE/2; ++i) {
725 SDOperand Op0 = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
726 PTyElementVT);
727 SDOperand Op1 = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
728 PTyElementVT);
729 Ops.push_back(DAG.getNode(ISD::BUILD_PAIR, VT, Op0, Op1));
730 }
731 }
732
733 Ops.push_back(DAG.getConstant(NE, MVT::i32));
734 Ops.push_back(DAG.getValueType(PTyLegalElementVT));
Chris Lattnerbd564bf2006-08-08 02:23:42 +0000735 N = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector, &Ops[0], Ops.size());
Chris Lattner2e2ef952006-04-05 06:54:42 +0000736
737 // Finally, use a VBIT_CONVERT to make this available as the appropriate
738 // vector type.
739 N = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, N,
740 DAG.getConstant(PTy->getNumElements(),
741 MVT::i32),
742 DAG.getValueType(TLI.getValueType(PTy->getElementType())));
Chris Lattner199862b2006-03-16 19:57:50 +0000743 }
744
745 return N;
746}
747
748
Chris Lattner1c08c712005-01-07 07:47:53 +0000749void SelectionDAGLowering::visitRet(ReturnInst &I) {
750 if (I.getNumOperands() == 0) {
Chris Lattnera651cf62005-01-17 19:43:36 +0000751 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getRoot()));
Chris Lattner1c08c712005-01-07 07:47:53 +0000752 return;
753 }
Chris Lattnerbd564bf2006-08-08 02:23:42 +0000754 SmallVector<SDOperand, 8> NewValues;
Nate Begemanee625572006-01-27 21:09:22 +0000755 NewValues.push_back(getRoot());
756 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
757 SDOperand RetOp = getValue(I.getOperand(i));
758
759 // If this is an integer return value, we need to promote it ourselves to
760 // the full width of a register, since LegalizeOp will use ANY_EXTEND rather
761 // than sign/zero.
Evan Cheng8e7d0562006-05-26 23:09:09 +0000762 // FIXME: C calling convention requires the return type to be promoted to
763 // at least 32-bit. But this is not necessary for non-C calling conventions.
Nate Begemanee625572006-01-27 21:09:22 +0000764 if (MVT::isInteger(RetOp.getValueType()) &&
765 RetOp.getValueType() < MVT::i64) {
766 MVT::ValueType TmpVT;
767 if (TLI.getTypeAction(MVT::i32) == TargetLowering::Promote)
768 TmpVT = TLI.getTypeToTransformTo(MVT::i32);
769 else
770 TmpVT = MVT::i32;
Reid Spencer47857812006-12-31 05:55:36 +0000771 const FunctionType *FTy = I.getParent()->getParent()->getFunctionType();
Reid Spencerbcca3402007-01-03 16:49:33 +0000772 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
Reid Spencer8c57dfb2007-01-03 04:25:33 +0000773 if (FTy->paramHasAttr(0, FunctionType::SExtAttribute))
774 ExtendKind = ISD::SIGN_EXTEND;
Reid Spencer47857812006-12-31 05:55:36 +0000775 if (FTy->paramHasAttr(0, FunctionType::ZExtAttribute))
776 ExtendKind = ISD::ZERO_EXTEND;
Reid Spencer376dd212007-01-03 05:03:05 +0000777 RetOp = DAG.getNode(ExtendKind, TmpVT, RetOp);
Nate Begemanee625572006-01-27 21:09:22 +0000778 }
779 NewValues.push_back(RetOp);
Reid Spencer47857812006-12-31 05:55:36 +0000780 NewValues.push_back(DAG.getConstant(false, MVT::i32));
Chris Lattner1c08c712005-01-07 07:47:53 +0000781 }
Chris Lattnerbd564bf2006-08-08 02:23:42 +0000782 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other,
783 &NewValues[0], NewValues.size()));
Chris Lattner1c08c712005-01-07 07:47:53 +0000784}
785
Chris Lattner571e4342006-10-27 21:36:01 +0000786/// ExportFromCurrentBlock - If this condition isn't known to be exported from
787/// the current basic block, add it to ValueMap now so that we'll get a
788/// CopyTo/FromReg.
789void SelectionDAGLowering::ExportFromCurrentBlock(Value *V) {
790 // No need to export constants.
791 if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
792
793 // Already exported?
794 if (FuncInfo.isExportedInst(V)) return;
795
796 unsigned Reg = FuncInfo.InitializeRegForValue(V);
797 PendingLoads.push_back(CopyValueToVirtualRegister(V, Reg));
798}
799
Chris Lattner8c494ab2006-10-27 23:50:33 +0000800bool SelectionDAGLowering::isExportableFromCurrentBlock(Value *V,
801 const BasicBlock *FromBB) {
802 // The operands of the setcc have to be in this block. We don't know
803 // how to export them from some other block.
804 if (Instruction *VI = dyn_cast<Instruction>(V)) {
805 // Can export from current BB.
806 if (VI->getParent() == FromBB)
807 return true;
808
809 // Is already exported, noop.
810 return FuncInfo.isExportedInst(V);
811 }
812
813 // If this is an argument, we can export it if the BB is the entry block or
814 // if it is already exported.
815 if (isa<Argument>(V)) {
816 if (FromBB == &FromBB->getParent()->getEntryBlock())
817 return true;
818
819 // Otherwise, can only export this if it is already exported.
820 return FuncInfo.isExportedInst(V);
821 }
822
823 // Otherwise, constants can always be exported.
824 return true;
825}
826
Chris Lattner6a586c82006-10-29 21:01:20 +0000827static bool InBlock(const Value *V, const BasicBlock *BB) {
828 if (const Instruction *I = dyn_cast<Instruction>(V))
829 return I->getParent() == BB;
830 return true;
831}
832
Chris Lattner571e4342006-10-27 21:36:01 +0000833/// FindMergedConditions - If Cond is an expression like
834void SelectionDAGLowering::FindMergedConditions(Value *Cond,
835 MachineBasicBlock *TBB,
836 MachineBasicBlock *FBB,
837 MachineBasicBlock *CurBB,
838 unsigned Opc) {
Chris Lattner571e4342006-10-27 21:36:01 +0000839 // If this node is not part of the or/and tree, emit it as a branch.
Reid Spencere4d87aa2006-12-23 06:05:41 +0000840 Instruction *BOp = dyn_cast<Instruction>(Cond);
Chris Lattner571e4342006-10-27 21:36:01 +0000841
Reid Spencere4d87aa2006-12-23 06:05:41 +0000842 if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
843 (unsigned)BOp->getOpcode() != Opc || !BOp->hasOneUse() ||
Chris Lattner6a586c82006-10-29 21:01:20 +0000844 BOp->getParent() != CurBB->getBasicBlock() ||
845 !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
846 !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
Chris Lattner571e4342006-10-27 21:36:01 +0000847 const BasicBlock *BB = CurBB->getBasicBlock();
848
Reid Spencere4d87aa2006-12-23 06:05:41 +0000849 // If the leaf of the tree is a comparison, merge the condition into
850 // the caseblock.
851 if ((isa<ICmpInst>(Cond) || isa<FCmpInst>(Cond)) &&
852 // The operands of the cmp have to be in this block. We don't know
Chris Lattner5a145f02006-10-29 18:23:37 +0000853 // how to export them from some other block. If this is the first block
854 // of the sequence, no exporting is needed.
855 (CurBB == CurMBB ||
856 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
857 isExportableFromCurrentBlock(BOp->getOperand(1), BB)))) {
Reid Spencere4d87aa2006-12-23 06:05:41 +0000858 BOp = cast<Instruction>(Cond);
859 ISD::CondCode Condition;
860 if (ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
861 switch (IC->getPredicate()) {
862 default: assert(0 && "Unknown icmp predicate opcode!");
863 case ICmpInst::ICMP_EQ: Condition = ISD::SETEQ; break;
864 case ICmpInst::ICMP_NE: Condition = ISD::SETNE; break;
865 case ICmpInst::ICMP_SLE: Condition = ISD::SETLE; break;
866 case ICmpInst::ICMP_ULE: Condition = ISD::SETULE; break;
867 case ICmpInst::ICMP_SGE: Condition = ISD::SETGE; break;
868 case ICmpInst::ICMP_UGE: Condition = ISD::SETUGE; break;
869 case ICmpInst::ICMP_SLT: Condition = ISD::SETLT; break;
870 case ICmpInst::ICMP_ULT: Condition = ISD::SETULT; break;
871 case ICmpInst::ICMP_SGT: Condition = ISD::SETGT; break;
872 case ICmpInst::ICMP_UGT: Condition = ISD::SETUGT; break;
873 }
874 } else if (FCmpInst *FC = dyn_cast<FCmpInst>(Cond)) {
875 ISD::CondCode FPC, FOC;
876 switch (FC->getPredicate()) {
877 default: assert(0 && "Unknown fcmp predicate opcode!");
878 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
879 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
880 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
881 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
882 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
883 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
884 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
885 case FCmpInst::FCMP_ORD: FOC = ISD::SETEQ; FPC = ISD::SETO; break;
886 case FCmpInst::FCMP_UNO: FOC = ISD::SETNE; FPC = ISD::SETUO; break;
887 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
888 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
889 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
890 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
891 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
892 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
893 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
894 }
895 if (FiniteOnlyFPMath())
896 Condition = FOC;
897 else
898 Condition = FPC;
899 } else {
Chris Lattner0da331f2007-02-04 01:31:47 +0000900 Condition = ISD::SETEQ; // silence warning.
Reid Spencere4d87aa2006-12-23 06:05:41 +0000901 assert(0 && "Unknown compare instruction");
Chris Lattner571e4342006-10-27 21:36:01 +0000902 }
903
Chris Lattner571e4342006-10-27 21:36:01 +0000904 SelectionDAGISel::CaseBlock CB(Condition, BOp->getOperand(0),
905 BOp->getOperand(1), TBB, FBB, CurBB);
906 SwitchCases.push_back(CB);
907 return;
908 }
909
910 // Create a CaseBlock record representing this branch.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000911 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, Cond, ConstantInt::getTrue(),
Chris Lattner571e4342006-10-27 21:36:01 +0000912 TBB, FBB, CurBB);
913 SwitchCases.push_back(CB);
Chris Lattner571e4342006-10-27 21:36:01 +0000914 return;
915 }
916
Chris Lattnerd2f9ee92006-10-27 21:54:23 +0000917
918 // Create TmpBB after CurBB.
Chris Lattner571e4342006-10-27 21:36:01 +0000919 MachineFunction::iterator BBI = CurBB;
920 MachineBasicBlock *TmpBB = new MachineBasicBlock(CurBB->getBasicBlock());
921 CurBB->getParent()->getBasicBlockList().insert(++BBI, TmpBB);
922
Chris Lattnerd2f9ee92006-10-27 21:54:23 +0000923 if (Opc == Instruction::Or) {
924 // Codegen X | Y as:
925 // jmp_if_X TBB
926 // jmp TmpBB
927 // TmpBB:
928 // jmp_if_Y TBB
929 // jmp FBB
930 //
Chris Lattner571e4342006-10-27 21:36:01 +0000931
Chris Lattnerd2f9ee92006-10-27 21:54:23 +0000932 // Emit the LHS condition.
933 FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, Opc);
934
935 // Emit the RHS condition into TmpBB.
936 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
937 } else {
938 assert(Opc == Instruction::And && "Unknown merge op!");
939 // Codegen X & Y as:
940 // jmp_if_X TmpBB
941 // jmp FBB
942 // TmpBB:
943 // jmp_if_Y TBB
944 // jmp FBB
945 //
946 // This requires creation of TmpBB after CurBB.
947
948 // Emit the LHS condition.
949 FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, Opc);
950
951 // Emit the RHS condition into TmpBB.
952 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
953 }
Chris Lattner571e4342006-10-27 21:36:01 +0000954}
955
Chris Lattnerdf19f272006-10-31 22:37:42 +0000956/// If the set of cases should be emitted as a series of branches, return true.
957/// If we should emit this as a bunch of and/or'd together conditions, return
958/// false.
959static bool
960ShouldEmitAsBranches(const std::vector<SelectionDAGISel::CaseBlock> &Cases) {
961 if (Cases.size() != 2) return true;
962
Chris Lattner0ccb5002006-10-31 23:06:00 +0000963 // If this is two comparisons of the same values or'd or and'd together, they
964 // will get folded into a single comparison, so don't emit two blocks.
965 if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
966 Cases[0].CmpRHS == Cases[1].CmpRHS) ||
967 (Cases[0].CmpRHS == Cases[1].CmpLHS &&
968 Cases[0].CmpLHS == Cases[1].CmpRHS)) {
969 return false;
970 }
971
Chris Lattnerdf19f272006-10-31 22:37:42 +0000972 return true;
973}
974
Chris Lattner1c08c712005-01-07 07:47:53 +0000975void SelectionDAGLowering::visitBr(BranchInst &I) {
976 // Update machine-CFG edges.
977 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
Chris Lattner1c08c712005-01-07 07:47:53 +0000978
979 // Figure out which block is immediately after the current one.
980 MachineBasicBlock *NextBlock = 0;
981 MachineFunction::iterator BBI = CurMBB;
982 if (++BBI != CurMBB->getParent()->end())
983 NextBlock = BBI;
984
985 if (I.isUnconditional()) {
986 // If this is not a fall-through branch, emit the branch.
987 if (Succ0MBB != NextBlock)
Chris Lattnera651cf62005-01-17 19:43:36 +0000988 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
Misha Brukmandedf2bd2005-04-22 04:01:18 +0000989 DAG.getBasicBlock(Succ0MBB)));
Chris Lattner1c08c712005-01-07 07:47:53 +0000990
Chris Lattner57ab6592006-10-24 17:57:59 +0000991 // Update machine-CFG edges.
992 CurMBB->addSuccessor(Succ0MBB);
993
994 return;
995 }
996
997 // If this condition is one of the special cases we handle, do special stuff
998 // now.
999 Value *CondVal = I.getCondition();
Chris Lattner57ab6592006-10-24 17:57:59 +00001000 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
Chris Lattner571e4342006-10-27 21:36:01 +00001001
1002 // If this is a series of conditions that are or'd or and'd together, emit
1003 // this as a sequence of branches instead of setcc's with and/or operations.
1004 // For example, instead of something like:
1005 // cmp A, B
1006 // C = seteq
1007 // cmp D, E
1008 // F = setle
1009 // or C, F
1010 // jnz foo
1011 // Emit:
1012 // cmp A, B
1013 // je foo
1014 // cmp D, E
1015 // jle foo
1016 //
1017 if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
1018 if (BOp->hasOneUse() &&
Chris Lattnerd2f9ee92006-10-27 21:54:23 +00001019 (BOp->getOpcode() == Instruction::And ||
Chris Lattner571e4342006-10-27 21:36:01 +00001020 BOp->getOpcode() == Instruction::Or)) {
1021 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, CurMBB, BOp->getOpcode());
Chris Lattner0ccb5002006-10-31 23:06:00 +00001022 // If the compares in later blocks need to use values not currently
1023 // exported from this block, export them now. This block should always
1024 // be the first entry.
1025 assert(SwitchCases[0].ThisBB == CurMBB && "Unexpected lowering!");
1026
Chris Lattnerdf19f272006-10-31 22:37:42 +00001027 // Allow some cases to be rejected.
1028 if (ShouldEmitAsBranches(SwitchCases)) {
Chris Lattnerdf19f272006-10-31 22:37:42 +00001029 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
1030 ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
1031 ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
1032 }
1033
1034 // Emit the branch for this block.
1035 visitSwitchCase(SwitchCases[0]);
1036 SwitchCases.erase(SwitchCases.begin());
1037 return;
Chris Lattner5a145f02006-10-29 18:23:37 +00001038 }
1039
Chris Lattner0ccb5002006-10-31 23:06:00 +00001040 // Okay, we decided not to do this, remove any inserted MBB's and clear
1041 // SwitchCases.
1042 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
1043 CurMBB->getParent()->getBasicBlockList().erase(SwitchCases[i].ThisBB);
1044
Chris Lattnerdf19f272006-10-31 22:37:42 +00001045 SwitchCases.clear();
Chris Lattner571e4342006-10-27 21:36:01 +00001046 }
1047 }
Chris Lattner24525952006-10-24 18:07:37 +00001048
1049 // Create a CaseBlock record representing this branch.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001050 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(),
Chris Lattner24525952006-10-24 18:07:37 +00001051 Succ0MBB, Succ1MBB, CurMBB);
1052 // Use visitSwitchCase to actually insert the fast branch sequence for this
1053 // cond branch.
1054 visitSwitchCase(CB);
Chris Lattner1c08c712005-01-07 07:47:53 +00001055}
1056
Nate Begemanf15485a2006-03-27 01:32:24 +00001057/// visitSwitchCase - Emits the necessary code to represent a single node in
1058/// the binary search tree resulting from lowering a switch instruction.
1059void SelectionDAGLowering::visitSwitchCase(SelectionDAGISel::CaseBlock &CB) {
Chris Lattner57ab6592006-10-24 17:57:59 +00001060 SDOperand Cond;
1061 SDOperand CondLHS = getValue(CB.CmpLHS);
1062
Chris Lattner571e4342006-10-27 21:36:01 +00001063 // Build the setcc now, fold "(X == true)" to X and "(X == false)" to !X to
1064 // handle common cases produced by branch lowering.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001065 if (CB.CmpRHS == ConstantInt::getTrue() && CB.CC == ISD::SETEQ)
Chris Lattner57ab6592006-10-24 17:57:59 +00001066 Cond = CondLHS;
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001067 else if (CB.CmpRHS == ConstantInt::getFalse() && CB.CC == ISD::SETEQ) {
Chris Lattner571e4342006-10-27 21:36:01 +00001068 SDOperand True = DAG.getConstant(1, CondLHS.getValueType());
1069 Cond = DAG.getNode(ISD::XOR, CondLHS.getValueType(), CondLHS, True);
1070 } else
1071 Cond = DAG.getSetCC(MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
Nate Begemanf15485a2006-03-27 01:32:24 +00001072
1073 // Set NextBlock to be the MBB immediately after the current one, if any.
1074 // This is used to avoid emitting unnecessary branches to the next block.
1075 MachineBasicBlock *NextBlock = 0;
1076 MachineFunction::iterator BBI = CurMBB;
1077 if (++BBI != CurMBB->getParent()->end())
1078 NextBlock = BBI;
1079
1080 // If the lhs block is the next block, invert the condition so that we can
1081 // fall through to the lhs instead of the rhs block.
Chris Lattner57ab6592006-10-24 17:57:59 +00001082 if (CB.TrueBB == NextBlock) {
1083 std::swap(CB.TrueBB, CB.FalseBB);
Nate Begemanf15485a2006-03-27 01:32:24 +00001084 SDOperand True = DAG.getConstant(1, Cond.getValueType());
1085 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
1086 }
1087 SDOperand BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(), Cond,
Chris Lattner57ab6592006-10-24 17:57:59 +00001088 DAG.getBasicBlock(CB.TrueBB));
1089 if (CB.FalseBB == NextBlock)
Nate Begemanf15485a2006-03-27 01:32:24 +00001090 DAG.setRoot(BrCond);
1091 else
1092 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond,
Chris Lattner57ab6592006-10-24 17:57:59 +00001093 DAG.getBasicBlock(CB.FalseBB)));
Nate Begemanf15485a2006-03-27 01:32:24 +00001094 // Update successor info
Chris Lattner57ab6592006-10-24 17:57:59 +00001095 CurMBB->addSuccessor(CB.TrueBB);
1096 CurMBB->addSuccessor(CB.FalseBB);
Nate Begemanf15485a2006-03-27 01:32:24 +00001097}
1098
Nate Begeman37efe672006-04-22 18:53:45 +00001099void SelectionDAGLowering::visitJumpTable(SelectionDAGISel::JumpTable &JT) {
Nate Begeman37efe672006-04-22 18:53:45 +00001100 // Emit the code for the jump table
1101 MVT::ValueType PTy = TLI.getPointerTy();
Evan Cheng3d4ce112006-10-30 08:00:44 +00001102 SDOperand Index = DAG.getCopyFromReg(getRoot(), JT.Reg, PTy);
1103 SDOperand Table = DAG.getJumpTable(JT.JTI, PTy);
1104 DAG.setRoot(DAG.getNode(ISD::BR_JT, MVT::Other, Index.getValue(1),
1105 Table, Index));
1106 return;
Nate Begeman37efe672006-04-22 18:53:45 +00001107}
1108
Jim Laskeyb180aa12007-02-21 22:53:45 +00001109void SelectionDAGLowering::visitInvoke(InvokeInst &I) {
Jim Laskey183f47f2007-02-25 21:43:59 +00001110 assert(0 && "Should never be visited directly");
1111}
1112void SelectionDAGLowering::visitInvoke(InvokeInst &I, bool AsTerminator) {
Jim Laskeyb180aa12007-02-21 22:53:45 +00001113 // Retrieve successors.
1114 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
1115 MachineBasicBlock *LandingPad = FuncInfo.MBBMap[I.getSuccessor(1)];
1116
Jim Laskey183f47f2007-02-25 21:43:59 +00001117 if (!AsTerminator) {
1118 // Mark landing pad so that it doesn't get deleted in branch folding.
1119 LandingPad->setIsLandingPad();
1120
1121 // Insert a label before the invoke call to mark the try range.
1122 // This can be used to detect deletion of the invoke via the
1123 // MachineModuleInfo.
1124 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
1125 unsigned BeginLabel = MMI->NextLabelID();
1126 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, getRoot(),
1127 DAG.getConstant(BeginLabel, MVT::i32)));
Jim Laskeyb180aa12007-02-21 22:53:45 +00001128
Jim Laskey183f47f2007-02-25 21:43:59 +00001129 LowerCallTo(I, I.getCalledValue()->getType(),
1130 I.getCallingConv(),
1131 false,
1132 getValue(I.getOperand(0)),
1133 3);
Jim Laskeyb180aa12007-02-21 22:53:45 +00001134
Jim Laskey183f47f2007-02-25 21:43:59 +00001135 // Insert a label before the invoke call to mark the try range.
1136 // This can be used to detect deletion of the invoke via the
1137 // MachineModuleInfo.
1138 unsigned EndLabel = MMI->NextLabelID();
1139 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, getRoot(),
1140 DAG.getConstant(EndLabel, MVT::i32)));
1141
1142 // Inform MachineModuleInfo of range.
1143 MMI->addInvoke(LandingPad, BeginLabel, EndLabel);
1144
1145 // Update successor info
1146 CurMBB->addSuccessor(Return);
1147 CurMBB->addSuccessor(LandingPad);
1148 } else {
1149 // Drop into normal successor.
1150 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
1151 DAG.getBasicBlock(Return)));
1152 }
Jim Laskeyb180aa12007-02-21 22:53:45 +00001153}
1154
1155void SelectionDAGLowering::visitUnwind(UnwindInst &I) {
1156}
1157
Nate Begemanf15485a2006-03-27 01:32:24 +00001158void SelectionDAGLowering::visitSwitch(SwitchInst &I) {
1159 // Figure out which block is immediately after the current one.
1160 MachineBasicBlock *NextBlock = 0;
1161 MachineFunction::iterator BBI = CurMBB;
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001162
Nate Begemanf15485a2006-03-27 01:32:24 +00001163 if (++BBI != CurMBB->getParent()->end())
1164 NextBlock = BBI;
1165
Chris Lattnerd2c1d222006-10-22 21:36:53 +00001166 MachineBasicBlock *Default = FuncInfo.MBBMap[I.getDefaultDest()];
1167
Nate Begemanf15485a2006-03-27 01:32:24 +00001168 // If there is only the default destination, branch to it if it is not the
1169 // next basic block. Otherwise, just fall through.
1170 if (I.getNumOperands() == 2) {
1171 // Update machine-CFG edges.
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001172
Nate Begemanf15485a2006-03-27 01:32:24 +00001173 // If this is not a fall-through branch, emit the branch.
Chris Lattnerd2c1d222006-10-22 21:36:53 +00001174 if (Default != NextBlock)
Nate Begemanf15485a2006-03-27 01:32:24 +00001175 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
Chris Lattnerd2c1d222006-10-22 21:36:53 +00001176 DAG.getBasicBlock(Default)));
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001177
Chris Lattnerd2c1d222006-10-22 21:36:53 +00001178 CurMBB->addSuccessor(Default);
Nate Begemanf15485a2006-03-27 01:32:24 +00001179 return;
1180 }
1181
1182 // If there are any non-default case statements, create a vector of Cases
1183 // representing each one, and sort the vector so that we can efficiently
1184 // create a binary search tree from them.
1185 std::vector<Case> Cases;
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001186
Nate Begemanf15485a2006-03-27 01:32:24 +00001187 for (unsigned i = 1; i < I.getNumSuccessors(); ++i) {
1188 MachineBasicBlock *SMBB = FuncInfo.MBBMap[I.getSuccessor(i)];
1189 Cases.push_back(Case(I.getSuccessorValue(i), SMBB));
1190 }
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001191
Nate Begemanf15485a2006-03-27 01:32:24 +00001192 std::sort(Cases.begin(), Cases.end(), CaseCmp());
1193
1194 // Get the Value to be switched on and default basic blocks, which will be
1195 // inserted into CaseBlock records, representing basic blocks in the binary
1196 // search tree.
1197 Value *SV = I.getOperand(0);
Nate Begeman37efe672006-04-22 18:53:45 +00001198
1199 // Get the MachineFunction which holds the current MBB. This is used during
1200 // emission of jump tables, and when inserting any additional MBBs necessary
1201 // to represent the switch.
Nate Begemanf15485a2006-03-27 01:32:24 +00001202 MachineFunction *CurMF = CurMBB->getParent();
1203 const BasicBlock *LLVMBB = CurMBB->getBasicBlock();
Chris Lattnerd2c1d222006-10-22 21:36:53 +00001204
1205 // If the switch has few cases (two or less) emit a series of specific
1206 // tests.
Chris Lattnerb2e806e2006-10-22 23:00:53 +00001207 if (Cases.size() < 3) {
Chris Lattnerd2c1d222006-10-22 21:36:53 +00001208 // TODO: If any two of the cases has the same destination, and if one value
1209 // is the same as the other, but has one bit unset that the other has set,
1210 // use bit manipulation to do two compares at once. For example:
1211 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
1212
Chris Lattnerb3543432006-10-23 18:38:22 +00001213 // Rearrange the case blocks so that the last one falls through if possible.
1214 if (NextBlock && Default != NextBlock && Cases.back().second != NextBlock) {
1215 // The last case block won't fall through into 'NextBlock' if we emit the
1216 // branches in this order. See if rearranging a case value would help.
1217 for (unsigned i = 0, e = Cases.size()-1; i != e; ++i) {
1218 if (Cases[i].second == NextBlock) {
1219 std::swap(Cases[i], Cases.back());
1220 break;
1221 }
1222 }
1223 }
1224
Chris Lattnerd2c1d222006-10-22 21:36:53 +00001225 // Create a CaseBlock record representing a conditional branch to
1226 // the Case's target mbb if the value being switched on SV is equal
1227 // to C.
1228 MachineBasicBlock *CurBlock = CurMBB;
1229 for (unsigned i = 0, e = Cases.size(); i != e; ++i) {
1230 MachineBasicBlock *FallThrough;
1231 if (i != e-1) {
1232 FallThrough = new MachineBasicBlock(CurMBB->getBasicBlock());
1233 CurMF->getBasicBlockList().insert(BBI, FallThrough);
1234 } else {
1235 // If the last case doesn't match, go to the default block.
1236 FallThrough = Default;
1237 }
1238
1239 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, SV, Cases[i].first,
1240 Cases[i].second, FallThrough, CurBlock);
1241
1242 // If emitting the first comparison, just call visitSwitchCase to emit the
1243 // code into the current block. Otherwise, push the CaseBlock onto the
1244 // vector to be later processed by SDISel, and insert the node's MBB
1245 // before the next MBB.
1246 if (CurBlock == CurMBB)
1247 visitSwitchCase(CB);
1248 else
1249 SwitchCases.push_back(CB);
1250
1251 CurBlock = FallThrough;
1252 }
1253 return;
1254 }
Nate Begeman37efe672006-04-22 18:53:45 +00001255
Nate Begeman17c275f2006-05-08 16:51:36 +00001256 // If the switch has more than 5 blocks, and at least 31.25% dense, and the
1257 // target supports indirect branches, then emit a jump table rather than
1258 // lowering the switch to a binary tree of conditional branches.
Evan Cheng3d4ce112006-10-30 08:00:44 +00001259 if ((TLI.isOperationLegal(ISD::BR_JT, MVT::Other) ||
1260 TLI.isOperationLegal(ISD::BRIND, MVT::Other)) &&
Nate Begemanf4360a42006-05-03 03:48:02 +00001261 Cases.size() > 5) {
Chris Lattner21840b12007-02-14 07:18:16 +00001262 uint64_t First =cast<ConstantInt>(Cases.front().first)->getSExtValue();
1263 uint64_t Last = cast<ConstantInt>(Cases.back().first)->getSExtValue();
Nate Begemanf4360a42006-05-03 03:48:02 +00001264 double Density = (double)Cases.size() / (double)((Last - First) + 1ULL);
1265
Nate Begeman17c275f2006-05-08 16:51:36 +00001266 if (Density >= 0.3125) {
Nate Begeman37efe672006-04-22 18:53:45 +00001267 // Create a new basic block to hold the code for loading the address
1268 // of the jump table, and jumping to it. Update successor information;
1269 // we will either branch to the default case for the switch, or the jump
1270 // table.
1271 MachineBasicBlock *JumpTableBB = new MachineBasicBlock(LLVMBB);
1272 CurMF->getBasicBlockList().insert(BBI, JumpTableBB);
1273 CurMBB->addSuccessor(Default);
1274 CurMBB->addSuccessor(JumpTableBB);
1275
1276 // Subtract the lowest switch case value from the value being switched on
1277 // and conditional branch to default mbb if the result is greater than the
1278 // difference between smallest and largest cases.
1279 SDOperand SwitchOp = getValue(SV);
1280 MVT::ValueType VT = SwitchOp.getValueType();
1281 SDOperand SUB = DAG.getNode(ISD::SUB, VT, SwitchOp,
1282 DAG.getConstant(First, VT));
1283
1284 // The SDNode we just created, which holds the value being switched on
1285 // minus the the smallest case value, needs to be copied to a virtual
1286 // register so it can be used as an index into the jump table in a
1287 // subsequent basic block. This value may be smaller or larger than the
1288 // target's pointer type, and therefore require extension or truncating.
1289 if (VT > TLI.getPointerTy())
1290 SwitchOp = DAG.getNode(ISD::TRUNCATE, TLI.getPointerTy(), SUB);
1291 else
1292 SwitchOp = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(), SUB);
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001293
Nate Begeman37efe672006-04-22 18:53:45 +00001294 unsigned JumpTableReg = FuncInfo.MakeReg(TLI.getPointerTy());
1295 SDOperand CopyTo = DAG.getCopyToReg(getRoot(), JumpTableReg, SwitchOp);
1296
1297 // Emit the range check for the jump table, and branch to the default
1298 // block for the switch statement if the value being switched on exceeds
1299 // the largest case in the switch.
1300 SDOperand CMP = DAG.getSetCC(TLI.getSetCCResultTy(), SUB,
1301 DAG.getConstant(Last-First,VT), ISD::SETUGT);
1302 DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, CopyTo, CMP,
1303 DAG.getBasicBlock(Default)));
1304
Nate Begemanf4360a42006-05-03 03:48:02 +00001305 // Build a vector of destination BBs, corresponding to each target
1306 // of the jump table. If the value of the jump table slot corresponds to
1307 // a case statement, push the case's BB onto the vector, otherwise, push
1308 // the default BB.
Nate Begeman37efe672006-04-22 18:53:45 +00001309 std::vector<MachineBasicBlock*> DestBBs;
Chris Lattnerc661d612007-02-14 07:34:56 +00001310 int64_t TEI = First;
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001311 for (CaseItr ii = Cases.begin(), ee = Cases.end(); ii != ee; ++TEI)
Chris Lattner21840b12007-02-14 07:18:16 +00001312 if (cast<ConstantInt>(ii->first)->getSExtValue() == TEI) {
Nate Begemanf4360a42006-05-03 03:48:02 +00001313 DestBBs.push_back(ii->second);
Nate Begemanf4360a42006-05-03 03:48:02 +00001314 ++ii;
1315 } else {
1316 DestBBs.push_back(Default);
Nate Begemanf4360a42006-05-03 03:48:02 +00001317 }
Nate Begemanf4360a42006-05-03 03:48:02 +00001318
Chris Lattner8c494ab2006-10-27 23:50:33 +00001319 // Update successor info. Add one edge to each unique successor.
1320 // Vector bool would be better, but vector<bool> is really slow.
1321 std::vector<unsigned char> SuccsHandled;
1322 SuccsHandled.resize(CurMBB->getParent()->getNumBlockIDs());
1323
Chris Lattnerc66764c2006-09-10 06:36:57 +00001324 for (std::vector<MachineBasicBlock*>::iterator I = DestBBs.begin(),
Chris Lattner8c494ab2006-10-27 23:50:33 +00001325 E = DestBBs.end(); I != E; ++I) {
1326 if (!SuccsHandled[(*I)->getNumber()]) {
1327 SuccsHandled[(*I)->getNumber()] = true;
1328 JumpTableBB->addSuccessor(*I);
1329 }
1330 }
Nate Begemanf4360a42006-05-03 03:48:02 +00001331
1332 // Create a jump table index for this jump table, or return an existing
1333 // one.
Nate Begeman37efe672006-04-22 18:53:45 +00001334 unsigned JTI = CurMF->getJumpTableInfo()->getJumpTableIndex(DestBBs);
1335
1336 // Set the jump table information so that we can codegen it as a second
1337 // MachineBasicBlock
1338 JT.Reg = JumpTableReg;
1339 JT.JTI = JTI;
1340 JT.MBB = JumpTableBB;
Nate Begeman9453eea2006-04-23 06:26:20 +00001341 JT.Default = Default;
Nate Begeman37efe672006-04-22 18:53:45 +00001342 return;
1343 }
1344 }
Nate Begemanf15485a2006-03-27 01:32:24 +00001345
1346 // Push the initial CaseRec onto the worklist
1347 std::vector<CaseRec> CaseVec;
1348 CaseVec.push_back(CaseRec(CurMBB,0,0,CaseRange(Cases.begin(),Cases.end())));
1349
1350 while (!CaseVec.empty()) {
1351 // Grab a record representing a case range to process off the worklist
1352 CaseRec CR = CaseVec.back();
1353 CaseVec.pop_back();
1354
1355 // Size is the number of Cases represented by this range. If Size is 1,
1356 // then we are processing a leaf of the binary search tree. Otherwise,
1357 // we need to pick a pivot, and push left and right ranges onto the
1358 // worklist.
1359 unsigned Size = CR.Range.second - CR.Range.first;
1360
1361 if (Size == 1) {
1362 // Create a CaseBlock record representing a conditional branch to
1363 // the Case's target mbb if the value being switched on SV is equal
1364 // to C. Otherwise, branch to default.
1365 Constant *C = CR.Range.first->first;
1366 MachineBasicBlock *Target = CR.Range.first->second;
1367 SelectionDAGISel::CaseBlock CB(ISD::SETEQ, SV, C, Target, Default,
1368 CR.CaseBB);
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001369
Nate Begemanf15485a2006-03-27 01:32:24 +00001370 // If the MBB representing the leaf node is the current MBB, then just
1371 // call visitSwitchCase to emit the code into the current block.
1372 // Otherwise, push the CaseBlock onto the vector to be later processed
1373 // by SDISel, and insert the node's MBB before the next MBB.
1374 if (CR.CaseBB == CurMBB)
1375 visitSwitchCase(CB);
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001376 else
Nate Begemanf15485a2006-03-27 01:32:24 +00001377 SwitchCases.push_back(CB);
Nate Begemanf15485a2006-03-27 01:32:24 +00001378 } else {
1379 // split case range at pivot
1380 CaseItr Pivot = CR.Range.first + (Size / 2);
1381 CaseRange LHSR(CR.Range.first, Pivot);
1382 CaseRange RHSR(Pivot, CR.Range.second);
1383 Constant *C = Pivot->first;
Chris Lattner57ab6592006-10-24 17:57:59 +00001384 MachineBasicBlock *FalseBB = 0, *TrueBB = 0;
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001385
Nate Begemanf15485a2006-03-27 01:32:24 +00001386 // We know that we branch to the LHS if the Value being switched on is
1387 // less than the Pivot value, C. We use this to optimize our binary
1388 // tree a bit, by recognizing that if SV is greater than or equal to the
1389 // LHS's Case Value, and that Case Value is exactly one less than the
1390 // Pivot's Value, then we can branch directly to the LHS's Target,
1391 // rather than creating a leaf node for it.
1392 if ((LHSR.second - LHSR.first) == 1 &&
1393 LHSR.first->first == CR.GE &&
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001394 cast<ConstantInt>(C)->getZExtValue() ==
1395 (cast<ConstantInt>(CR.GE)->getZExtValue() + 1ULL)) {
Chris Lattner57ab6592006-10-24 17:57:59 +00001396 TrueBB = LHSR.first->second;
Nate Begemanf15485a2006-03-27 01:32:24 +00001397 } else {
Chris Lattner57ab6592006-10-24 17:57:59 +00001398 TrueBB = new MachineBasicBlock(LLVMBB);
1399 CurMF->getBasicBlockList().insert(BBI, TrueBB);
1400 CaseVec.push_back(CaseRec(TrueBB, C, CR.GE, LHSR));
Nate Begemanf15485a2006-03-27 01:32:24 +00001401 }
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001402
Nate Begemanf15485a2006-03-27 01:32:24 +00001403 // Similar to the optimization above, if the Value being switched on is
1404 // known to be less than the Constant CR.LT, and the current Case Value
1405 // is CR.LT - 1, then we can branch directly to the target block for
1406 // the current Case Value, rather than emitting a RHS leaf node for it.
1407 if ((RHSR.second - RHSR.first) == 1 && CR.LT &&
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001408 cast<ConstantInt>(RHSR.first->first)->getZExtValue() ==
1409 (cast<ConstantInt>(CR.LT)->getZExtValue() - 1ULL)) {
Chris Lattner57ab6592006-10-24 17:57:59 +00001410 FalseBB = RHSR.first->second;
Nate Begemanf15485a2006-03-27 01:32:24 +00001411 } else {
Chris Lattner57ab6592006-10-24 17:57:59 +00001412 FalseBB = new MachineBasicBlock(LLVMBB);
1413 CurMF->getBasicBlockList().insert(BBI, FalseBB);
1414 CaseVec.push_back(CaseRec(FalseBB,CR.LT,C,RHSR));
Nate Begemanf15485a2006-03-27 01:32:24 +00001415 }
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001416
Nate Begemanf15485a2006-03-27 01:32:24 +00001417 // Create a CaseBlock record representing a conditional branch to
1418 // the LHS node if the value being switched on SV is less than C.
1419 // Otherwise, branch to LHS.
Chris Lattner21840b12007-02-14 07:18:16 +00001420 SelectionDAGISel::CaseBlock CB(ISD::SETLT, SV, C, TrueBB, FalseBB,
1421 CR.CaseBB);
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001422
Nate Begemanf15485a2006-03-27 01:32:24 +00001423 if (CR.CaseBB == CurMBB)
1424 visitSwitchCase(CB);
Bill Wendlingc70ddad2006-10-19 21:46:38 +00001425 else
Nate Begemanf15485a2006-03-27 01:32:24 +00001426 SwitchCases.push_back(CB);
Nate Begemanf15485a2006-03-27 01:32:24 +00001427 }
1428 }
1429}
1430
Chris Lattnerb9fccc42005-04-02 05:04:50 +00001431void SelectionDAGLowering::visitSub(User &I) {
1432 // -0.0 - X --> fneg
Reid Spencer24d6da52007-01-21 00:29:26 +00001433 const Type *Ty = I.getType();
Reid Spencer9d6565a2007-02-15 02:26:10 +00001434 if (isa<VectorType>(Ty)) {
Reid Spencer24d6da52007-01-21 00:29:26 +00001435 visitVectorBinary(I, ISD::VSUB);
1436 } else if (Ty->isFloatingPoint()) {
Chris Lattner01b3d732005-09-28 22:28:18 +00001437 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
1438 if (CFP->isExactlyValue(-0.0)) {
1439 SDOperand Op2 = getValue(I.getOperand(1));
1440 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
1441 return;
1442 }
Reid Spencer24d6da52007-01-21 00:29:26 +00001443 visitScalarBinary(I, ISD::FSUB);
Reid Spencer1628cec2006-10-26 06:15:43 +00001444 } else
Reid Spencer24d6da52007-01-21 00:29:26 +00001445 visitScalarBinary(I, ISD::SUB);
Chris Lattnerb9fccc42005-04-02 05:04:50 +00001446}
1447
Reid Spencer24d6da52007-01-21 00:29:26 +00001448void SelectionDAGLowering::visitScalarBinary(User &I, unsigned OpCode) {
Chris Lattner1c08c712005-01-07 07:47:53 +00001449 SDOperand Op1 = getValue(I.getOperand(0));
1450 SDOperand Op2 = getValue(I.getOperand(1));
Reid Spencer24d6da52007-01-21 00:29:26 +00001451
1452 setValue(&I, DAG.getNode(OpCode, Op1.getValueType(), Op1, Op2));
Reid Spencer1628cec2006-10-26 06:15:43 +00001453}
1454
Reid Spencer24d6da52007-01-21 00:29:26 +00001455void
1456SelectionDAGLowering::visitVectorBinary(User &I, unsigned OpCode) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001457 assert(isa<VectorType>(I.getType()));
1458 const VectorType *Ty = cast<VectorType>(I.getType());
Reid Spencer24d6da52007-01-21 00:29:26 +00001459 SDOperand Typ = DAG.getValueType(TLI.getValueType(Ty->getElementType()));
Reid Spencer1628cec2006-10-26 06:15:43 +00001460
Reid Spencer24d6da52007-01-21 00:29:26 +00001461 setValue(&I, DAG.getNode(OpCode, MVT::Vector,
1462 getValue(I.getOperand(0)),
1463 getValue(I.getOperand(1)),
1464 DAG.getConstant(Ty->getNumElements(), MVT::i32),
1465 Typ));
1466}
1467
1468void SelectionDAGLowering::visitEitherBinary(User &I, unsigned ScalarOp,
1469 unsigned VectorOp) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001470 if (isa<VectorType>(I.getType()))
Reid Spencer24d6da52007-01-21 00:29:26 +00001471 visitVectorBinary(I, VectorOp);
1472 else
1473 visitScalarBinary(I, ScalarOp);
Nate Begemane21ea612005-11-18 07:42:56 +00001474}
Chris Lattner2c49f272005-01-19 22:31:21 +00001475
Nate Begemane21ea612005-11-18 07:42:56 +00001476void SelectionDAGLowering::visitShift(User &I, unsigned Opcode) {
1477 SDOperand Op1 = getValue(I.getOperand(0));
1478 SDOperand Op2 = getValue(I.getOperand(1));
1479
Reid Spencer832254e2007-02-02 02:16:23 +00001480 if (TLI.getShiftAmountTy() < Op2.getValueType())
1481 Op2 = DAG.getNode(ISD::TRUNCATE, TLI.getShiftAmountTy(), Op2);
1482 else if (TLI.getShiftAmountTy() > Op2.getValueType())
1483 Op2 = DAG.getNode(ISD::ANY_EXTEND, TLI.getShiftAmountTy(), Op2);
Nate Begemane21ea612005-11-18 07:42:56 +00001484
Chris Lattner1c08c712005-01-07 07:47:53 +00001485 setValue(&I, DAG.getNode(Opcode, Op1.getValueType(), Op1, Op2));
1486}
1487
Reid Spencer45fb3f32006-11-20 01:22:35 +00001488void SelectionDAGLowering::visitICmp(User &I) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00001489 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
1490 if (ICmpInst *IC = dyn_cast<ICmpInst>(&I))
1491 predicate = IC->getPredicate();
1492 else if (ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
1493 predicate = ICmpInst::Predicate(IC->getPredicate());
1494 SDOperand Op1 = getValue(I.getOperand(0));
1495 SDOperand Op2 = getValue(I.getOperand(1));
Reid Spencer45fb3f32006-11-20 01:22:35 +00001496 ISD::CondCode Opcode;
Reid Spencere4d87aa2006-12-23 06:05:41 +00001497 switch (predicate) {
Reid Spencer45fb3f32006-11-20 01:22:35 +00001498 case ICmpInst::ICMP_EQ : Opcode = ISD::SETEQ; break;
1499 case ICmpInst::ICMP_NE : Opcode = ISD::SETNE; break;
1500 case ICmpInst::ICMP_UGT : Opcode = ISD::SETUGT; break;
1501 case ICmpInst::ICMP_UGE : Opcode = ISD::SETUGE; break;
1502 case ICmpInst::ICMP_ULT : Opcode = ISD::SETULT; break;
1503 case ICmpInst::ICMP_ULE : Opcode = ISD::SETULE; break;
1504 case ICmpInst::ICMP_SGT : Opcode = ISD::SETGT; break;
1505 case ICmpInst::ICMP_SGE : Opcode = ISD::SETGE; break;
1506 case ICmpInst::ICMP_SLT : Opcode = ISD::SETLT; break;
1507 case ICmpInst::ICMP_SLE : Opcode = ISD::SETLE; break;
1508 default:
1509 assert(!"Invalid ICmp predicate value");
1510 Opcode = ISD::SETEQ;
1511 break;
1512 }
1513 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Opcode));
1514}
1515
1516void SelectionDAGLowering::visitFCmp(User &I) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00001517 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
1518 if (FCmpInst *FC = dyn_cast<FCmpInst>(&I))
1519 predicate = FC->getPredicate();
1520 else if (ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
1521 predicate = FCmpInst::Predicate(FC->getPredicate());
Chris Lattner1c08c712005-01-07 07:47:53 +00001522 SDOperand Op1 = getValue(I.getOperand(0));
1523 SDOperand Op2 = getValue(I.getOperand(1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00001524 ISD::CondCode Condition, FOC, FPC;
1525 switch (predicate) {
1526 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
1527 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
1528 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
1529 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
1530 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
1531 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
1532 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
1533 case FCmpInst::FCMP_ORD: FOC = ISD::SETEQ; FPC = ISD::SETO; break;
1534 case FCmpInst::FCMP_UNO: FOC = ISD::SETNE; FPC = ISD::SETUO; break;
1535 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
1536 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
1537 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
1538 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
1539 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
1540 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
1541 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
1542 default:
1543 assert(!"Invalid FCmp predicate value");
1544 FOC = FPC = ISD::SETFALSE;
1545 break;
1546 }
1547 if (FiniteOnlyFPMath())
1548 Condition = FOC;
1549 else
1550 Condition = FPC;
1551 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Condition));
Chris Lattner1c08c712005-01-07 07:47:53 +00001552}
1553
1554void SelectionDAGLowering::visitSelect(User &I) {
1555 SDOperand Cond = getValue(I.getOperand(0));
1556 SDOperand TrueVal = getValue(I.getOperand(1));
1557 SDOperand FalseVal = getValue(I.getOperand(2));
Reid Spencer9d6565a2007-02-15 02:26:10 +00001558 if (!isa<VectorType>(I.getType())) {
Chris Lattnerb22e35a2006-04-08 22:22:57 +00001559 setValue(&I, DAG.getNode(ISD::SELECT, TrueVal.getValueType(), Cond,
1560 TrueVal, FalseVal));
1561 } else {
1562 setValue(&I, DAG.getNode(ISD::VSELECT, MVT::Vector, Cond, TrueVal, FalseVal,
1563 *(TrueVal.Val->op_end()-2),
1564 *(TrueVal.Val->op_end()-1)));
1565 }
Chris Lattner1c08c712005-01-07 07:47:53 +00001566}
1567
Reid Spencer3da59db2006-11-27 01:05:10 +00001568
1569void SelectionDAGLowering::visitTrunc(User &I) {
1570 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
1571 SDOperand N = getValue(I.getOperand(0));
1572 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1573 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
1574}
1575
1576void SelectionDAGLowering::visitZExt(User &I) {
1577 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
1578 // ZExt also can't be a cast to bool for same reason. So, nothing much to do
1579 SDOperand N = getValue(I.getOperand(0));
1580 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1581 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
1582}
1583
1584void SelectionDAGLowering::visitSExt(User &I) {
1585 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
1586 // SExt also can't be a cast to bool for same reason. So, nothing much to do
1587 SDOperand N = getValue(I.getOperand(0));
1588 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1589 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, DestVT, N));
1590}
1591
1592void SelectionDAGLowering::visitFPTrunc(User &I) {
1593 // FPTrunc is never a no-op cast, no need to check
1594 SDOperand N = getValue(I.getOperand(0));
1595 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1596 setValue(&I, DAG.getNode(ISD::FP_ROUND, DestVT, N));
1597}
1598
1599void SelectionDAGLowering::visitFPExt(User &I){
1600 // FPTrunc is never a no-op cast, no need to check
1601 SDOperand N = getValue(I.getOperand(0));
1602 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1603 setValue(&I, DAG.getNode(ISD::FP_EXTEND, DestVT, N));
1604}
1605
1606void SelectionDAGLowering::visitFPToUI(User &I) {
1607 // FPToUI is never a no-op cast, no need to check
1608 SDOperand N = getValue(I.getOperand(0));
1609 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1610 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, DestVT, N));
1611}
1612
1613void SelectionDAGLowering::visitFPToSI(User &I) {
1614 // FPToSI is never a no-op cast, no need to check
1615 SDOperand N = getValue(I.getOperand(0));
1616 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1617 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, DestVT, N));
1618}
1619
1620void SelectionDAGLowering::visitUIToFP(User &I) {
1621 // UIToFP is never a no-op cast, no need to check
1622 SDOperand N = getValue(I.getOperand(0));
1623 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1624 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, DestVT, N));
1625}
1626
1627void SelectionDAGLowering::visitSIToFP(User &I){
1628 // UIToFP is never a no-op cast, no need to check
1629 SDOperand N = getValue(I.getOperand(0));
1630 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1631 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, DestVT, N));
1632}
1633
1634void SelectionDAGLowering::visitPtrToInt(User &I) {
1635 // What to do depends on the size of the integer and the size of the pointer.
1636 // We can either truncate, zero extend, or no-op, accordingly.
Chris Lattner1c08c712005-01-07 07:47:53 +00001637 SDOperand N = getValue(I.getOperand(0));
Chris Lattnere25ca692006-03-22 20:09:35 +00001638 MVT::ValueType SrcVT = N.getValueType();
Chris Lattner28b5b1c2006-03-15 22:19:46 +00001639 MVT::ValueType DestVT = TLI.getValueType(I.getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00001640 SDOperand Result;
1641 if (MVT::getSizeInBits(DestVT) < MVT::getSizeInBits(SrcVT))
1642 Result = DAG.getNode(ISD::TRUNCATE, DestVT, N);
1643 else
1644 // Note: ZERO_EXTEND can handle cases where the sizes are equal too
1645 Result = DAG.getNode(ISD::ZERO_EXTEND, DestVT, N);
1646 setValue(&I, Result);
1647}
Chris Lattner1c08c712005-01-07 07:47:53 +00001648
Reid Spencer3da59db2006-11-27 01:05:10 +00001649void SelectionDAGLowering::visitIntToPtr(User &I) {
1650 // What to do depends on the size of the integer and the size of the pointer.
1651 // We can either truncate, zero extend, or no-op, accordingly.
1652 SDOperand N = getValue(I.getOperand(0));
1653 MVT::ValueType SrcVT = N.getValueType();
1654 MVT::ValueType DestVT = TLI.getValueType(I.getType());
1655 if (MVT::getSizeInBits(DestVT) < MVT::getSizeInBits(SrcVT))
1656 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
1657 else
1658 // Note: ZERO_EXTEND can handle cases where the sizes are equal too
1659 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
1660}
1661
1662void SelectionDAGLowering::visitBitCast(User &I) {
1663 SDOperand N = getValue(I.getOperand(0));
1664 MVT::ValueType DestVT = TLI.getValueType(I.getType());
Chris Lattnere25ca692006-03-22 20:09:35 +00001665 if (DestVT == MVT::Vector) {
Reid Spencer3da59db2006-11-27 01:05:10 +00001666 // This is a cast to a vector from something else.
1667 // Get information about the output vector.
Reid Spencer9d6565a2007-02-15 02:26:10 +00001668 const VectorType *DestTy = cast<VectorType>(I.getType());
Chris Lattnere25ca692006-03-22 20:09:35 +00001669 MVT::ValueType EltVT = TLI.getValueType(DestTy->getElementType());
1670 setValue(&I, DAG.getNode(ISD::VBIT_CONVERT, DestVT, N,
1671 DAG.getConstant(DestTy->getNumElements(),MVT::i32),
1672 DAG.getValueType(EltVT)));
Reid Spencer3da59db2006-11-27 01:05:10 +00001673 return;
1674 }
1675 MVT::ValueType SrcVT = N.getValueType();
1676 if (SrcVT == MVT::Vector) {
1677 // This is a cast from a vctor to something else.
1678 // Get information about the input vector.
Chris Lattnere25ca692006-03-22 20:09:35 +00001679 setValue(&I, DAG.getNode(ISD::VBIT_CONVERT, DestVT, N));
Reid Spencer3da59db2006-11-27 01:05:10 +00001680 return;
Chris Lattner1c08c712005-01-07 07:47:53 +00001681 }
Reid Spencer3da59db2006-11-27 01:05:10 +00001682
1683 // BitCast assures us that source and destination are the same size so this
1684 // is either a BIT_CONVERT or a no-op.
1685 if (DestVT != N.getValueType())
1686 setValue(&I, DAG.getNode(ISD::BIT_CONVERT, DestVT, N)); // convert types
1687 else
1688 setValue(&I, N); // noop cast.
Chris Lattner1c08c712005-01-07 07:47:53 +00001689}
1690
Chris Lattner2bbd8102006-03-29 00:11:43 +00001691void SelectionDAGLowering::visitInsertElement(User &I) {
Chris Lattnerc7029802006-03-18 01:44:44 +00001692 SDOperand InVec = getValue(I.getOperand(0));
1693 SDOperand InVal = getValue(I.getOperand(1));
1694 SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
1695 getValue(I.getOperand(2)));
1696
Chris Lattner2332b9f2006-03-19 01:17:20 +00001697 SDOperand Num = *(InVec.Val->op_end()-2);
1698 SDOperand Typ = *(InVec.Val->op_end()-1);
1699 setValue(&I, DAG.getNode(ISD::VINSERT_VECTOR_ELT, MVT::Vector,
1700 InVec, InVal, InIdx, Num, Typ));
Chris Lattnerc7029802006-03-18 01:44:44 +00001701}
1702
Chris Lattner2bbd8102006-03-29 00:11:43 +00001703void SelectionDAGLowering::visitExtractElement(User &I) {
Chris Lattner384504c2006-03-21 20:44:12 +00001704 SDOperand InVec = getValue(I.getOperand(0));
1705 SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
1706 getValue(I.getOperand(1)));
1707 SDOperand Typ = *(InVec.Val->op_end()-1);
1708 setValue(&I, DAG.getNode(ISD::VEXTRACT_VECTOR_ELT,
1709 TLI.getValueType(I.getType()), InVec, InIdx));
1710}
Chris Lattnerc7029802006-03-18 01:44:44 +00001711
Chris Lattner3e104b12006-04-08 04:15:24 +00001712void SelectionDAGLowering::visitShuffleVector(User &I) {
1713 SDOperand V1 = getValue(I.getOperand(0));
1714 SDOperand V2 = getValue(I.getOperand(1));
1715 SDOperand Mask = getValue(I.getOperand(2));
1716
1717 SDOperand Num = *(V1.Val->op_end()-2);
1718 SDOperand Typ = *(V2.Val->op_end()-1);
1719 setValue(&I, DAG.getNode(ISD::VVECTOR_SHUFFLE, MVT::Vector,
1720 V1, V2, Mask, Num, Typ));
1721}
1722
1723
Chris Lattner1c08c712005-01-07 07:47:53 +00001724void SelectionDAGLowering::visitGetElementPtr(User &I) {
1725 SDOperand N = getValue(I.getOperand(0));
1726 const Type *Ty = I.getOperand(0)->getType();
Chris Lattner1c08c712005-01-07 07:47:53 +00001727
1728 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
1729 OI != E; ++OI) {
1730 Value *Idx = *OI;
Chris Lattnerc88d8e92005-12-05 07:10:48 +00001731 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
Reid Spencerb83eb642006-10-20 07:07:24 +00001732 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
Chris Lattner1c08c712005-01-07 07:47:53 +00001733 if (Field) {
1734 // N = N + Offset
Chris Lattnerb1919e22007-02-10 19:55:17 +00001735 uint64_t Offset = TD->getStructLayout(StTy)->getElementOffset(Field);
Chris Lattner1c08c712005-01-07 07:47:53 +00001736 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
Misha Brukmandedf2bd2005-04-22 04:01:18 +00001737 getIntPtrConstant(Offset));
Chris Lattner1c08c712005-01-07 07:47:53 +00001738 }
1739 Ty = StTy->getElementType(Field);
1740 } else {
1741 Ty = cast<SequentialType>(Ty)->getElementType();
Chris Lattner7cc47772005-01-07 21:56:57 +00001742
Chris Lattner7c0104b2005-11-09 04:45:33 +00001743 // If this is a constant subscript, handle it quickly.
1744 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
Reid Spencerb83eb642006-10-20 07:07:24 +00001745 if (CI->getZExtValue() == 0) continue;
Reid Spencer47857812006-12-31 05:55:36 +00001746 uint64_t Offs =
Evan Cheng0d630d22007-01-05 01:46:20 +00001747 TD->getTypeSize(Ty)*cast<ConstantInt>(CI)->getSExtValue();
Chris Lattner7c0104b2005-11-09 04:45:33 +00001748 N = DAG.getNode(ISD::ADD, N.getValueType(), N, getIntPtrConstant(Offs));
1749 continue;
Chris Lattner1c08c712005-01-07 07:47:53 +00001750 }
Chris Lattner7c0104b2005-11-09 04:45:33 +00001751
1752 // N = N + Idx * ElementSize;
Owen Andersona69571c2006-05-03 01:29:57 +00001753 uint64_t ElementSize = TD->getTypeSize(Ty);
Chris Lattner7c0104b2005-11-09 04:45:33 +00001754 SDOperand IdxN = getValue(Idx);
1755
1756 // If the index is smaller or larger than intptr_t, truncate or extend
1757 // it.
1758 if (IdxN.getValueType() < N.getValueType()) {
Reid Spencer47857812006-12-31 05:55:36 +00001759 IdxN = DAG.getNode(ISD::SIGN_EXTEND, N.getValueType(), IdxN);
Chris Lattner7c0104b2005-11-09 04:45:33 +00001760 } else if (IdxN.getValueType() > N.getValueType())
1761 IdxN = DAG.getNode(ISD::TRUNCATE, N.getValueType(), IdxN);
1762
1763 // If this is a multiply by a power of two, turn it into a shl
1764 // immediately. This is a very common case.
1765 if (isPowerOf2_64(ElementSize)) {
1766 unsigned Amt = Log2_64(ElementSize);
1767 IdxN = DAG.getNode(ISD::SHL, N.getValueType(), IdxN,
Chris Lattner6b2d6962005-11-09 16:50:40 +00001768 DAG.getConstant(Amt, TLI.getShiftAmountTy()));
Chris Lattner7c0104b2005-11-09 04:45:33 +00001769 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
1770 continue;
1771 }
1772
1773 SDOperand Scale = getIntPtrConstant(ElementSize);
1774 IdxN = DAG.getNode(ISD::MUL, N.getValueType(), IdxN, Scale);
1775 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
Chris Lattner1c08c712005-01-07 07:47:53 +00001776 }
1777 }
1778 setValue(&I, N);
1779}
1780
1781void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
1782 // If this is a fixed sized alloca in the entry block of the function,
1783 // allocate it statically on the stack.
1784 if (FuncInfo.StaticAllocaMap.count(&I))
1785 return; // getValue will auto-populate this.
1786
1787 const Type *Ty = I.getAllocatedType();
Owen Andersona69571c2006-05-03 01:29:57 +00001788 uint64_t TySize = TLI.getTargetData()->getTypeSize(Ty);
Chris Lattner58092e32007-01-20 22:35:55 +00001789 unsigned Align =
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00001790 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
Chris Lattner58092e32007-01-20 22:35:55 +00001791 I.getAlignment());
Chris Lattner1c08c712005-01-07 07:47:53 +00001792
1793 SDOperand AllocSize = getValue(I.getArraySize());
Chris Lattner68cd65e2005-01-22 23:04:37 +00001794 MVT::ValueType IntPtr = TLI.getPointerTy();
1795 if (IntPtr < AllocSize.getValueType())
1796 AllocSize = DAG.getNode(ISD::TRUNCATE, IntPtr, AllocSize);
1797 else if (IntPtr > AllocSize.getValueType())
1798 AllocSize = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, AllocSize);
Chris Lattner1c08c712005-01-07 07:47:53 +00001799
Chris Lattner68cd65e2005-01-22 23:04:37 +00001800 AllocSize = DAG.getNode(ISD::MUL, IntPtr, AllocSize,
Chris Lattner1c08c712005-01-07 07:47:53 +00001801 getIntPtrConstant(TySize));
1802
1803 // Handle alignment. If the requested alignment is less than or equal to the
1804 // stack alignment, ignore it and round the size of the allocation up to the
1805 // stack alignment size. If the size is greater than the stack alignment, we
1806 // note this in the DYNAMIC_STACKALLOC node.
1807 unsigned StackAlign =
1808 TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
1809 if (Align <= StackAlign) {
1810 Align = 0;
1811 // Add SA-1 to the size.
1812 AllocSize = DAG.getNode(ISD::ADD, AllocSize.getValueType(), AllocSize,
1813 getIntPtrConstant(StackAlign-1));
1814 // Mask out the low bits for alignment purposes.
1815 AllocSize = DAG.getNode(ISD::AND, AllocSize.getValueType(), AllocSize,
1816 getIntPtrConstant(~(uint64_t)(StackAlign-1)));
1817 }
1818
Chris Lattnerbd564bf2006-08-08 02:23:42 +00001819 SDOperand Ops[] = { getRoot(), AllocSize, getIntPtrConstant(Align) };
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00001820 const MVT::ValueType *VTs = DAG.getNodeValueTypes(AllocSize.getValueType(),
1821 MVT::Other);
1822 SDOperand DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, VTs, 2, Ops, 3);
Chris Lattner0da331f2007-02-04 01:31:47 +00001823 setValue(&I, DSA);
1824 DAG.setRoot(DSA.getValue(1));
Chris Lattner1c08c712005-01-07 07:47:53 +00001825
1826 // Inform the Frame Information that we have just allocated a variable-sized
1827 // object.
1828 CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
1829}
1830
Chris Lattner1c08c712005-01-07 07:47:53 +00001831void SelectionDAGLowering::visitLoad(LoadInst &I) {
1832 SDOperand Ptr = getValue(I.getOperand(0));
Misha Brukmanedf128a2005-04-21 22:36:52 +00001833
Chris Lattnerd3948112005-01-17 22:19:26 +00001834 SDOperand Root;
1835 if (I.isVolatile())
1836 Root = getRoot();
1837 else {
1838 // Do not serialize non-volatile loads against each other.
1839 Root = DAG.getRoot();
1840 }
Chris Lattner28b5b1c2006-03-15 22:19:46 +00001841
Evan Cheng466685d2006-10-09 20:57:25 +00001842 setValue(&I, getLoadFrom(I.getType(), Ptr, I.getOperand(0),
Chris Lattner28b5b1c2006-03-15 22:19:46 +00001843 Root, I.isVolatile()));
1844}
1845
1846SDOperand SelectionDAGLowering::getLoadFrom(const Type *Ty, SDOperand Ptr,
Evan Cheng466685d2006-10-09 20:57:25 +00001847 const Value *SV, SDOperand Root,
Chris Lattner28b5b1c2006-03-15 22:19:46 +00001848 bool isVolatile) {
Nate Begeman5fbb5d22005-11-19 00:36:38 +00001849 SDOperand L;
Reid Spencer9d6565a2007-02-15 02:26:10 +00001850 if (const VectorType *PTy = dyn_cast<VectorType>(Ty)) {
Nate Begeman4ef3b812005-11-22 01:29:36 +00001851 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
Evan Cheng466685d2006-10-09 20:57:25 +00001852 L = DAG.getVecLoad(PTy->getNumElements(), PVT, Root, Ptr,
1853 DAG.getSrcValue(SV));
Nate Begeman5fbb5d22005-11-19 00:36:38 +00001854 } else {
Evan Cheng0b4f80e2006-12-20 01:27:29 +00001855 L = DAG.getLoad(TLI.getValueType(Ty), Root, Ptr, SV, 0, isVolatile);
Nate Begeman5fbb5d22005-11-19 00:36:38 +00001856 }
Chris Lattnerd3948112005-01-17 22:19:26 +00001857
Chris Lattner28b5b1c2006-03-15 22:19:46 +00001858 if (isVolatile)
Chris Lattnerd3948112005-01-17 22:19:26 +00001859 DAG.setRoot(L.getValue(1));
1860 else
1861 PendingLoads.push_back(L.getValue(1));
Chris Lattner28b5b1c2006-03-15 22:19:46 +00001862
1863 return L;
Chris Lattner1c08c712005-01-07 07:47:53 +00001864}
1865
1866
1867void SelectionDAGLowering::visitStore(StoreInst &I) {
1868 Value *SrcV = I.getOperand(0);
1869 SDOperand Src = getValue(SrcV);
1870 SDOperand Ptr = getValue(I.getOperand(1));
Evan Cheng0b4f80e2006-12-20 01:27:29 +00001871 DAG.setRoot(DAG.getStore(getRoot(), Src, Ptr, I.getOperand(1), 0,
Evan Cheng8b2794a2006-10-13 21:14:26 +00001872 I.isVolatile()));
Chris Lattner1c08c712005-01-07 07:47:53 +00001873}
1874
Chris Lattner0eade312006-03-24 02:22:33 +00001875/// IntrinsicCannotAccessMemory - Return true if the specified intrinsic cannot
1876/// access memory and has no other side effects at all.
1877static bool IntrinsicCannotAccessMemory(unsigned IntrinsicID) {
1878#define GET_NO_MEMORY_INTRINSICS
1879#include "llvm/Intrinsics.gen"
1880#undef GET_NO_MEMORY_INTRINSICS
1881 return false;
1882}
1883
Chris Lattnere58a7802006-04-02 03:41:14 +00001884// IntrinsicOnlyReadsMemory - Return true if the specified intrinsic doesn't
1885// have any side-effects or if it only reads memory.
1886static bool IntrinsicOnlyReadsMemory(unsigned IntrinsicID) {
1887#define GET_SIDE_EFFECT_INFO
1888#include "llvm/Intrinsics.gen"
1889#undef GET_SIDE_EFFECT_INFO
1890 return false;
1891}
1892
Chris Lattner0eade312006-03-24 02:22:33 +00001893/// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
1894/// node.
1895void SelectionDAGLowering::visitTargetIntrinsic(CallInst &I,
1896 unsigned Intrinsic) {
Chris Lattner7255a542006-03-24 22:49:42 +00001897 bool HasChain = !IntrinsicCannotAccessMemory(Intrinsic);
Chris Lattnere58a7802006-04-02 03:41:14 +00001898 bool OnlyLoad = HasChain && IntrinsicOnlyReadsMemory(Intrinsic);
Chris Lattner0eade312006-03-24 02:22:33 +00001899
1900 // Build the operand list.
Chris Lattnerbd564bf2006-08-08 02:23:42 +00001901 SmallVector<SDOperand, 8> Ops;
Chris Lattnere58a7802006-04-02 03:41:14 +00001902 if (HasChain) { // If this intrinsic has side-effects, chainify it.
1903 if (OnlyLoad) {
1904 // We don't need to serialize loads against other loads.
1905 Ops.push_back(DAG.getRoot());
1906 } else {
1907 Ops.push_back(getRoot());
1908 }
1909 }
Chris Lattner0eade312006-03-24 02:22:33 +00001910
1911 // Add the intrinsic ID as an integer operand.
1912 Ops.push_back(DAG.getConstant(Intrinsic, TLI.getPointerTy()));
1913
1914 // Add all operands of the call to the operand list.
1915 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
1916 SDOperand Op = getValue(I.getOperand(i));
1917
Reid Spencerac9dcb92007-02-15 03:39:18 +00001918 // If this is a vector type, force it to the right vector type.
Chris Lattner0eade312006-03-24 02:22:33 +00001919 if (Op.getValueType() == MVT::Vector) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001920 const VectorType *OpTy = cast<VectorType>(I.getOperand(i)->getType());
Chris Lattner0eade312006-03-24 02:22:33 +00001921 MVT::ValueType EltVT = TLI.getValueType(OpTy->getElementType());
1922
1923 MVT::ValueType VVT = MVT::getVectorType(EltVT, OpTy->getNumElements());
1924 assert(VVT != MVT::Other && "Intrinsic uses a non-legal type?");
1925 Op = DAG.getNode(ISD::VBIT_CONVERT, VVT, Op);
1926 }
1927
1928 assert(TLI.isTypeLegal(Op.getValueType()) &&
1929 "Intrinsic uses a non-legal type?");
1930 Ops.push_back(Op);
1931 }
1932
1933 std::vector<MVT::ValueType> VTs;
1934 if (I.getType() != Type::VoidTy) {
1935 MVT::ValueType VT = TLI.getValueType(I.getType());
1936 if (VT == MVT::Vector) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001937 const VectorType *DestTy = cast<VectorType>(I.getType());
Chris Lattner0eade312006-03-24 02:22:33 +00001938 MVT::ValueType EltVT = TLI.getValueType(DestTy->getElementType());
1939
1940 VT = MVT::getVectorType(EltVT, DestTy->getNumElements());
1941 assert(VT != MVT::Other && "Intrinsic uses a non-legal type?");
1942 }
1943
1944 assert(TLI.isTypeLegal(VT) && "Intrinsic uses a non-legal type?");
1945 VTs.push_back(VT);
1946 }
1947 if (HasChain)
1948 VTs.push_back(MVT::Other);
1949
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00001950 const MVT::ValueType *VTList = DAG.getNodeValueTypes(VTs);
1951
Chris Lattner0eade312006-03-24 02:22:33 +00001952 // Create the node.
Chris Lattner48b61a72006-03-28 00:40:33 +00001953 SDOperand Result;
1954 if (!HasChain)
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00001955 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VTList, VTs.size(),
1956 &Ops[0], Ops.size());
Chris Lattner48b61a72006-03-28 00:40:33 +00001957 else if (I.getType() != Type::VoidTy)
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00001958 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, VTList, VTs.size(),
1959 &Ops[0], Ops.size());
Chris Lattner48b61a72006-03-28 00:40:33 +00001960 else
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00001961 Result = DAG.getNode(ISD::INTRINSIC_VOID, VTList, VTs.size(),
1962 &Ops[0], Ops.size());
Chris Lattner48b61a72006-03-28 00:40:33 +00001963
Chris Lattnere58a7802006-04-02 03:41:14 +00001964 if (HasChain) {
1965 SDOperand Chain = Result.getValue(Result.Val->getNumValues()-1);
1966 if (OnlyLoad)
1967 PendingLoads.push_back(Chain);
1968 else
1969 DAG.setRoot(Chain);
1970 }
Chris Lattner0eade312006-03-24 02:22:33 +00001971 if (I.getType() != Type::VoidTy) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001972 if (const VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
Chris Lattner0eade312006-03-24 02:22:33 +00001973 MVT::ValueType EVT = TLI.getValueType(PTy->getElementType());
1974 Result = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, Result,
1975 DAG.getConstant(PTy->getNumElements(), MVT::i32),
1976 DAG.getValueType(EVT));
1977 }
1978 setValue(&I, Result);
1979 }
1980}
1981
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001982/// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
1983/// we want to emit this as a call to a named external function, return the name
1984/// otherwise lower it and return null.
1985const char *
1986SelectionDAGLowering::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
1987 switch (Intrinsic) {
Chris Lattner0eade312006-03-24 02:22:33 +00001988 default:
1989 // By default, turn this into a target intrinsic node.
1990 visitTargetIntrinsic(I, Intrinsic);
1991 return 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00001992 case Intrinsic::vastart: visitVAStart(I); return 0;
1993 case Intrinsic::vaend: visitVAEnd(I); return 0;
1994 case Intrinsic::vacopy: visitVACopy(I); return 0;
Nate Begemanbcc5f362007-01-29 22:58:52 +00001995 case Intrinsic::returnaddress:
1996 setValue(&I, DAG.getNode(ISD::RETURNADDR, TLI.getPointerTy(),
1997 getValue(I.getOperand(1))));
1998 return 0;
1999 case Intrinsic::frameaddress:
2000 setValue(&I, DAG.getNode(ISD::FRAMEADDR, TLI.getPointerTy(),
2001 getValue(I.getOperand(1))));
2002 return 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002003 case Intrinsic::setjmp:
Anton Korobeynikovd27a2582006-12-10 23:12:42 +00002004 return "_setjmp"+!TLI.usesUnderscoreSetJmp();
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002005 break;
2006 case Intrinsic::longjmp:
Anton Korobeynikovd27a2582006-12-10 23:12:42 +00002007 return "_longjmp"+!TLI.usesUnderscoreLongJmp();
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002008 break;
Chris Lattner03dd4652006-03-03 00:00:25 +00002009 case Intrinsic::memcpy_i32:
2010 case Intrinsic::memcpy_i64:
2011 visitMemIntrinsic(I, ISD::MEMCPY);
2012 return 0;
2013 case Intrinsic::memset_i32:
2014 case Intrinsic::memset_i64:
2015 visitMemIntrinsic(I, ISD::MEMSET);
2016 return 0;
2017 case Intrinsic::memmove_i32:
2018 case Intrinsic::memmove_i64:
2019 visitMemIntrinsic(I, ISD::MEMMOVE);
2020 return 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002021
Chris Lattner86cb6432005-12-13 17:40:33 +00002022 case Intrinsic::dbg_stoppoint: {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002023 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskey43970fe2006-03-23 18:06:46 +00002024 DbgStopPointInst &SPI = cast<DbgStopPointInst>(I);
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002025 if (MMI && SPI.getContext() && MMI->Verify(SPI.getContext())) {
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002026 SDOperand Ops[5];
Chris Lattner36ce6912005-11-29 06:21:05 +00002027
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002028 Ops[0] = getRoot();
2029 Ops[1] = getValue(SPI.getLineValue());
2030 Ops[2] = getValue(SPI.getColumnValue());
Chris Lattner36ce6912005-11-29 06:21:05 +00002031
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002032 DebugInfoDesc *DD = MMI->getDescFor(SPI.getContext());
Jim Laskeyce72b172006-02-11 01:01:30 +00002033 assert(DD && "Not a debug information descriptor");
Jim Laskey43970fe2006-03-23 18:06:46 +00002034 CompileUnitDesc *CompileUnit = cast<CompileUnitDesc>(DD);
2035
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002036 Ops[3] = DAG.getString(CompileUnit->getFileName());
2037 Ops[4] = DAG.getString(CompileUnit->getDirectory());
Jim Laskeyce72b172006-02-11 01:01:30 +00002038
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002039 DAG.setRoot(DAG.getNode(ISD::LOCATION, MVT::Other, Ops, 5));
Chris Lattner86cb6432005-12-13 17:40:33 +00002040 }
Jim Laskey43970fe2006-03-23 18:06:46 +00002041
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +00002042 return 0;
Chris Lattner36ce6912005-11-29 06:21:05 +00002043 }
Jim Laskey43970fe2006-03-23 18:06:46 +00002044 case Intrinsic::dbg_region_start: {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002045 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskey43970fe2006-03-23 18:06:46 +00002046 DbgRegionStartInst &RSI = cast<DbgRegionStartInst>(I);
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002047 if (MMI && RSI.getContext() && MMI->Verify(RSI.getContext())) {
2048 unsigned LabelID = MMI->RecordRegionStart(RSI.getContext());
Jim Laskey1ee29252007-01-26 14:34:52 +00002049 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, getRoot(),
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002050 DAG.getConstant(LabelID, MVT::i32)));
Jim Laskey43970fe2006-03-23 18:06:46 +00002051 }
2052
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +00002053 return 0;
Jim Laskey43970fe2006-03-23 18:06:46 +00002054 }
2055 case Intrinsic::dbg_region_end: {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002056 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskey43970fe2006-03-23 18:06:46 +00002057 DbgRegionEndInst &REI = cast<DbgRegionEndInst>(I);
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002058 if (MMI && REI.getContext() && MMI->Verify(REI.getContext())) {
2059 unsigned LabelID = MMI->RecordRegionEnd(REI.getContext());
Jim Laskey1ee29252007-01-26 14:34:52 +00002060 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other,
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002061 getRoot(), DAG.getConstant(LabelID, MVT::i32)));
Jim Laskey43970fe2006-03-23 18:06:46 +00002062 }
2063
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +00002064 return 0;
Jim Laskey43970fe2006-03-23 18:06:46 +00002065 }
2066 case Intrinsic::dbg_func_start: {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002067 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskey43970fe2006-03-23 18:06:46 +00002068 DbgFuncStartInst &FSI = cast<DbgFuncStartInst>(I);
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002069 if (MMI && FSI.getSubprogram() &&
2070 MMI->Verify(FSI.getSubprogram())) {
2071 unsigned LabelID = MMI->RecordRegionStart(FSI.getSubprogram());
Jim Laskey1ee29252007-01-26 14:34:52 +00002072 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other,
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002073 getRoot(), DAG.getConstant(LabelID, MVT::i32)));
Jim Laskey43970fe2006-03-23 18:06:46 +00002074 }
2075
Chris Lattnerb1a5a5c2005-11-16 07:22:30 +00002076 return 0;
Jim Laskey43970fe2006-03-23 18:06:46 +00002077 }
2078 case Intrinsic::dbg_declare: {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002079 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskey43970fe2006-03-23 18:06:46 +00002080 DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002081 if (MMI && DI.getVariable() && MMI->Verify(DI.getVariable())) {
Jim Laskey0892cee2006-03-24 09:50:27 +00002082 SDOperand AddressOp = getValue(DI.getAddress());
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002083 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(AddressOp))
Jim Laskey44c3b9f2007-01-26 21:22:28 +00002084 MMI->RecordVariable(DI.getVariable(), FI->getIndex());
Jim Laskey43970fe2006-03-23 18:06:46 +00002085 }
2086
2087 return 0;
2088 }
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002089
Jim Laskeyb180aa12007-02-21 22:53:45 +00002090 case Intrinsic::eh_exception: {
2091 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
2092
Jim Laskey735b6f82007-02-22 15:38:06 +00002093 if (MMI) {
2094 // Add a label to mark the beginning of the landing pad. Deletion of the
2095 // landing pad can thus be detected via the MachineModuleInfo.
2096 unsigned LabelID = MMI->addLandingPad(CurMBB);
2097 DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, DAG.getEntryNode(),
2098 DAG.getConstant(LabelID, MVT::i32)));
2099
2100 // Mark exception register as live in.
2101 unsigned Reg = TLI.getExceptionAddressRegister();
2102 if (Reg) CurMBB->addLiveIn(Reg);
2103
2104 // Insert the EXCEPTIONADDR instruction.
2105 SDVTList VTs = DAG.getVTList(TLI.getPointerTy(), MVT::Other);
2106 SDOperand Ops[1];
2107 Ops[0] = DAG.getRoot();
2108 SDOperand Op = DAG.getNode(ISD::EXCEPTIONADDR, VTs, Ops, 1);
2109 setValue(&I, Op);
2110 DAG.setRoot(Op.getValue(1));
Jim Laskey7a1de982007-02-24 09:45:44 +00002111 } else {
Jim Laskey64ce0ca2007-02-28 18:37:04 +00002112 setValue(&I, DAG.getConstant(0, TLI.getPointerTy()));
Jim Laskey735b6f82007-02-22 15:38:06 +00002113 }
Jim Laskeyb180aa12007-02-21 22:53:45 +00002114 return 0;
2115 }
2116
Jim Laskey0b4711b2007-03-01 20:24:30 +00002117 case Intrinsic::eh_selector:
2118 case Intrinsic::eh_filter:{
Jim Laskeyb180aa12007-02-21 22:53:45 +00002119 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
2120
Jim Laskey735b6f82007-02-22 15:38:06 +00002121 if (MMI) {
2122 // Inform the MachineModuleInfo of the personality for this landing pad.
Jim Laskeycbfdb7b2007-02-22 16:10:05 +00002123 ConstantExpr *CE = dyn_cast<ConstantExpr>(I.getOperand(2));
2124 assert(CE && CE->getOpcode() == Instruction::BitCast &&
2125 isa<Function>(CE->getOperand(0)) &&
2126 "Personality should be a function");
2127 MMI->addPersonality(CurMBB, cast<Function>(CE->getOperand(0)));
Jim Laskey0b4711b2007-03-01 20:24:30 +00002128 if (Intrinsic == Intrinsic::eh_filter)
2129 MMI->setIsFilterLandingPad(CurMBB);
Jim Laskeyb180aa12007-02-21 22:53:45 +00002130
Jim Laskey735b6f82007-02-22 15:38:06 +00002131 // Gather all the type infos for this landing pad and pass them along to
2132 // MachineModuleInfo.
2133 std::vector<GlobalVariable *> TyInfo;
2134 for (unsigned i = 3, N = I.getNumOperands(); i < N; ++i) {
Jim Laskeycbfdb7b2007-02-22 16:10:05 +00002135 ConstantExpr *CE = dyn_cast<ConstantExpr>(I.getOperand(i));
2136 if (CE && CE->getOpcode() == Instruction::BitCast &&
2137 isa<GlobalVariable>(CE->getOperand(0))) {
2138 TyInfo.push_back(cast<GlobalVariable>(CE->getOperand(0)));
2139 } else {
2140 ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(i));
2141 assert(CI && CI->getZExtValue() == 0 &&
2142 "TypeInfo must be a global variable typeinfo or NULL");
2143 TyInfo.push_back(NULL);
Jim Laskey735b6f82007-02-22 15:38:06 +00002144 }
Jim Laskey735b6f82007-02-22 15:38:06 +00002145 }
2146 MMI->addCatchTypeInfo(CurMBB, TyInfo);
2147
2148 // Mark exception selector register as live in.
2149 unsigned Reg = TLI.getExceptionSelectorRegister();
2150 if (Reg) CurMBB->addLiveIn(Reg);
2151
2152 // Insert the EHSELECTION instruction.
Jim Laskey64ce0ca2007-02-28 18:37:04 +00002153 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::Other);
Jim Laskey735b6f82007-02-22 15:38:06 +00002154 SDOperand Ops[2];
2155 Ops[0] = getValue(I.getOperand(1));
2156 Ops[1] = getRoot();
2157 SDOperand Op = DAG.getNode(ISD::EHSELECTION, VTs, Ops, 2);
2158 setValue(&I, Op);
2159 DAG.setRoot(Op.getValue(1));
Jim Laskey7a1de982007-02-24 09:45:44 +00002160 } else {
Jim Laskey64ce0ca2007-02-28 18:37:04 +00002161 setValue(&I, DAG.getConstant(0, MVT::i32));
Jim Laskey735b6f82007-02-22 15:38:06 +00002162 }
Jim Laskeyb180aa12007-02-21 22:53:45 +00002163
2164 return 0;
2165 }
2166
2167 case Intrinsic::eh_typeid_for: {
Jim Laskeyb180aa12007-02-21 22:53:45 +00002168 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Jim Laskeyb180aa12007-02-21 22:53:45 +00002169
Jim Laskey735b6f82007-02-22 15:38:06 +00002170 if (MMI) {
2171 // Find the type id for the given typeinfo.
2172 GlobalVariable *GV = NULL;
Jim Laskeycbfdb7b2007-02-22 16:10:05 +00002173 ConstantExpr *CE = dyn_cast<ConstantExpr>(I.getOperand(1));
2174 if (CE && CE->getOpcode() == Instruction::BitCast &&
2175 isa<GlobalVariable>(CE->getOperand(0))) {
2176 GV = cast<GlobalVariable>(CE->getOperand(0));
2177 } else {
2178 ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1));
2179 assert(CI && CI->getZExtValue() == 0 &&
2180 "TypeInfo must be a global variable typeinfo or NULL");
2181 GV = NULL;
Jim Laskey735b6f82007-02-22 15:38:06 +00002182 }
2183
2184 unsigned TypeID = MMI->getTypeIDFor(GV);
2185 setValue(&I, DAG.getConstant(TypeID, MVT::i32));
Jim Laskey7a1de982007-02-24 09:45:44 +00002186 } else {
2187 setValue(&I, DAG.getConstant(0, MVT::i32));
Jim Laskey735b6f82007-02-22 15:38:06 +00002188 }
Jim Laskeyb180aa12007-02-21 22:53:45 +00002189
2190 return 0;
2191 }
2192
Reid Spencer0b118202006-01-16 21:12:35 +00002193 case Intrinsic::sqrt_f32:
2194 case Intrinsic::sqrt_f64:
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002195 setValue(&I, DAG.getNode(ISD::FSQRT,
2196 getValue(I.getOperand(1)).getValueType(),
2197 getValue(I.getOperand(1))));
2198 return 0;
Chris Lattner6ddf8ed2006-09-09 06:03:30 +00002199 case Intrinsic::powi_f32:
2200 case Intrinsic::powi_f64:
2201 setValue(&I, DAG.getNode(ISD::FPOWI,
2202 getValue(I.getOperand(1)).getValueType(),
2203 getValue(I.getOperand(1)),
2204 getValue(I.getOperand(2))));
2205 return 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002206 case Intrinsic::pcmarker: {
2207 SDOperand Tmp = getValue(I.getOperand(1));
2208 DAG.setRoot(DAG.getNode(ISD::PCMARKER, MVT::Other, getRoot(), Tmp));
2209 return 0;
2210 }
Andrew Lenharth8b91c772005-11-11 22:48:54 +00002211 case Intrinsic::readcyclecounter: {
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002212 SDOperand Op = getRoot();
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00002213 SDOperand Tmp = DAG.getNode(ISD::READCYCLECOUNTER,
2214 DAG.getNodeValueTypes(MVT::i64, MVT::Other), 2,
2215 &Op, 1);
Andrew Lenharth8b91c772005-11-11 22:48:54 +00002216 setValue(&I, Tmp);
2217 DAG.setRoot(Tmp.getValue(1));
Andrew Lenharth51b8d542005-11-11 16:47:30 +00002218 return 0;
Andrew Lenharth8b91c772005-11-11 22:48:54 +00002219 }
Nate Begemand88fc032006-01-14 03:14:10 +00002220 case Intrinsic::bswap_i16:
Nate Begemand88fc032006-01-14 03:14:10 +00002221 case Intrinsic::bswap_i32:
Nate Begemand88fc032006-01-14 03:14:10 +00002222 case Intrinsic::bswap_i64:
2223 setValue(&I, DAG.getNode(ISD::BSWAP,
2224 getValue(I.getOperand(1)).getValueType(),
2225 getValue(I.getOperand(1))));
2226 return 0;
Reid Spencer0b118202006-01-16 21:12:35 +00002227 case Intrinsic::cttz_i8:
2228 case Intrinsic::cttz_i16:
2229 case Intrinsic::cttz_i32:
2230 case Intrinsic::cttz_i64:
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002231 setValue(&I, DAG.getNode(ISD::CTTZ,
2232 getValue(I.getOperand(1)).getValueType(),
2233 getValue(I.getOperand(1))));
2234 return 0;
Reid Spencer0b118202006-01-16 21:12:35 +00002235 case Intrinsic::ctlz_i8:
2236 case Intrinsic::ctlz_i16:
2237 case Intrinsic::ctlz_i32:
2238 case Intrinsic::ctlz_i64:
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002239 setValue(&I, DAG.getNode(ISD::CTLZ,
2240 getValue(I.getOperand(1)).getValueType(),
2241 getValue(I.getOperand(1))));
2242 return 0;
Reid Spencer0b118202006-01-16 21:12:35 +00002243 case Intrinsic::ctpop_i8:
2244 case Intrinsic::ctpop_i16:
2245 case Intrinsic::ctpop_i32:
2246 case Intrinsic::ctpop_i64:
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002247 setValue(&I, DAG.getNode(ISD::CTPOP,
2248 getValue(I.getOperand(1)).getValueType(),
2249 getValue(I.getOperand(1))));
2250 return 0;
Chris Lattner140d53c2006-01-13 02:50:02 +00002251 case Intrinsic::stacksave: {
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002252 SDOperand Op = getRoot();
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00002253 SDOperand Tmp = DAG.getNode(ISD::STACKSAVE,
2254 DAG.getNodeValueTypes(TLI.getPointerTy(), MVT::Other), 2, &Op, 1);
Chris Lattner140d53c2006-01-13 02:50:02 +00002255 setValue(&I, Tmp);
2256 DAG.setRoot(Tmp.getValue(1));
2257 return 0;
2258 }
Chris Lattner39a17dd2006-01-23 05:22:07 +00002259 case Intrinsic::stackrestore: {
2260 SDOperand Tmp = getValue(I.getOperand(1));
2261 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, MVT::Other, getRoot(), Tmp));
Chris Lattner140d53c2006-01-13 02:50:02 +00002262 return 0;
Chris Lattner39a17dd2006-01-23 05:22:07 +00002263 }
Chris Lattnerac22c832005-12-12 22:51:16 +00002264 case Intrinsic::prefetch:
2265 // FIXME: Currently discarding prefetches.
2266 return 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002267 }
2268}
2269
2270
Jim Laskey1da20a72007-02-23 21:45:01 +00002271void SelectionDAGLowering::LowerCallTo(Instruction &I,
2272 const Type *CalledValueTy,
2273 unsigned CallingConv,
2274 bool IsTailCall,
Jim Laskey735b6f82007-02-22 15:38:06 +00002275 SDOperand Callee, unsigned OpIdx) {
Jim Laskey1da20a72007-02-23 21:45:01 +00002276 const PointerType *PT = cast<PointerType>(CalledValueTy);
Jim Laskey735b6f82007-02-22 15:38:06 +00002277 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
2278
2279 TargetLowering::ArgListTy Args;
2280 TargetLowering::ArgListEntry Entry;
2281 Args.reserve(I.getNumOperands());
2282 for (unsigned i = OpIdx, e = I.getNumOperands(); i != e; ++i) {
2283 Value *Arg = I.getOperand(i);
2284 SDOperand ArgNode = getValue(Arg);
2285 Entry.Node = ArgNode; Entry.Ty = Arg->getType();
Anton Korobeynikovd0b82b32007-03-07 16:25:09 +00002286 Entry.isSExt = FTy->paramHasAttr(i, FunctionType::SExtAttribute);
2287 Entry.isZExt = FTy->paramHasAttr(i, FunctionType::ZExtAttribute);
Jim Laskey735b6f82007-02-22 15:38:06 +00002288 Entry.isInReg = FTy->paramHasAttr(i, FunctionType::InRegAttribute);
2289 Entry.isSRet = FTy->paramHasAttr(i, FunctionType::StructRetAttribute);
2290 Args.push_back(Entry);
2291 }
2292
2293 std::pair<SDOperand,SDOperand> Result =
2294 TLI.LowerCallTo(getRoot(), I.getType(),
2295 FTy->paramHasAttr(0,FunctionType::SExtAttribute),
Jim Laskey1da20a72007-02-23 21:45:01 +00002296 FTy->isVarArg(), CallingConv, IsTailCall,
Jim Laskey735b6f82007-02-22 15:38:06 +00002297 Callee, Args, DAG);
2298 if (I.getType() != Type::VoidTy)
2299 setValue(&I, Result.first);
2300 DAG.setRoot(Result.second);
2301}
2302
2303
Chris Lattner1c08c712005-01-07 07:47:53 +00002304void SelectionDAGLowering::visitCall(CallInst &I) {
Chris Lattner64e14b12005-01-08 22:48:57 +00002305 const char *RenameFn = 0;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002306 if (Function *F = I.getCalledFunction()) {
Reid Spencer5cbf9852007-01-30 20:08:39 +00002307 if (F->isDeclaration())
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002308 if (unsigned IID = F->getIntrinsicID()) {
2309 RenameFn = visitIntrinsicCall(I, IID);
2310 if (!RenameFn)
2311 return;
2312 } else { // Not an LLVM intrinsic.
2313 const std::string &Name = F->getName();
Chris Lattnera09f8482006-03-05 05:09:38 +00002314 if (Name[0] == 'c' && (Name == "copysign" || Name == "copysignf")) {
2315 if (I.getNumOperands() == 3 && // Basic sanity checks.
2316 I.getOperand(1)->getType()->isFloatingPoint() &&
2317 I.getType() == I.getOperand(1)->getType() &&
2318 I.getType() == I.getOperand(2)->getType()) {
2319 SDOperand LHS = getValue(I.getOperand(1));
2320 SDOperand RHS = getValue(I.getOperand(2));
2321 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, LHS.getValueType(),
2322 LHS, RHS));
2323 return;
2324 }
2325 } else if (Name[0] == 'f' && (Name == "fabs" || Name == "fabsf")) {
Chris Lattnerc0f18152005-04-02 05:26:53 +00002326 if (I.getNumOperands() == 2 && // Basic sanity checks.
2327 I.getOperand(1)->getType()->isFloatingPoint() &&
2328 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002329 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattnerc0f18152005-04-02 05:26:53 +00002330 setValue(&I, DAG.getNode(ISD::FABS, Tmp.getValueType(), Tmp));
2331 return;
2332 }
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002333 } else if (Name[0] == 's' && (Name == "sin" || Name == "sinf")) {
Chris Lattnerf76e7dc2005-04-30 04:43:14 +00002334 if (I.getNumOperands() == 2 && // Basic sanity checks.
2335 I.getOperand(1)->getType()->isFloatingPoint() &&
Chris Lattner06a248c92006-02-14 05:39:35 +00002336 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002337 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattnerf76e7dc2005-04-30 04:43:14 +00002338 setValue(&I, DAG.getNode(ISD::FSIN, Tmp.getValueType(), Tmp));
2339 return;
2340 }
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002341 } else if (Name[0] == 'c' && (Name == "cos" || Name == "cosf")) {
Chris Lattnerf76e7dc2005-04-30 04:43:14 +00002342 if (I.getNumOperands() == 2 && // Basic sanity checks.
2343 I.getOperand(1)->getType()->isFloatingPoint() &&
Chris Lattner06a248c92006-02-14 05:39:35 +00002344 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002345 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattnerf76e7dc2005-04-30 04:43:14 +00002346 setValue(&I, DAG.getNode(ISD::FCOS, Tmp.getValueType(), Tmp));
2347 return;
2348 }
2349 }
Chris Lattner1ca85d52005-05-14 13:56:55 +00002350 }
Chris Lattnerce7518c2006-01-26 22:24:51 +00002351 } else if (isa<InlineAsm>(I.getOperand(0))) {
2352 visitInlineAsm(I);
2353 return;
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00002354 }
Misha Brukmanedf128a2005-04-21 22:36:52 +00002355
Chris Lattner64e14b12005-01-08 22:48:57 +00002356 SDOperand Callee;
2357 if (!RenameFn)
2358 Callee = getValue(I.getOperand(0));
2359 else
2360 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
Jim Laskey735b6f82007-02-22 15:38:06 +00002361
Jim Laskey1da20a72007-02-23 21:45:01 +00002362 LowerCallTo(I, I.getCalledValue()->getType(),
2363 I.getCallingConv(),
2364 I.isTailCall(),
2365 Callee,
2366 1);
Chris Lattner1c08c712005-01-07 07:47:53 +00002367}
2368
Jim Laskey735b6f82007-02-22 15:38:06 +00002369
Chris Lattner864635a2006-02-22 22:37:12 +00002370SDOperand RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
Chris Lattner9f6637d2006-02-23 20:06:57 +00002371 SDOperand &Chain, SDOperand &Flag)const{
Chris Lattner864635a2006-02-22 22:37:12 +00002372 SDOperand Val = DAG.getCopyFromReg(Chain, Regs[0], RegVT, Flag);
2373 Chain = Val.getValue(1);
2374 Flag = Val.getValue(2);
2375
2376 // If the result was expanded, copy from the top part.
2377 if (Regs.size() > 1) {
2378 assert(Regs.size() == 2 &&
2379 "Cannot expand to more than 2 elts yet!");
2380 SDOperand Hi = DAG.getCopyFromReg(Chain, Regs[1], RegVT, Flag);
Evan Cheng693163e2006-10-04 22:23:53 +00002381 Chain = Hi.getValue(1);
2382 Flag = Hi.getValue(2);
Chris Lattner9f6637d2006-02-23 20:06:57 +00002383 if (DAG.getTargetLoweringInfo().isLittleEndian())
2384 return DAG.getNode(ISD::BUILD_PAIR, ValueVT, Val, Hi);
2385 else
2386 return DAG.getNode(ISD::BUILD_PAIR, ValueVT, Hi, Val);
Chris Lattner864635a2006-02-22 22:37:12 +00002387 }
Chris Lattner4e4b5762006-02-01 18:59:47 +00002388
Chris Lattnercf752aa2006-06-08 18:22:48 +00002389 // Otherwise, if the return value was promoted or extended, truncate it to the
Chris Lattner864635a2006-02-22 22:37:12 +00002390 // appropriate type.
2391 if (RegVT == ValueVT)
2392 return Val;
2393
Chris Lattnercf752aa2006-06-08 18:22:48 +00002394 if (MVT::isInteger(RegVT)) {
2395 if (ValueVT < RegVT)
2396 return DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
2397 else
2398 return DAG.getNode(ISD::ANY_EXTEND, ValueVT, Val);
2399 } else {
Chris Lattner864635a2006-02-22 22:37:12 +00002400 return DAG.getNode(ISD::FP_ROUND, ValueVT, Val);
Chris Lattnercf752aa2006-06-08 18:22:48 +00002401 }
Chris Lattner864635a2006-02-22 22:37:12 +00002402}
2403
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002404/// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
2405/// specified value into the registers specified by this object. This uses
2406/// Chain/Flag as the input and updates them for the output Chain/Flag.
2407void RegsForValue::getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
Evan Chenga8441262006-06-15 08:11:54 +00002408 SDOperand &Chain, SDOperand &Flag,
2409 MVT::ValueType PtrVT) const {
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002410 if (Regs.size() == 1) {
2411 // If there is a single register and the types differ, this must be
2412 // a promotion.
2413 if (RegVT != ValueVT) {
Chris Lattner0c48fd42006-06-08 18:27:11 +00002414 if (MVT::isInteger(RegVT)) {
2415 if (RegVT < ValueVT)
2416 Val = DAG.getNode(ISD::TRUNCATE, RegVT, Val);
2417 else
2418 Val = DAG.getNode(ISD::ANY_EXTEND, RegVT, Val);
2419 } else
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002420 Val = DAG.getNode(ISD::FP_EXTEND, RegVT, Val);
2421 }
2422 Chain = DAG.getCopyToReg(Chain, Regs[0], Val, Flag);
2423 Flag = Chain.getValue(1);
2424 } else {
Chris Lattner9f6637d2006-02-23 20:06:57 +00002425 std::vector<unsigned> R(Regs);
2426 if (!DAG.getTargetLoweringInfo().isLittleEndian())
2427 std::reverse(R.begin(), R.end());
2428
2429 for (unsigned i = 0, e = R.size(); i != e; ++i) {
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002430 SDOperand Part = DAG.getNode(ISD::EXTRACT_ELEMENT, RegVT, Val,
Evan Chenga8441262006-06-15 08:11:54 +00002431 DAG.getConstant(i, PtrVT));
Chris Lattner9f6637d2006-02-23 20:06:57 +00002432 Chain = DAG.getCopyToReg(Chain, R[i], Part, Flag);
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002433 Flag = Chain.getValue(1);
2434 }
2435 }
2436}
Chris Lattner864635a2006-02-22 22:37:12 +00002437
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002438/// AddInlineAsmOperands - Add this value to the specified inlineasm node
2439/// operand list. This adds the code marker and includes the number of
2440/// values added into it.
2441void RegsForValue::AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
Chris Lattner9f6637d2006-02-23 20:06:57 +00002442 std::vector<SDOperand> &Ops) const {
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002443 Ops.push_back(DAG.getConstant(Code | (Regs.size() << 3), MVT::i32));
2444 for (unsigned i = 0, e = Regs.size(); i != e; ++i)
2445 Ops.push_back(DAG.getRegister(Regs[i], RegVT));
2446}
Chris Lattner864635a2006-02-22 22:37:12 +00002447
2448/// isAllocatableRegister - If the specified register is safe to allocate,
2449/// i.e. it isn't a stack pointer or some other special register, return the
2450/// register class for the register. Otherwise, return null.
2451static const TargetRegisterClass *
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00002452isAllocatableRegister(unsigned Reg, MachineFunction &MF,
2453 const TargetLowering &TLI, const MRegisterInfo *MRI) {
Chris Lattnerf8814cf2006-04-02 00:24:45 +00002454 MVT::ValueType FoundVT = MVT::Other;
2455 const TargetRegisterClass *FoundRC = 0;
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00002456 for (MRegisterInfo::regclass_iterator RCI = MRI->regclass_begin(),
2457 E = MRI->regclass_end(); RCI != E; ++RCI) {
Chris Lattnerf8814cf2006-04-02 00:24:45 +00002458 MVT::ValueType ThisVT = MVT::Other;
2459
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00002460 const TargetRegisterClass *RC = *RCI;
2461 // If none of the the value types for this register class are valid, we
2462 // can't use it. For example, 64-bit reg classes on 32-bit targets.
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00002463 for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
2464 I != E; ++I) {
2465 if (TLI.isTypeLegal(*I)) {
Chris Lattnerf8814cf2006-04-02 00:24:45 +00002466 // If we have already found this register in a different register class,
2467 // choose the one with the largest VT specified. For example, on
2468 // PowerPC, we favor f64 register classes over f32.
2469 if (FoundVT == MVT::Other ||
2470 MVT::getSizeInBits(FoundVT) < MVT::getSizeInBits(*I)) {
2471 ThisVT = *I;
2472 break;
2473 }
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00002474 }
2475 }
2476
Chris Lattnerf8814cf2006-04-02 00:24:45 +00002477 if (ThisVT == MVT::Other) continue;
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00002478
Chris Lattner864635a2006-02-22 22:37:12 +00002479 // NOTE: This isn't ideal. In particular, this might allocate the
2480 // frame pointer in functions that need it (due to them not being taken
2481 // out of allocation, because a variable sized allocation hasn't been seen
2482 // yet). This is a slight code pessimization, but should still work.
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00002483 for (TargetRegisterClass::iterator I = RC->allocation_order_begin(MF),
2484 E = RC->allocation_order_end(MF); I != E; ++I)
Chris Lattnerf8814cf2006-04-02 00:24:45 +00002485 if (*I == Reg) {
2486 // We found a matching register class. Keep looking at others in case
2487 // we find one with larger registers that this physreg is also in.
2488 FoundRC = RC;
2489 FoundVT = ThisVT;
2490 break;
2491 }
Chris Lattner4e4b5762006-02-01 18:59:47 +00002492 }
Chris Lattnerf8814cf2006-04-02 00:24:45 +00002493 return FoundRC;
Chris Lattner864635a2006-02-22 22:37:12 +00002494}
2495
2496RegsForValue SelectionDAGLowering::
2497GetRegistersForValue(const std::string &ConstrCode,
2498 MVT::ValueType VT, bool isOutReg, bool isInReg,
2499 std::set<unsigned> &OutputRegs,
2500 std::set<unsigned> &InputRegs) {
2501 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
2502 TLI.getRegForInlineAsmConstraint(ConstrCode, VT);
2503 std::vector<unsigned> Regs;
2504
2505 unsigned NumRegs = VT != MVT::Other ? TLI.getNumElements(VT) : 1;
2506 MVT::ValueType RegVT;
2507 MVT::ValueType ValueVT = VT;
2508
Chris Lattner2a821602006-11-02 01:41:49 +00002509 // If this is a constraint for a specific physical register, like {r17},
2510 // assign it now.
Chris Lattner864635a2006-02-22 22:37:12 +00002511 if (PhysReg.first) {
2512 if (VT == MVT::Other)
2513 ValueVT = *PhysReg.second->vt_begin();
Chris Lattnercf752aa2006-06-08 18:22:48 +00002514
2515 // Get the actual register value type. This is important, because the user
2516 // may have asked for (e.g.) the AX register in i32 type. We need to
2517 // remember that AX is actually i16 to get the right extension.
2518 RegVT = *PhysReg.second->vt_begin();
Chris Lattner864635a2006-02-22 22:37:12 +00002519
2520 // This is a explicit reference to a physical register.
2521 Regs.push_back(PhysReg.first);
2522
2523 // If this is an expanded reference, add the rest of the regs to Regs.
2524 if (NumRegs != 1) {
Chris Lattner864635a2006-02-22 22:37:12 +00002525 TargetRegisterClass::iterator I = PhysReg.second->begin();
2526 TargetRegisterClass::iterator E = PhysReg.second->end();
2527 for (; *I != PhysReg.first; ++I)
2528 assert(I != E && "Didn't find reg!");
2529
2530 // Already added the first reg.
2531 --NumRegs; ++I;
2532 for (; NumRegs; --NumRegs, ++I) {
2533 assert(I != E && "Ran out of registers to allocate!");
2534 Regs.push_back(*I);
2535 }
2536 }
2537 return RegsForValue(Regs, RegVT, ValueVT);
2538 }
2539
Chris Lattner2a821602006-11-02 01:41:49 +00002540 // Otherwise, if this was a reference to an LLVM register class, create vregs
2541 // for this reference.
2542 std::vector<unsigned> RegClassRegs;
2543 if (PhysReg.second) {
2544 // If this is an early clobber or tied register, our regalloc doesn't know
2545 // how to maintain the constraint. If it isn't, go ahead and create vreg
2546 // and let the regalloc do the right thing.
2547 if (!isOutReg || !isInReg) {
2548 if (VT == MVT::Other)
2549 ValueVT = *PhysReg.second->vt_begin();
2550 RegVT = *PhysReg.second->vt_begin();
2551
2552 // Create the appropriate number of virtual registers.
2553 SSARegMap *RegMap = DAG.getMachineFunction().getSSARegMap();
2554 for (; NumRegs; --NumRegs)
2555 Regs.push_back(RegMap->createVirtualRegister(PhysReg.second));
2556
2557 return RegsForValue(Regs, RegVT, ValueVT);
2558 }
2559
2560 // Otherwise, we can't allocate it. Let the code below figure out how to
2561 // maintain these constraints.
2562 RegClassRegs.assign(PhysReg.second->begin(), PhysReg.second->end());
2563
2564 } else {
2565 // This is a reference to a register class that doesn't directly correspond
2566 // to an LLVM register class. Allocate NumRegs consecutive, available,
2567 // registers from the class.
2568 RegClassRegs = TLI.getRegClassForInlineAsmConstraint(ConstrCode, VT);
2569 }
Chris Lattner864635a2006-02-22 22:37:12 +00002570
2571 const MRegisterInfo *MRI = DAG.getTarget().getRegisterInfo();
2572 MachineFunction &MF = *CurMBB->getParent();
2573 unsigned NumAllocated = 0;
2574 for (unsigned i = 0, e = RegClassRegs.size(); i != e; ++i) {
2575 unsigned Reg = RegClassRegs[i];
2576 // See if this register is available.
2577 if ((isOutReg && OutputRegs.count(Reg)) || // Already used.
2578 (isInReg && InputRegs.count(Reg))) { // Already used.
2579 // Make sure we find consecutive registers.
2580 NumAllocated = 0;
2581 continue;
2582 }
2583
2584 // Check to see if this register is allocatable (i.e. don't give out the
2585 // stack pointer).
Chris Lattner9b6fb5d2006-02-22 23:09:03 +00002586 const TargetRegisterClass *RC = isAllocatableRegister(Reg, MF, TLI, MRI);
Chris Lattner864635a2006-02-22 22:37:12 +00002587 if (!RC) {
2588 // Make sure we find consecutive registers.
2589 NumAllocated = 0;
2590 continue;
2591 }
2592
2593 // Okay, this register is good, we can use it.
2594 ++NumAllocated;
2595
2596 // If we allocated enough consecutive
2597 if (NumAllocated == NumRegs) {
2598 unsigned RegStart = (i-NumAllocated)+1;
2599 unsigned RegEnd = i+1;
2600 // Mark all of the allocated registers used.
2601 for (unsigned i = RegStart; i != RegEnd; ++i) {
2602 unsigned Reg = RegClassRegs[i];
2603 Regs.push_back(Reg);
2604 if (isOutReg) OutputRegs.insert(Reg); // Mark reg used.
2605 if (isInReg) InputRegs.insert(Reg); // Mark reg used.
2606 }
2607
2608 return RegsForValue(Regs, *RC->vt_begin(), VT);
2609 }
2610 }
2611
2612 // Otherwise, we couldn't allocate enough registers for this.
2613 return RegsForValue();
Chris Lattner4e4b5762006-02-01 18:59:47 +00002614}
2615
Chris Lattner367f1092007-01-29 23:45:14 +00002616/// getConstraintGenerality - Return an integer indicating how general CT is.
2617static unsigned getConstraintGenerality(TargetLowering::ConstraintType CT) {
2618 switch (CT) {
2619 default: assert(0 && "Unknown constraint type!");
2620 case TargetLowering::C_Other:
2621 case TargetLowering::C_Unknown:
2622 return 0;
2623 case TargetLowering::C_Register:
2624 return 1;
2625 case TargetLowering::C_RegisterClass:
2626 return 2;
2627 case TargetLowering::C_Memory:
2628 return 3;
2629 }
2630}
2631
2632static std::string GetMostGeneralConstraint(std::vector<std::string> &C,
2633 const TargetLowering &TLI) {
2634 assert(!C.empty() && "Must have at least one constraint");
2635 if (C.size() == 1) return C[0];
2636
2637 std::string *Current = &C[0];
2638 // If we have multiple constraints, try to pick the most general one ahead
2639 // of time. This isn't a wonderful solution, but handles common cases.
2640 TargetLowering::ConstraintType Flavor = TLI.getConstraintType(Current[0][0]);
2641 for (unsigned j = 1, e = C.size(); j != e; ++j) {
2642 TargetLowering::ConstraintType ThisFlavor = TLI.getConstraintType(C[j][0]);
2643 if (getConstraintGenerality(ThisFlavor) >
2644 getConstraintGenerality(Flavor)) {
2645 // This constraint letter is more general than the previous one,
2646 // use it.
2647 Flavor = ThisFlavor;
2648 Current = &C[j];
2649 }
2650 }
2651 return *Current;
2652}
2653
Chris Lattner864635a2006-02-22 22:37:12 +00002654
Chris Lattnerce7518c2006-01-26 22:24:51 +00002655/// visitInlineAsm - Handle a call to an InlineAsm object.
2656///
2657void SelectionDAGLowering::visitInlineAsm(CallInst &I) {
2658 InlineAsm *IA = cast<InlineAsm>(I.getOperand(0));
2659
2660 SDOperand AsmStr = DAG.getTargetExternalSymbol(IA->getAsmString().c_str(),
2661 MVT::Other);
2662
Chris Lattner2cc2f662006-02-01 01:28:23 +00002663 std::vector<InlineAsm::ConstraintInfo> Constraints = IA->ParseConstraints();
Chris Lattner1efa40f2006-02-22 00:56:39 +00002664 std::vector<MVT::ValueType> ConstraintVTs;
Chris Lattnerce7518c2006-01-26 22:24:51 +00002665
2666 /// AsmNodeOperands - A list of pairs. The first element is a register, the
2667 /// second is a bitfield where bit #0 is set if it is a use and bit #1 is set
2668 /// if it is a def of that register.
2669 std::vector<SDOperand> AsmNodeOperands;
2670 AsmNodeOperands.push_back(SDOperand()); // reserve space for input chain
2671 AsmNodeOperands.push_back(AsmStr);
2672
2673 SDOperand Chain = getRoot();
2674 SDOperand Flag;
2675
Chris Lattner4e4b5762006-02-01 18:59:47 +00002676 // We fully assign registers here at isel time. This is not optimal, but
2677 // should work. For register classes that correspond to LLVM classes, we
2678 // could let the LLVM RA do its thing, but we currently don't. Do a prepass
2679 // over the constraints, collecting fixed registers that we know we can't use.
2680 std::set<unsigned> OutputRegs, InputRegs;
Chris Lattner1efa40f2006-02-22 00:56:39 +00002681 unsigned OpNum = 1;
Chris Lattner4e4b5762006-02-01 18:59:47 +00002682 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
Chris Lattner367f1092007-01-29 23:45:14 +00002683 std::string ConstraintCode =
2684 GetMostGeneralConstraint(Constraints[i].Codes, TLI);
Chris Lattner2223aea2006-02-02 00:25:23 +00002685
Chris Lattner1efa40f2006-02-22 00:56:39 +00002686 MVT::ValueType OpVT;
2687
2688 // Compute the value type for each operand and add it to ConstraintVTs.
2689 switch (Constraints[i].Type) {
2690 case InlineAsm::isOutput:
2691 if (!Constraints[i].isIndirectOutput) {
2692 assert(I.getType() != Type::VoidTy && "Bad inline asm!");
2693 OpVT = TLI.getValueType(I.getType());
2694 } else {
Chris Lattner22873462006-02-27 23:45:39 +00002695 const Type *OpTy = I.getOperand(OpNum)->getType();
Chris Lattner1efa40f2006-02-22 00:56:39 +00002696 OpVT = TLI.getValueType(cast<PointerType>(OpTy)->getElementType());
2697 OpNum++; // Consumes a call operand.
2698 }
2699 break;
2700 case InlineAsm::isInput:
2701 OpVT = TLI.getValueType(I.getOperand(OpNum)->getType());
2702 OpNum++; // Consumes a call operand.
2703 break;
2704 case InlineAsm::isClobber:
2705 OpVT = MVT::Other;
2706 break;
2707 }
2708
2709 ConstraintVTs.push_back(OpVT);
2710
Chris Lattner864635a2006-02-22 22:37:12 +00002711 if (TLI.getRegForInlineAsmConstraint(ConstraintCode, OpVT).first == 0)
2712 continue; // Not assigned a fixed reg.
Chris Lattner1efa40f2006-02-22 00:56:39 +00002713
Chris Lattner864635a2006-02-22 22:37:12 +00002714 // Build a list of regs that this operand uses. This always has a single
2715 // element for promoted/expanded operands.
2716 RegsForValue Regs = GetRegistersForValue(ConstraintCode, OpVT,
2717 false, false,
2718 OutputRegs, InputRegs);
Chris Lattner4e4b5762006-02-01 18:59:47 +00002719
2720 switch (Constraints[i].Type) {
2721 case InlineAsm::isOutput:
2722 // We can't assign any other output to this register.
Chris Lattner864635a2006-02-22 22:37:12 +00002723 OutputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner4e4b5762006-02-01 18:59:47 +00002724 // If this is an early-clobber output, it cannot be assigned to the same
2725 // value as the input reg.
Chris Lattner2223aea2006-02-02 00:25:23 +00002726 if (Constraints[i].isEarlyClobber || Constraints[i].hasMatchingInput)
Chris Lattner864635a2006-02-22 22:37:12 +00002727 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner4e4b5762006-02-01 18:59:47 +00002728 break;
Chris Lattner1efa40f2006-02-22 00:56:39 +00002729 case InlineAsm::isInput:
2730 // We can't assign any other input to this register.
Chris Lattner864635a2006-02-22 22:37:12 +00002731 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner1efa40f2006-02-22 00:56:39 +00002732 break;
Chris Lattner4e4b5762006-02-01 18:59:47 +00002733 case InlineAsm::isClobber:
2734 // Clobbered regs cannot be used as inputs or outputs.
Chris Lattner864635a2006-02-22 22:37:12 +00002735 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
2736 OutputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner4e4b5762006-02-01 18:59:47 +00002737 break;
Chris Lattner4e4b5762006-02-01 18:59:47 +00002738 }
2739 }
Chris Lattner2cc2f662006-02-01 01:28:23 +00002740
Chris Lattner0f0b7d42006-02-21 23:12:12 +00002741 // Loop over all of the inputs, copying the operand values into the
2742 // appropriate registers and processing the output regs.
Chris Lattner864635a2006-02-22 22:37:12 +00002743 RegsForValue RetValRegs;
2744 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
Chris Lattner1efa40f2006-02-22 00:56:39 +00002745 OpNum = 1;
Chris Lattner0f0b7d42006-02-21 23:12:12 +00002746
Chris Lattner6656dd12006-01-31 02:03:41 +00002747 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
Chris Lattner367f1092007-01-29 23:45:14 +00002748 std::string ConstraintCode =
2749 GetMostGeneralConstraint(Constraints[i].Codes, TLI);
Chris Lattner1efa40f2006-02-22 00:56:39 +00002750
Chris Lattner2cc2f662006-02-01 01:28:23 +00002751 switch (Constraints[i].Type) {
2752 case InlineAsm::isOutput: {
Chris Lattner22873462006-02-27 23:45:39 +00002753 TargetLowering::ConstraintType CTy = TargetLowering::C_RegisterClass;
2754 if (ConstraintCode.size() == 1) // not a physreg name.
2755 CTy = TLI.getConstraintType(ConstraintCode[0]);
2756
2757 if (CTy == TargetLowering::C_Memory) {
2758 // Memory output.
2759 SDOperand InOperandVal = getValue(I.getOperand(OpNum));
2760
2761 // Check that the operand (the address to store to) isn't a float.
2762 if (!MVT::isInteger(InOperandVal.getValueType()))
2763 assert(0 && "MATCH FAIL!");
2764
2765 if (!Constraints[i].isIndirectOutput)
2766 assert(0 && "MATCH FAIL!");
2767
2768 OpNum++; // Consumes a call operand.
2769
2770 // Extend/truncate to the right pointer type if needed.
2771 MVT::ValueType PtrType = TLI.getPointerTy();
2772 if (InOperandVal.getValueType() < PtrType)
2773 InOperandVal = DAG.getNode(ISD::ZERO_EXTEND, PtrType, InOperandVal);
2774 else if (InOperandVal.getValueType() > PtrType)
2775 InOperandVal = DAG.getNode(ISD::TRUNCATE, PtrType, InOperandVal);
2776
2777 // Add information to the INLINEASM node to know about this output.
2778 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
2779 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
2780 AsmNodeOperands.push_back(InOperandVal);
2781 break;
2782 }
2783
2784 // Otherwise, this is a register output.
2785 assert(CTy == TargetLowering::C_RegisterClass && "Unknown op type!");
2786
Chris Lattner864635a2006-02-22 22:37:12 +00002787 // If this is an early-clobber output, or if there is an input
2788 // constraint that matches this, we need to reserve the input register
2789 // so no other inputs allocate to it.
2790 bool UsesInputRegister = false;
2791 if (Constraints[i].isEarlyClobber || Constraints[i].hasMatchingInput)
2792 UsesInputRegister = true;
2793
2794 // Copy the output from the appropriate register. Find a register that
Chris Lattner1efa40f2006-02-22 00:56:39 +00002795 // we can use.
Chris Lattner864635a2006-02-22 22:37:12 +00002796 RegsForValue Regs =
2797 GetRegistersForValue(ConstraintCode, ConstraintVTs[i],
2798 true, UsesInputRegister,
2799 OutputRegs, InputRegs);
Chris Lattnerd03f1582006-10-31 07:33:13 +00002800 if (Regs.Regs.empty()) {
Bill Wendling832171c2006-12-07 20:04:42 +00002801 cerr << "Couldn't allocate output reg for contraint '"
2802 << ConstraintCode << "'!\n";
Chris Lattnerd03f1582006-10-31 07:33:13 +00002803 exit(1);
2804 }
Chris Lattner1efa40f2006-02-22 00:56:39 +00002805
Chris Lattner2cc2f662006-02-01 01:28:23 +00002806 if (!Constraints[i].isIndirectOutput) {
Chris Lattner864635a2006-02-22 22:37:12 +00002807 assert(RetValRegs.Regs.empty() &&
Chris Lattner2cc2f662006-02-01 01:28:23 +00002808 "Cannot have multiple output constraints yet!");
Chris Lattner2cc2f662006-02-01 01:28:23 +00002809 assert(I.getType() != Type::VoidTy && "Bad inline asm!");
Chris Lattner864635a2006-02-22 22:37:12 +00002810 RetValRegs = Regs;
Chris Lattner2cc2f662006-02-01 01:28:23 +00002811 } else {
Chris Lattner22873462006-02-27 23:45:39 +00002812 IndirectStoresToEmit.push_back(std::make_pair(Regs,
2813 I.getOperand(OpNum)));
Chris Lattner2cc2f662006-02-01 01:28:23 +00002814 OpNum++; // Consumes a call operand.
2815 }
Chris Lattner6656dd12006-01-31 02:03:41 +00002816
2817 // Add information to the INLINEASM node to know that this register is
2818 // set.
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002819 Regs.AddInlineAsmOperands(2 /*REGDEF*/, DAG, AsmNodeOperands);
Chris Lattner6656dd12006-01-31 02:03:41 +00002820 break;
2821 }
2822 case InlineAsm::isInput: {
Chris Lattner22873462006-02-27 23:45:39 +00002823 SDOperand InOperandVal = getValue(I.getOperand(OpNum));
Chris Lattner4e4b5762006-02-01 18:59:47 +00002824 OpNum++; // Consumes a call operand.
Chris Lattner3d81fee2006-02-04 02:16:44 +00002825
Chris Lattner2223aea2006-02-02 00:25:23 +00002826 if (isdigit(ConstraintCode[0])) { // Matching constraint?
2827 // If this is required to match an output register we have already set,
2828 // just use its register.
2829 unsigned OperandNo = atoi(ConstraintCode.c_str());
Chris Lattner3d81fee2006-02-04 02:16:44 +00002830
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002831 // Scan until we find the definition we already emitted of this operand.
2832 // When we find it, create a RegsForValue operand.
2833 unsigned CurOp = 2; // The first operand.
2834 for (; OperandNo; --OperandNo) {
2835 // Advance to the next operand.
2836 unsigned NumOps =
2837 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
Chris Lattnera15cf702006-07-20 19:02:21 +00002838 assert(((NumOps & 7) == 2 /*REGDEF*/ ||
2839 (NumOps & 7) == 4 /*MEM*/) &&
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002840 "Skipped past definitions?");
2841 CurOp += (NumOps>>3)+1;
2842 }
2843
2844 unsigned NumOps =
2845 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
Chris Lattner527fae12007-02-01 01:21:12 +00002846 if ((NumOps & 7) == 2 /*REGDEF*/) {
2847 // Add NumOps>>3 registers to MatchedRegs.
2848 RegsForValue MatchedRegs;
2849 MatchedRegs.ValueVT = InOperandVal.getValueType();
2850 MatchedRegs.RegVT = AsmNodeOperands[CurOp+1].getValueType();
2851 for (unsigned i = 0, e = NumOps>>3; i != e; ++i) {
2852 unsigned Reg =
2853 cast<RegisterSDNode>(AsmNodeOperands[++CurOp])->getReg();
2854 MatchedRegs.Regs.push_back(Reg);
2855 }
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002856
Chris Lattner527fae12007-02-01 01:21:12 +00002857 // Use the produced MatchedRegs object to
2858 MatchedRegs.getCopyToRegs(InOperandVal, DAG, Chain, Flag,
2859 TLI.getPointerTy());
2860 MatchedRegs.AddInlineAsmOperands(1 /*REGUSE*/, DAG, AsmNodeOperands);
2861 break;
2862 } else {
2863 assert((NumOps & 7) == 4/*MEM*/ && "Unknown matching constraint!");
2864 assert(0 && "matching constraints for memory operands unimp");
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002865 }
Chris Lattner2223aea2006-02-02 00:25:23 +00002866 }
Chris Lattner87bc3bd2006-02-24 01:11:24 +00002867
2868 TargetLowering::ConstraintType CTy = TargetLowering::C_RegisterClass;
2869 if (ConstraintCode.size() == 1) // not a physreg name.
2870 CTy = TLI.getConstraintType(ConstraintCode[0]);
2871
2872 if (CTy == TargetLowering::C_Other) {
Chris Lattner53069fb2006-10-31 19:41:18 +00002873 InOperandVal = TLI.isOperandValidForConstraint(InOperandVal,
2874 ConstraintCode[0], DAG);
2875 if (!InOperandVal.Val) {
Bill Wendling832171c2006-12-07 20:04:42 +00002876 cerr << "Invalid operand for inline asm constraint '"
2877 << ConstraintCode << "'!\n";
Chris Lattner53069fb2006-10-31 19:41:18 +00002878 exit(1);
2879 }
Chris Lattner87bc3bd2006-02-24 01:11:24 +00002880
2881 // Add information to the INLINEASM node to know about this input.
2882 unsigned ResOpType = 3 /*IMM*/ | (1 << 3);
2883 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
2884 AsmNodeOperands.push_back(InOperandVal);
2885 break;
2886 } else if (CTy == TargetLowering::C_Memory) {
2887 // Memory input.
2888
Chris Lattner6dfc6802007-03-08 22:29:47 +00002889 // If the operand is a float, spill to a constant pool entry to get its
2890 // address.
2891 if (ConstantFP *Val = dyn_cast<ConstantFP>(I.getOperand(OpNum-1)))
2892 InOperandVal = DAG.getConstantPool(Val, TLI.getPointerTy());
2893
Chris Lattnerb4ddac92007-03-08 07:07:03 +00002894 if (!MVT::isInteger(InOperandVal.getValueType())) {
Chris Lattner6dfc6802007-03-08 22:29:47 +00002895 cerr << "Match failed, cannot handle this yet!\n";
2896 InOperandVal.Val->dump();
Chris Lattnerb4ddac92007-03-08 07:07:03 +00002897 exit(1);
2898 }
Chris Lattner87bc3bd2006-02-24 01:11:24 +00002899
2900 // Extend/truncate to the right pointer type if needed.
2901 MVT::ValueType PtrType = TLI.getPointerTy();
2902 if (InOperandVal.getValueType() < PtrType)
2903 InOperandVal = DAG.getNode(ISD::ZERO_EXTEND, PtrType, InOperandVal);
2904 else if (InOperandVal.getValueType() > PtrType)
2905 InOperandVal = DAG.getNode(ISD::TRUNCATE, PtrType, InOperandVal);
2906
2907 // Add information to the INLINEASM node to know about this input.
2908 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
2909 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
2910 AsmNodeOperands.push_back(InOperandVal);
2911 break;
2912 }
2913
2914 assert(CTy == TargetLowering::C_RegisterClass && "Unknown op type!");
2915
2916 // Copy the input into the appropriate registers.
2917 RegsForValue InRegs =
2918 GetRegistersForValue(ConstraintCode, ConstraintVTs[i],
2919 false, true, OutputRegs, InputRegs);
2920 // FIXME: should be match fail.
2921 assert(!InRegs.Regs.empty() && "Couldn't allocate input reg!");
2922
Evan Chenga8441262006-06-15 08:11:54 +00002923 InRegs.getCopyToRegs(InOperandVal, DAG, Chain, Flag, TLI.getPointerTy());
Chris Lattner87bc3bd2006-02-24 01:11:24 +00002924
2925 InRegs.AddInlineAsmOperands(1/*REGUSE*/, DAG, AsmNodeOperands);
Chris Lattner6656dd12006-01-31 02:03:41 +00002926 break;
2927 }
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002928 case InlineAsm::isClobber: {
2929 RegsForValue ClobberedRegs =
2930 GetRegistersForValue(ConstraintCode, MVT::Other, false, false,
2931 OutputRegs, InputRegs);
2932 // Add the clobbered value to the operand list, so that the register
2933 // allocator is aware that the physreg got clobbered.
2934 if (!ClobberedRegs.Regs.empty())
2935 ClobberedRegs.AddInlineAsmOperands(2/*REGDEF*/, DAG, AsmNodeOperands);
Chris Lattner6656dd12006-01-31 02:03:41 +00002936 break;
2937 }
Chris Lattnerc3a9f8d2006-02-23 19:21:04 +00002938 }
Chris Lattner6656dd12006-01-31 02:03:41 +00002939 }
Chris Lattnerce7518c2006-01-26 22:24:51 +00002940
2941 // Finish up input operands.
2942 AsmNodeOperands[0] = Chain;
2943 if (Flag.Val) AsmNodeOperands.push_back(Flag);
2944
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00002945 Chain = DAG.getNode(ISD::INLINEASM,
2946 DAG.getNodeValueTypes(MVT::Other, MVT::Flag), 2,
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002947 &AsmNodeOperands[0], AsmNodeOperands.size());
Chris Lattnerce7518c2006-01-26 22:24:51 +00002948 Flag = Chain.getValue(1);
2949
Chris Lattner6656dd12006-01-31 02:03:41 +00002950 // If this asm returns a register value, copy the result from that register
2951 // and set it as the value of the call.
Chris Lattner864635a2006-02-22 22:37:12 +00002952 if (!RetValRegs.Regs.empty())
2953 setValue(&I, RetValRegs.getCopyFromRegs(DAG, Chain, Flag));
Chris Lattnerce7518c2006-01-26 22:24:51 +00002954
Chris Lattner6656dd12006-01-31 02:03:41 +00002955 std::vector<std::pair<SDOperand, Value*> > StoresToEmit;
2956
2957 // Process indirect outputs, first output all of the flagged copies out of
2958 // physregs.
2959 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
Chris Lattner864635a2006-02-22 22:37:12 +00002960 RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
Chris Lattner6656dd12006-01-31 02:03:41 +00002961 Value *Ptr = IndirectStoresToEmit[i].second;
Chris Lattner864635a2006-02-22 22:37:12 +00002962 SDOperand OutVal = OutRegs.getCopyFromRegs(DAG, Chain, Flag);
2963 StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
Chris Lattner6656dd12006-01-31 02:03:41 +00002964 }
2965
2966 // Emit the non-flagged stores from the physregs.
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002967 SmallVector<SDOperand, 8> OutChains;
Chris Lattner6656dd12006-01-31 02:03:41 +00002968 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i)
Evan Cheng786225a2006-10-05 23:01:46 +00002969 OutChains.push_back(DAG.getStore(Chain, StoresToEmit[i].first,
Chris Lattner6656dd12006-01-31 02:03:41 +00002970 getValue(StoresToEmit[i].second),
Evan Cheng8b2794a2006-10-13 21:14:26 +00002971 StoresToEmit[i].second, 0));
Chris Lattner6656dd12006-01-31 02:03:41 +00002972 if (!OutChains.empty())
Chris Lattnerbd564bf2006-08-08 02:23:42 +00002973 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
2974 &OutChains[0], OutChains.size());
Chris Lattnerce7518c2006-01-26 22:24:51 +00002975 DAG.setRoot(Chain);
2976}
2977
2978
Chris Lattner1c08c712005-01-07 07:47:53 +00002979void SelectionDAGLowering::visitMalloc(MallocInst &I) {
2980 SDOperand Src = getValue(I.getOperand(0));
2981
2982 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattner68cd65e2005-01-22 23:04:37 +00002983
2984 if (IntPtr < Src.getValueType())
2985 Src = DAG.getNode(ISD::TRUNCATE, IntPtr, Src);
2986 else if (IntPtr > Src.getValueType())
2987 Src = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, Src);
Chris Lattner1c08c712005-01-07 07:47:53 +00002988
2989 // Scale the source by the type size.
Owen Andersona69571c2006-05-03 01:29:57 +00002990 uint64_t ElementSize = TD->getTypeSize(I.getType()->getElementType());
Chris Lattner1c08c712005-01-07 07:47:53 +00002991 Src = DAG.getNode(ISD::MUL, Src.getValueType(),
2992 Src, getIntPtrConstant(ElementSize));
2993
Reid Spencer47857812006-12-31 05:55:36 +00002994 TargetLowering::ArgListTy Args;
2995 TargetLowering::ArgListEntry Entry;
2996 Entry.Node = Src;
2997 Entry.Ty = TLI.getTargetData()->getIntPtrType();
Reid Spencer47857812006-12-31 05:55:36 +00002998 Args.push_back(Entry);
Chris Lattnercf5734d2005-01-08 19:26:18 +00002999
3000 std::pair<SDOperand,SDOperand> Result =
Reid Spencer47857812006-12-31 05:55:36 +00003001 TLI.LowerCallTo(getRoot(), I.getType(), false, false, CallingConv::C, true,
Chris Lattnercf5734d2005-01-08 19:26:18 +00003002 DAG.getExternalSymbol("malloc", IntPtr),
3003 Args, DAG);
3004 setValue(&I, Result.first); // Pointers always fit in registers
3005 DAG.setRoot(Result.second);
Chris Lattner1c08c712005-01-07 07:47:53 +00003006}
3007
3008void SelectionDAGLowering::visitFree(FreeInst &I) {
Reid Spencer47857812006-12-31 05:55:36 +00003009 TargetLowering::ArgListTy Args;
3010 TargetLowering::ArgListEntry Entry;
3011 Entry.Node = getValue(I.getOperand(0));
3012 Entry.Ty = TLI.getTargetData()->getIntPtrType();
Reid Spencer47857812006-12-31 05:55:36 +00003013 Args.push_back(Entry);
Chris Lattner1c08c712005-01-07 07:47:53 +00003014 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattnercf5734d2005-01-08 19:26:18 +00003015 std::pair<SDOperand,SDOperand> Result =
Reid Spencer47857812006-12-31 05:55:36 +00003016 TLI.LowerCallTo(getRoot(), Type::VoidTy, false, false, CallingConv::C, true,
Chris Lattnercf5734d2005-01-08 19:26:18 +00003017 DAG.getExternalSymbol("free", IntPtr), Args, DAG);
3018 DAG.setRoot(Result.second);
Chris Lattner1c08c712005-01-07 07:47:53 +00003019}
3020
Chris Lattner025c39b2005-08-26 20:54:47 +00003021// InsertAtEndOfBasicBlock - This method should be implemented by targets that
3022// mark instructions with the 'usesCustomDAGSchedInserter' flag. These
3023// instructions are special in various ways, which require special support to
3024// insert. The specified MachineInstr is created but not inserted into any
3025// basic blocks, and the scheduler passes ownership of it to this method.
3026MachineBasicBlock *TargetLowering::InsertAtEndOfBasicBlock(MachineInstr *MI,
3027 MachineBasicBlock *MBB) {
Bill Wendling832171c2006-12-07 20:04:42 +00003028 cerr << "If a target marks an instruction with "
3029 << "'usesCustomDAGSchedInserter', it must implement "
3030 << "TargetLowering::InsertAtEndOfBasicBlock!\n";
Chris Lattner025c39b2005-08-26 20:54:47 +00003031 abort();
3032 return 0;
3033}
3034
Chris Lattner39ae3622005-01-09 00:00:49 +00003035void SelectionDAGLowering::visitVAStart(CallInst &I) {
Nate Begemanacc398c2006-01-25 18:21:52 +00003036 DAG.setRoot(DAG.getNode(ISD::VASTART, MVT::Other, getRoot(),
3037 getValue(I.getOperand(1)),
3038 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner39ae3622005-01-09 00:00:49 +00003039}
3040
3041void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
Nate Begemanacc398c2006-01-25 18:21:52 +00003042 SDOperand V = DAG.getVAArg(TLI.getValueType(I.getType()), getRoot(),
3043 getValue(I.getOperand(0)),
3044 DAG.getSrcValue(I.getOperand(0)));
3045 setValue(&I, V);
3046 DAG.setRoot(V.getValue(1));
Chris Lattner1c08c712005-01-07 07:47:53 +00003047}
3048
3049void SelectionDAGLowering::visitVAEnd(CallInst &I) {
Nate Begemanacc398c2006-01-25 18:21:52 +00003050 DAG.setRoot(DAG.getNode(ISD::VAEND, MVT::Other, getRoot(),
3051 getValue(I.getOperand(1)),
3052 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner1c08c712005-01-07 07:47:53 +00003053}
3054
3055void SelectionDAGLowering::visitVACopy(CallInst &I) {
Nate Begemanacc398c2006-01-25 18:21:52 +00003056 DAG.setRoot(DAG.getNode(ISD::VACOPY, MVT::Other, getRoot(),
3057 getValue(I.getOperand(1)),
3058 getValue(I.getOperand(2)),
3059 DAG.getSrcValue(I.getOperand(1)),
3060 DAG.getSrcValue(I.getOperand(2))));
Chris Lattner1c08c712005-01-07 07:47:53 +00003061}
3062
Evan Chengb15974a2006-12-12 07:27:38 +00003063/// ExpandScalarFormalArgs - Recursively expand the formal_argument node, either
3064/// bit_convert it or join a pair of them with a BUILD_PAIR when appropriate.
3065static SDOperand ExpandScalarFormalArgs(MVT::ValueType VT, SDNode *Arg,
3066 unsigned &i, SelectionDAG &DAG,
3067 TargetLowering &TLI) {
3068 if (TLI.getTypeAction(VT) != TargetLowering::Expand)
3069 return SDOperand(Arg, i++);
3070
3071 MVT::ValueType EVT = TLI.getTypeToTransformTo(VT);
3072 unsigned NumVals = MVT::getSizeInBits(VT) / MVT::getSizeInBits(EVT);
3073 if (NumVals == 1) {
3074 return DAG.getNode(ISD::BIT_CONVERT, VT,
3075 ExpandScalarFormalArgs(EVT, Arg, i, DAG, TLI));
3076 } else if (NumVals == 2) {
3077 SDOperand Lo = ExpandScalarFormalArgs(EVT, Arg, i, DAG, TLI);
3078 SDOperand Hi = ExpandScalarFormalArgs(EVT, Arg, i, DAG, TLI);
3079 if (!TLI.isLittleEndian())
3080 std::swap(Lo, Hi);
3081 return DAG.getNode(ISD::BUILD_PAIR, VT, Lo, Hi);
3082 } else {
3083 // Value scalarized into many values. Unimp for now.
3084 assert(0 && "Cannot expand i64 -> i16 yet!");
3085 }
3086 return SDOperand();
3087}
3088
Chris Lattnerfdfded52006-04-12 16:20:43 +00003089/// TargetLowering::LowerArguments - This is the default LowerArguments
3090/// implementation, which just inserts a FORMAL_ARGUMENTS node. FIXME: When all
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003091/// targets are migrated to using FORMAL_ARGUMENTS, this hook should be
3092/// integrated into SDISel.
Chris Lattnerfdfded52006-04-12 16:20:43 +00003093std::vector<SDOperand>
3094TargetLowering::LowerArguments(Function &F, SelectionDAG &DAG) {
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00003095 const FunctionType *FTy = F.getFunctionType();
Chris Lattnerfdfded52006-04-12 16:20:43 +00003096 // Add CC# and isVararg as operands to the FORMAL_ARGUMENTS node.
3097 std::vector<SDOperand> Ops;
Chris Lattner8c0c10c2006-05-16 06:45:34 +00003098 Ops.push_back(DAG.getRoot());
Chris Lattnerfdfded52006-04-12 16:20:43 +00003099 Ops.push_back(DAG.getConstant(F.getCallingConv(), getPointerTy()));
3100 Ops.push_back(DAG.getConstant(F.isVarArg(), getPointerTy()));
3101
3102 // Add one result value for each formal argument.
3103 std::vector<MVT::ValueType> RetVals;
Anton Korobeynikov6aa279d2007-01-28 18:01:49 +00003104 unsigned j = 1;
Anton Korobeynikovac2b2cf2007-01-28 16:04:40 +00003105 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end();
3106 I != E; ++I, ++j) {
Chris Lattnerfdfded52006-04-12 16:20:43 +00003107 MVT::ValueType VT = getValueType(I->getType());
Anton Korobeynikovd0b82b32007-03-07 16:25:09 +00003108 unsigned Flags = ISD::ParamFlags::NoFlagSet;
Lauro Ramos Venancio7aa47b62007-02-13 13:50:08 +00003109 unsigned OriginalAlignment =
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00003110 getTargetData()->getABITypeAlignment(I->getType());
Lauro Ramos Venancio7aa47b62007-02-13 13:50:08 +00003111
Chris Lattnerddf53e42007-02-26 02:56:58 +00003112 // FIXME: Distinguish between a formal with no [sz]ext attribute from one
3113 // that is zero extended!
3114 if (FTy->paramHasAttr(j, FunctionType::ZExtAttribute))
Anton Korobeynikovd0b82b32007-03-07 16:25:09 +00003115 Flags &= ~(ISD::ParamFlags::SExt);
Chris Lattnerddf53e42007-02-26 02:56:58 +00003116 if (FTy->paramHasAttr(j, FunctionType::SExtAttribute))
Anton Korobeynikovd0b82b32007-03-07 16:25:09 +00003117 Flags |= ISD::ParamFlags::SExt;
Anton Korobeynikov0db79d82007-03-06 06:10:33 +00003118 if (FTy->paramHasAttr(j, FunctionType::InRegAttribute))
Anton Korobeynikovd0b82b32007-03-07 16:25:09 +00003119 Flags |= ISD::ParamFlags::InReg;
Anton Korobeynikov0db79d82007-03-06 06:10:33 +00003120 if (FTy->paramHasAttr(j, FunctionType::StructRetAttribute))
Anton Korobeynikovd0b82b32007-03-07 16:25:09 +00003121 Flags |= ISD::ParamFlags::StructReturn;
3122 Flags |= (OriginalAlignment << ISD::ParamFlags::OrigAlignmentOffs);
Chris Lattnerddf53e42007-02-26 02:56:58 +00003123
Chris Lattnerfdfded52006-04-12 16:20:43 +00003124 switch (getTypeAction(VT)) {
3125 default: assert(0 && "Unknown type action!");
3126 case Legal:
3127 RetVals.push_back(VT);
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00003128 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
Chris Lattnerfdfded52006-04-12 16:20:43 +00003129 break;
3130 case Promote:
3131 RetVals.push_back(getTypeToTransformTo(VT));
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00003132 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
Chris Lattnerfdfded52006-04-12 16:20:43 +00003133 break;
3134 case Expand:
3135 if (VT != MVT::Vector) {
3136 // If this is a large integer, it needs to be broken up into small
3137 // integers. Figure out what the destination type is and how many small
3138 // integers it turns into.
Evan Cheng9f877882006-12-13 20:57:08 +00003139 MVT::ValueType NVT = getTypeToExpandTo(VT);
3140 unsigned NumVals = getNumElements(VT);
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00003141 for (unsigned i = 0; i != NumVals; ++i) {
Chris Lattnerfdfded52006-04-12 16:20:43 +00003142 RetVals.push_back(NVT);
Lauro Ramos Venanciocf8270a2007-02-13 18:10:13 +00003143 // if it isn't first piece, alignment must be 1
Anton Korobeynikov0db79d82007-03-06 06:10:33 +00003144 if (i > 0)
Anton Korobeynikovd0b82b32007-03-07 16:25:09 +00003145 Flags = (Flags & (~ISD::ParamFlags::OrigAlignment)) |
3146 (1 << ISD::ParamFlags::OrigAlignmentOffs);
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00003147 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
3148 }
Chris Lattnerfdfded52006-04-12 16:20:43 +00003149 } else {
3150 // Otherwise, this is a vector type. We only support legal vectors
3151 // right now.
Reid Spencer9d6565a2007-02-15 02:26:10 +00003152 unsigned NumElems = cast<VectorType>(I->getType())->getNumElements();
3153 const Type *EltTy = cast<VectorType>(I->getType())->getElementType();
Evan Chengf7179bb2006-04-27 08:29:42 +00003154
Chris Lattnerfdfded52006-04-12 16:20:43 +00003155 // Figure out if there is a Packed type corresponding to this Vector
Reid Spencerac9dcb92007-02-15 03:39:18 +00003156 // type. If so, convert to the vector type.
Chris Lattnerfdfded52006-04-12 16:20:43 +00003157 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
3158 if (TVT != MVT::Other && isTypeLegal(TVT)) {
3159 RetVals.push_back(TVT);
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00003160 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
Chris Lattnerfdfded52006-04-12 16:20:43 +00003161 } else {
3162 assert(0 && "Don't support illegal by-val vector arguments yet!");
3163 }
3164 }
3165 break;
3166 }
3167 }
Evan Cheng3b0d2862006-04-25 23:03:35 +00003168
Chris Lattner8c0c10c2006-05-16 06:45:34 +00003169 RetVals.push_back(MVT::Other);
Chris Lattnerfdfded52006-04-12 16:20:43 +00003170
3171 // Create the node.
Chris Lattnerf9f37fc2006-08-14 23:53:35 +00003172 SDNode *Result = DAG.getNode(ISD::FORMAL_ARGUMENTS,
3173 DAG.getNodeValueTypes(RetVals), RetVals.size(),
Chris Lattnerbd564bf2006-08-08 02:23:42 +00003174 &Ops[0], Ops.size()).Val;
Chris Lattner8c0c10c2006-05-16 06:45:34 +00003175
3176 DAG.setRoot(SDOperand(Result, Result->getNumValues()-1));
Chris Lattnerfdfded52006-04-12 16:20:43 +00003177
3178 // Set up the return result vector.
3179 Ops.clear();
3180 unsigned i = 0;
Reid Spencer47857812006-12-31 05:55:36 +00003181 unsigned Idx = 1;
3182 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E;
3183 ++I, ++Idx) {
Chris Lattnerfdfded52006-04-12 16:20:43 +00003184 MVT::ValueType VT = getValueType(I->getType());
3185
3186 switch (getTypeAction(VT)) {
3187 default: assert(0 && "Unknown type action!");
3188 case Legal:
3189 Ops.push_back(SDOperand(Result, i++));
3190 break;
3191 case Promote: {
3192 SDOperand Op(Result, i++);
3193 if (MVT::isInteger(VT)) {
Chris Lattnerf8e7a212007-01-04 22:22:37 +00003194 if (FTy->paramHasAttr(Idx, FunctionType::SExtAttribute))
3195 Op = DAG.getNode(ISD::AssertSext, Op.getValueType(), Op,
3196 DAG.getValueType(VT));
3197 else if (FTy->paramHasAttr(Idx, FunctionType::ZExtAttribute))
3198 Op = DAG.getNode(ISD::AssertZext, Op.getValueType(), Op,
3199 DAG.getValueType(VT));
Chris Lattnerfdfded52006-04-12 16:20:43 +00003200 Op = DAG.getNode(ISD::TRUNCATE, VT, Op);
3201 } else {
3202 assert(MVT::isFloatingPoint(VT) && "Not int or FP?");
3203 Op = DAG.getNode(ISD::FP_ROUND, VT, Op);
3204 }
3205 Ops.push_back(Op);
3206 break;
3207 }
3208 case Expand:
3209 if (VT != MVT::Vector) {
Evan Chengb15974a2006-12-12 07:27:38 +00003210 // If this is a large integer or a floating point node that needs to be
3211 // expanded, it needs to be reassembled from small integers. Figure out
3212 // what the source elt type is and how many small integers it is.
3213 Ops.push_back(ExpandScalarFormalArgs(VT, Result, i, DAG, *this));
Chris Lattnerfdfded52006-04-12 16:20:43 +00003214 } else {
3215 // Otherwise, this is a vector type. We only support legal vectors
3216 // right now.
Reid Spencer9d6565a2007-02-15 02:26:10 +00003217 const VectorType *PTy = cast<VectorType>(I->getType());
Evan Cheng020c41f2006-04-28 05:25:15 +00003218 unsigned NumElems = PTy->getNumElements();
3219 const Type *EltTy = PTy->getElementType();
Evan Chengf7179bb2006-04-27 08:29:42 +00003220
Chris Lattnerfdfded52006-04-12 16:20:43 +00003221 // Figure out if there is a Packed type corresponding to this Vector
Reid Spencerac9dcb92007-02-15 03:39:18 +00003222 // type. If so, convert to the vector type.
Chris Lattnerfdfded52006-04-12 16:20:43 +00003223 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
Chris Lattnerd202ca42006-05-17 20:49:36 +00003224 if (TVT != MVT::Other && isTypeLegal(TVT)) {
Evan Cheng020c41f2006-04-28 05:25:15 +00003225 SDOperand N = SDOperand(Result, i++);
3226 // Handle copies from generic vectors to registers.
Chris Lattnerd202ca42006-05-17 20:49:36 +00003227 N = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, N,
3228 DAG.getConstant(NumElems, MVT::i32),
3229 DAG.getValueType(getValueType(EltTy)));
3230 Ops.push_back(N);
3231 } else {
Chris Lattnerfdfded52006-04-12 16:20:43 +00003232 assert(0 && "Don't support illegal by-val vector arguments yet!");
Chris Lattnerda098e72006-05-16 23:39:44 +00003233 abort();
Chris Lattnerfdfded52006-04-12 16:20:43 +00003234 }
3235 }
3236 break;
3237 }
3238 }
3239 return Ops;
3240}
3241
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003242
Evan Chengb15974a2006-12-12 07:27:38 +00003243/// ExpandScalarCallArgs - Recursively expand call argument node by
3244/// bit_converting it or extract a pair of elements from the larger node.
3245static void ExpandScalarCallArgs(MVT::ValueType VT, SDOperand Arg,
Lauro Ramos Venancio7aa47b62007-02-13 13:50:08 +00003246 unsigned Flags,
Evan Chengb15974a2006-12-12 07:27:38 +00003247 SmallVector<SDOperand, 32> &Ops,
3248 SelectionDAG &DAG,
Lauro Ramos Venancio7aa47b62007-02-13 13:50:08 +00003249 TargetLowering &TLI,
3250 bool isFirst = true) {
3251
Evan Chengb15974a2006-12-12 07:27:38 +00003252 if (TLI.getTypeAction(VT) != TargetLowering::Expand) {
Lauro Ramos Venanciocf8270a2007-02-13 18:10:13 +00003253 // if it isn't first piece, alignment must be 1
Lauro Ramos Venancio7aa47b62007-02-13 13:50:08 +00003254 if (!isFirst)
Anton Korobeynikovd0b82b32007-03-07 16:25:09 +00003255 Flags = (Flags & (~ISD::ParamFlags::OrigAlignment)) |
3256 (1 << ISD::ParamFlags::OrigAlignmentOffs);
Evan Chengb15974a2006-12-12 07:27:38 +00003257 Ops.push_back(Arg);
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00003258 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
Evan Chengb15974a2006-12-12 07:27:38 +00003259 return;
3260 }
3261
3262 MVT::ValueType EVT = TLI.getTypeToTransformTo(VT);
3263 unsigned NumVals = MVT::getSizeInBits(VT) / MVT::getSizeInBits(EVT);
3264 if (NumVals == 1) {
3265 Arg = DAG.getNode(ISD::BIT_CONVERT, EVT, Arg);
Lauro Ramos Venancio7aa47b62007-02-13 13:50:08 +00003266 ExpandScalarCallArgs(EVT, Arg, Flags, Ops, DAG, TLI, isFirst);
Evan Chengb15974a2006-12-12 07:27:38 +00003267 } else if (NumVals == 2) {
3268 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, EVT, Arg,
3269 DAG.getConstant(0, TLI.getPointerTy()));
3270 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, EVT, Arg,
3271 DAG.getConstant(1, TLI.getPointerTy()));
3272 if (!TLI.isLittleEndian())
3273 std::swap(Lo, Hi);
Lauro Ramos Venancio7aa47b62007-02-13 13:50:08 +00003274 ExpandScalarCallArgs(EVT, Lo, Flags, Ops, DAG, TLI, isFirst);
3275 ExpandScalarCallArgs(EVT, Hi, Flags, Ops, DAG, TLI, false);
Evan Chengb15974a2006-12-12 07:27:38 +00003276 } else {
3277 // Value scalarized into many values. Unimp for now.
3278 assert(0 && "Cannot expand i64 -> i16 yet!");
3279 }
3280}
3281
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003282/// TargetLowering::LowerCallTo - This is the default LowerCallTo
3283/// implementation, which just inserts an ISD::CALL node, which is later custom
3284/// lowered by the target to something concrete. FIXME: When all targets are
3285/// migrated to using ISD::CALL, this hook should be integrated into SDISel.
3286std::pair<SDOperand, SDOperand>
Reid Spencer47857812006-12-31 05:55:36 +00003287TargetLowering::LowerCallTo(SDOperand Chain, const Type *RetTy,
3288 bool RetTyIsSigned, bool isVarArg,
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003289 unsigned CallingConv, bool isTailCall,
3290 SDOperand Callee,
3291 ArgListTy &Args, SelectionDAG &DAG) {
Chris Lattnerbe384162006-08-16 22:57:46 +00003292 SmallVector<SDOperand, 32> Ops;
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003293 Ops.push_back(Chain); // Op#0 - Chain
3294 Ops.push_back(DAG.getConstant(CallingConv, getPointerTy())); // Op#1 - CC
3295 Ops.push_back(DAG.getConstant(isVarArg, getPointerTy())); // Op#2 - VarArg
3296 Ops.push_back(DAG.getConstant(isTailCall, getPointerTy())); // Op#3 - Tail
3297 Ops.push_back(Callee);
3298
3299 // Handle all of the outgoing arguments.
3300 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
Reid Spencer47857812006-12-31 05:55:36 +00003301 MVT::ValueType VT = getValueType(Args[i].Ty);
3302 SDOperand Op = Args[i].Node;
Anton Korobeynikovd0b82b32007-03-07 16:25:09 +00003303 unsigned Flags = ISD::ParamFlags::NoFlagSet;
Lauro Ramos Venancio7aa47b62007-02-13 13:50:08 +00003304 unsigned OriginalAlignment =
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00003305 getTargetData()->getABITypeAlignment(Args[i].Ty);
Anton Korobeynikov0db79d82007-03-06 06:10:33 +00003306
Anton Korobeynikovd0b82b32007-03-07 16:25:09 +00003307 if (Args[i].isSExt)
3308 Flags |= ISD::ParamFlags::SExt;
3309 if (Args[i].isZExt)
3310 Flags |= ISD::ParamFlags::ZExt;
Anton Korobeynikov0db79d82007-03-06 06:10:33 +00003311 if (Args[i].isInReg)
Anton Korobeynikovd0b82b32007-03-07 16:25:09 +00003312 Flags |= ISD::ParamFlags::InReg;
Anton Korobeynikov0db79d82007-03-06 06:10:33 +00003313 if (Args[i].isSRet)
Anton Korobeynikovd0b82b32007-03-07 16:25:09 +00003314 Flags |= ISD::ParamFlags::StructReturn;
3315 Flags |= OriginalAlignment << ISD::ParamFlags::OrigAlignmentOffs;
Anton Korobeynikov0db79d82007-03-06 06:10:33 +00003316
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003317 switch (getTypeAction(VT)) {
3318 default: assert(0 && "Unknown type action!");
Lauro Ramos Venancio7aa47b62007-02-13 13:50:08 +00003319 case Legal:
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003320 Ops.push_back(Op);
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00003321 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003322 break;
3323 case Promote:
3324 if (MVT::isInteger(VT)) {
Anton Korobeynikovd0b82b32007-03-07 16:25:09 +00003325 unsigned ExtOp;
3326 if (Args[i].isSExt)
3327 ExtOp = ISD::SIGN_EXTEND;
3328 else if (Args[i].isZExt)
3329 ExtOp = ISD::ZERO_EXTEND;
3330 else
3331 ExtOp = ISD::ANY_EXTEND;
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003332 Op = DAG.getNode(ExtOp, getTypeToTransformTo(VT), Op);
3333 } else {
3334 assert(MVT::isFloatingPoint(VT) && "Not int or FP?");
3335 Op = DAG.getNode(ISD::FP_EXTEND, getTypeToTransformTo(VT), Op);
3336 }
3337 Ops.push_back(Op);
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00003338 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003339 break;
3340 case Expand:
3341 if (VT != MVT::Vector) {
3342 // If this is a large integer, it needs to be broken down into small
3343 // integers. Figure out what the source elt type is and how many small
3344 // integers it is.
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00003345 ExpandScalarCallArgs(VT, Op, Flags, Ops, DAG, *this);
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003346 } else {
Chris Lattnerda098e72006-05-16 23:39:44 +00003347 // Otherwise, this is a vector type. We only support legal vectors
3348 // right now.
Reid Spencer9d6565a2007-02-15 02:26:10 +00003349 const VectorType *PTy = cast<VectorType>(Args[i].Ty);
Chris Lattnerda098e72006-05-16 23:39:44 +00003350 unsigned NumElems = PTy->getNumElements();
3351 const Type *EltTy = PTy->getElementType();
3352
3353 // Figure out if there is a Packed type corresponding to this Vector
Reid Spencerac9dcb92007-02-15 03:39:18 +00003354 // type. If so, convert to the vector type.
Chris Lattnerda098e72006-05-16 23:39:44 +00003355 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
Chris Lattner1b8daae2006-05-17 20:43:21 +00003356 if (TVT != MVT::Other && isTypeLegal(TVT)) {
Reid Spencerac9dcb92007-02-15 03:39:18 +00003357 // Insert a VBIT_CONVERT of the MVT::Vector type to the vector type.
Chris Lattner1b8daae2006-05-17 20:43:21 +00003358 Op = DAG.getNode(ISD::VBIT_CONVERT, TVT, Op);
3359 Ops.push_back(Op);
Anton Korobeynikovb10308e2007-01-28 13:31:35 +00003360 Ops.push_back(DAG.getConstant(Flags, MVT::i32));
Chris Lattner1b8daae2006-05-17 20:43:21 +00003361 } else {
Chris Lattnerda098e72006-05-16 23:39:44 +00003362 assert(0 && "Don't support illegal by-val vector call args yet!");
3363 abort();
3364 }
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003365 }
3366 break;
3367 }
3368 }
3369
3370 // Figure out the result value types.
Chris Lattnerbe384162006-08-16 22:57:46 +00003371 SmallVector<MVT::ValueType, 4> RetTys;
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003372
3373 if (RetTy != Type::VoidTy) {
3374 MVT::ValueType VT = getValueType(RetTy);
3375 switch (getTypeAction(VT)) {
3376 default: assert(0 && "Unknown type action!");
3377 case Legal:
3378 RetTys.push_back(VT);
3379 break;
3380 case Promote:
3381 RetTys.push_back(getTypeToTransformTo(VT));
3382 break;
3383 case Expand:
3384 if (VT != MVT::Vector) {
3385 // If this is a large integer, it needs to be reassembled from small
3386 // integers. Figure out what the source elt type is and how many small
3387 // integers it is.
Evan Cheng9f877882006-12-13 20:57:08 +00003388 MVT::ValueType NVT = getTypeToExpandTo(VT);
3389 unsigned NumVals = getNumElements(VT);
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003390 for (unsigned i = 0; i != NumVals; ++i)
3391 RetTys.push_back(NVT);
3392 } else {
Chris Lattnerda098e72006-05-16 23:39:44 +00003393 // Otherwise, this is a vector type. We only support legal vectors
3394 // right now.
Reid Spencer9d6565a2007-02-15 02:26:10 +00003395 const VectorType *PTy = cast<VectorType>(RetTy);
Chris Lattnerda098e72006-05-16 23:39:44 +00003396 unsigned NumElems = PTy->getNumElements();
3397 const Type *EltTy = PTy->getElementType();
3398
3399 // Figure out if there is a Packed type corresponding to this Vector
Reid Spencerac9dcb92007-02-15 03:39:18 +00003400 // type. If so, convert to the vector type.
Chris Lattnerda098e72006-05-16 23:39:44 +00003401 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
3402 if (TVT != MVT::Other && isTypeLegal(TVT)) {
3403 RetTys.push_back(TVT);
3404 } else {
3405 assert(0 && "Don't support illegal by-val vector call results yet!");
3406 abort();
3407 }
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003408 }
3409 }
3410 }
3411
3412 RetTys.push_back(MVT::Other); // Always has a chain.
3413
3414 // Finally, create the CALL node.
Chris Lattnerbe384162006-08-16 22:57:46 +00003415 SDOperand Res = DAG.getNode(ISD::CALL,
3416 DAG.getVTList(&RetTys[0], RetTys.size()),
3417 &Ops[0], Ops.size());
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003418
3419 // This returns a pair of operands. The first element is the
3420 // return value for the function (if RetTy is not VoidTy). The second
3421 // element is the outgoing token chain.
3422 SDOperand ResVal;
3423 if (RetTys.size() != 1) {
3424 MVT::ValueType VT = getValueType(RetTy);
3425 if (RetTys.size() == 2) {
3426 ResVal = Res;
3427
3428 // If this value was promoted, truncate it down.
3429 if (ResVal.getValueType() != VT) {
Chris Lattnerda098e72006-05-16 23:39:44 +00003430 if (VT == MVT::Vector) {
3431 // Insert a VBITCONVERT to convert from the packed result type to the
3432 // MVT::Vector type.
Reid Spencer9d6565a2007-02-15 02:26:10 +00003433 unsigned NumElems = cast<VectorType>(RetTy)->getNumElements();
3434 const Type *EltTy = cast<VectorType>(RetTy)->getElementType();
Chris Lattnerda098e72006-05-16 23:39:44 +00003435
3436 // Figure out if there is a Packed type corresponding to this Vector
Reid Spencerac9dcb92007-02-15 03:39:18 +00003437 // type. If so, convert to the vector type.
Chris Lattnerfea997a2007-02-01 04:55:59 +00003438 MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy),NumElems);
Chris Lattnerda098e72006-05-16 23:39:44 +00003439 if (TVT != MVT::Other && isTypeLegal(TVT)) {
Chris Lattnerda098e72006-05-16 23:39:44 +00003440 // Insert a VBIT_CONVERT of the FORMAL_ARGUMENTS to a
3441 // "N x PTyElementVT" MVT::Vector type.
3442 ResVal = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, ResVal,
Chris Lattnerd202ca42006-05-17 20:49:36 +00003443 DAG.getConstant(NumElems, MVT::i32),
3444 DAG.getValueType(getValueType(EltTy)));
Chris Lattnerda098e72006-05-16 23:39:44 +00003445 } else {
3446 abort();
3447 }
3448 } else if (MVT::isInteger(VT)) {
Reid Spencer47857812006-12-31 05:55:36 +00003449 unsigned AssertOp = ISD::AssertSext;
3450 if (!RetTyIsSigned)
3451 AssertOp = ISD::AssertZext;
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003452 ResVal = DAG.getNode(AssertOp, ResVal.getValueType(), ResVal,
3453 DAG.getValueType(VT));
3454 ResVal = DAG.getNode(ISD::TRUNCATE, VT, ResVal);
3455 } else {
3456 assert(MVT::isFloatingPoint(VT));
Evan Cheng1a8f1fe2006-12-09 02:42:38 +00003457 if (getTypeAction(VT) == Expand)
3458 ResVal = DAG.getNode(ISD::BIT_CONVERT, VT, ResVal);
3459 else
3460 ResVal = DAG.getNode(ISD::FP_ROUND, VT, ResVal);
Chris Lattnerf4ec8172006-05-16 22:53:20 +00003461 }
3462 }
3463 } else if (RetTys.size() == 3) {
3464 ResVal = DAG.getNode(ISD::BUILD_PAIR, VT,
3465 Res.getValue(0), Res.getValue(1));
3466
3467 } else {
3468 assert(0 && "Case not handled yet!");
3469 }
3470 }
3471
3472 return std::make_pair(ResVal, Res.getValue(Res.Val->getNumValues()-1));
3473}
3474
Chris Lattner50381b62005-05-14 05:50:48 +00003475SDOperand TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
Chris Lattner171453a2005-01-16 07:28:41 +00003476 assert(0 && "LowerOperation not implemented for this target!");
3477 abort();
Misha Brukmand3f03e42005-02-17 21:39:27 +00003478 return SDOperand();
Chris Lattner171453a2005-01-16 07:28:41 +00003479}
3480
Nate Begeman0aed7842006-01-28 03:14:31 +00003481SDOperand TargetLowering::CustomPromoteOperation(SDOperand Op,
3482 SelectionDAG &DAG) {
3483 assert(0 && "CustomPromoteOperation not implemented for this target!");
3484 abort();
3485 return SDOperand();
3486}
3487
Evan Cheng74d0aa92006-02-15 21:59:04 +00003488/// getMemsetValue - Vectorized representation of the memset value
Evan Cheng1db92f92006-02-14 08:22:34 +00003489/// operand.
3490static SDOperand getMemsetValue(SDOperand Value, MVT::ValueType VT,
Evan Chenga47876d2006-02-15 22:12:35 +00003491 SelectionDAG &DAG) {
Evan Cheng1db92f92006-02-14 08:22:34 +00003492 MVT::ValueType CurVT = VT;
3493 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
3494 uint64_t Val = C->getValue() & 255;
3495 unsigned Shift = 8;
3496 while (CurVT != MVT::i8) {
3497 Val = (Val << Shift) | Val;
3498 Shift <<= 1;
3499 CurVT = (MVT::ValueType)((unsigned)CurVT - 1);
Evan Cheng1db92f92006-02-14 08:22:34 +00003500 }
3501 return DAG.getConstant(Val, VT);
3502 } else {
3503 Value = DAG.getNode(ISD::ZERO_EXTEND, VT, Value);
3504 unsigned Shift = 8;
3505 while (CurVT != MVT::i8) {
3506 Value =
3507 DAG.getNode(ISD::OR, VT,
3508 DAG.getNode(ISD::SHL, VT, Value,
3509 DAG.getConstant(Shift, MVT::i8)), Value);
3510 Shift <<= 1;
3511 CurVT = (MVT::ValueType)((unsigned)CurVT - 1);
Evan Cheng1db92f92006-02-14 08:22:34 +00003512 }
3513
3514 return Value;
3515 }
3516}
3517
Evan Cheng74d0aa92006-02-15 21:59:04 +00003518/// getMemsetStringVal - Similar to getMemsetValue. Except this is only
3519/// used when a memcpy is turned into a memset when the source is a constant
3520/// string ptr.
3521static SDOperand getMemsetStringVal(MVT::ValueType VT,
3522 SelectionDAG &DAG, TargetLowering &TLI,
3523 std::string &Str, unsigned Offset) {
Evan Cheng74d0aa92006-02-15 21:59:04 +00003524 uint64_t Val = 0;
3525 unsigned MSB = getSizeInBits(VT) / 8;
3526 if (TLI.isLittleEndian())
3527 Offset = Offset + MSB - 1;
3528 for (unsigned i = 0; i != MSB; ++i) {
Evan Chenga5a57d62006-11-29 01:38:07 +00003529 Val = (Val << 8) | (unsigned char)Str[Offset];
Evan Cheng74d0aa92006-02-15 21:59:04 +00003530 Offset += TLI.isLittleEndian() ? -1 : 1;
3531 }
3532 return DAG.getConstant(Val, VT);
3533}
3534
Evan Cheng1db92f92006-02-14 08:22:34 +00003535/// getMemBasePlusOffset - Returns base and offset node for the
3536static SDOperand getMemBasePlusOffset(SDOperand Base, unsigned Offset,
3537 SelectionDAG &DAG, TargetLowering &TLI) {
3538 MVT::ValueType VT = Base.getValueType();
3539 return DAG.getNode(ISD::ADD, VT, Base, DAG.getConstant(Offset, VT));
3540}
3541
Evan Chengc4f8eee2006-02-14 20:12:38 +00003542/// MeetsMaxMemopRequirement - Determines if the number of memory ops required
Evan Cheng80e89d72006-02-14 09:11:59 +00003543/// to replace the memset / memcpy is below the threshold. It also returns the
3544/// types of the sequence of memory ops to perform memset / memcpy.
Evan Chengc4f8eee2006-02-14 20:12:38 +00003545static bool MeetsMaxMemopRequirement(std::vector<MVT::ValueType> &MemOps,
3546 unsigned Limit, uint64_t Size,
3547 unsigned Align, TargetLowering &TLI) {
Evan Cheng1db92f92006-02-14 08:22:34 +00003548 MVT::ValueType VT;
3549
3550 if (TLI.allowsUnalignedMemoryAccesses()) {
3551 VT = MVT::i64;
3552 } else {
3553 switch (Align & 7) {
3554 case 0:
3555 VT = MVT::i64;
3556 break;
3557 case 4:
3558 VT = MVT::i32;
3559 break;
3560 case 2:
3561 VT = MVT::i16;
3562 break;
3563 default:
3564 VT = MVT::i8;
3565 break;
3566 }
3567 }
3568
Evan Cheng80e89d72006-02-14 09:11:59 +00003569 MVT::ValueType LVT = MVT::i64;
3570 while (!TLI.isTypeLegal(LVT))
3571 LVT = (MVT::ValueType)((unsigned)LVT - 1);
3572 assert(MVT::isInteger(LVT));
Evan Cheng1db92f92006-02-14 08:22:34 +00003573
Evan Cheng80e89d72006-02-14 09:11:59 +00003574 if (VT > LVT)
3575 VT = LVT;
3576
Evan Chengdea72452006-02-14 23:05:54 +00003577 unsigned NumMemOps = 0;
Evan Cheng1db92f92006-02-14 08:22:34 +00003578 while (Size != 0) {
3579 unsigned VTSize = getSizeInBits(VT) / 8;
3580 while (VTSize > Size) {
3581 VT = (MVT::ValueType)((unsigned)VT - 1);
Evan Cheng1db92f92006-02-14 08:22:34 +00003582 VTSize >>= 1;
3583 }
Evan Cheng80e89d72006-02-14 09:11:59 +00003584 assert(MVT::isInteger(VT));
3585
3586 if (++NumMemOps > Limit)
3587 return false;
Evan Cheng1db92f92006-02-14 08:22:34 +00003588 MemOps.push_back(VT);
3589 Size -= VTSize;
3590 }
Evan Cheng80e89d72006-02-14 09:11:59 +00003591
3592 return true;
Evan Cheng1db92f92006-02-14 08:22:34 +00003593}
3594
Chris Lattner7041ee32005-01-11 05:56:49 +00003595void SelectionDAGLowering::visitMemIntrinsic(CallInst &I, unsigned Op) {
Evan Cheng1db92f92006-02-14 08:22:34 +00003596 SDOperand Op1 = getValue(I.getOperand(1));
3597 SDOperand Op2 = getValue(I.getOperand(2));
3598 SDOperand Op3 = getValue(I.getOperand(3));
3599 SDOperand Op4 = getValue(I.getOperand(4));
3600 unsigned Align = (unsigned)cast<ConstantSDNode>(Op4)->getValue();
3601 if (Align == 0) Align = 1;
3602
3603 if (ConstantSDNode *Size = dyn_cast<ConstantSDNode>(Op3)) {
3604 std::vector<MVT::ValueType> MemOps;
Evan Cheng1db92f92006-02-14 08:22:34 +00003605
3606 // Expand memset / memcpy to a series of load / store ops
3607 // if the size operand falls below a certain threshold.
Chris Lattnerbd564bf2006-08-08 02:23:42 +00003608 SmallVector<SDOperand, 8> OutChains;
Evan Cheng1db92f92006-02-14 08:22:34 +00003609 switch (Op) {
Evan Chengac940ab2006-02-14 19:45:56 +00003610 default: break; // Do nothing for now.
Evan Cheng1db92f92006-02-14 08:22:34 +00003611 case ISD::MEMSET: {
Evan Chengc4f8eee2006-02-14 20:12:38 +00003612 if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemset(),
3613 Size->getValue(), Align, TLI)) {
Evan Cheng80e89d72006-02-14 09:11:59 +00003614 unsigned NumMemOps = MemOps.size();
Evan Cheng1db92f92006-02-14 08:22:34 +00003615 unsigned Offset = 0;
3616 for (unsigned i = 0; i < NumMemOps; i++) {
3617 MVT::ValueType VT = MemOps[i];
3618 unsigned VTSize = getSizeInBits(VT) / 8;
Evan Chenga47876d2006-02-15 22:12:35 +00003619 SDOperand Value = getMemsetValue(Op2, VT, DAG);
Evan Cheng786225a2006-10-05 23:01:46 +00003620 SDOperand Store = DAG.getStore(getRoot(), Value,
Chris Lattner864635a2006-02-22 22:37:12 +00003621 getMemBasePlusOffset(Op1, Offset, DAG, TLI),
Evan Cheng8b2794a2006-10-13 21:14:26 +00003622 I.getOperand(1), Offset);
Evan Chengc080d6f2006-02-15 01:54:51 +00003623 OutChains.push_back(Store);
Evan Cheng1db92f92006-02-14 08:22:34 +00003624 Offset += VTSize;
3625 }
Evan Cheng1db92f92006-02-14 08:22:34 +00003626 }
Evan Chengc080d6f2006-02-15 01:54:51 +00003627 break;
Evan Cheng1db92f92006-02-14 08:22:34 +00003628 }
Evan Chengc080d6f2006-02-15 01:54:51 +00003629 case ISD::MEMCPY: {
3630 if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemcpy(),
3631 Size->getValue(), Align, TLI)) {
3632 unsigned NumMemOps = MemOps.size();
Evan Chengcffbb512006-02-16 23:11:42 +00003633 unsigned SrcOff = 0, DstOff = 0, SrcDelta = 0;
Evan Cheng74d0aa92006-02-15 21:59:04 +00003634 GlobalAddressSDNode *G = NULL;
3635 std::string Str;
Evan Chengcffbb512006-02-16 23:11:42 +00003636 bool CopyFromStr = false;
Evan Cheng74d0aa92006-02-15 21:59:04 +00003637
3638 if (Op2.getOpcode() == ISD::GlobalAddress)
3639 G = cast<GlobalAddressSDNode>(Op2);
3640 else if (Op2.getOpcode() == ISD::ADD &&
3641 Op2.getOperand(0).getOpcode() == ISD::GlobalAddress &&
3642 Op2.getOperand(1).getOpcode() == ISD::Constant) {
3643 G = cast<GlobalAddressSDNode>(Op2.getOperand(0));
Evan Chengcffbb512006-02-16 23:11:42 +00003644 SrcDelta = cast<ConstantSDNode>(Op2.getOperand(1))->getValue();
Evan Cheng74d0aa92006-02-15 21:59:04 +00003645 }
3646 if (G) {
3647 GlobalVariable *GV = dyn_cast<GlobalVariable>(G->getGlobal());
Evan Chengf3e486e2006-11-29 01:58:12 +00003648 if (GV && GV->isConstant()) {
Evan Cheng09371032006-03-10 23:52:03 +00003649 Str = GV->getStringValue(false);
Evan Chengcffbb512006-02-16 23:11:42 +00003650 if (!Str.empty()) {
3651 CopyFromStr = true;
3652 SrcOff += SrcDelta;
3653 }
3654 }
Evan Cheng74d0aa92006-02-15 21:59:04 +00003655 }
3656
Evan Chengc080d6f2006-02-15 01:54:51 +00003657 for (unsigned i = 0; i < NumMemOps; i++) {
3658 MVT::ValueType VT = MemOps[i];
3659 unsigned VTSize = getSizeInBits(VT) / 8;
Evan Cheng74d0aa92006-02-15 21:59:04 +00003660 SDOperand Value, Chain, Store;
3661
Evan Chengcffbb512006-02-16 23:11:42 +00003662 if (CopyFromStr) {
Evan Cheng74d0aa92006-02-15 21:59:04 +00003663 Value = getMemsetStringVal(VT, DAG, TLI, Str, SrcOff);
3664 Chain = getRoot();
3665 Store =
Evan Cheng786225a2006-10-05 23:01:46 +00003666 DAG.getStore(Chain, Value,
3667 getMemBasePlusOffset(Op1, DstOff, DAG, TLI),
Evan Cheng8b2794a2006-10-13 21:14:26 +00003668 I.getOperand(1), DstOff);
Evan Cheng74d0aa92006-02-15 21:59:04 +00003669 } else {
3670 Value = DAG.getLoad(VT, getRoot(),
3671 getMemBasePlusOffset(Op2, SrcOff, DAG, TLI),
Evan Cheng466685d2006-10-09 20:57:25 +00003672 I.getOperand(2), SrcOff);
Evan Cheng74d0aa92006-02-15 21:59:04 +00003673 Chain = Value.getValue(1);
3674 Store =
Evan Cheng786225a2006-10-05 23:01:46 +00003675 DAG.getStore(Chain, Value,
3676 getMemBasePlusOffset(Op1, DstOff, DAG, TLI),
Evan Cheng8b2794a2006-10-13 21:14:26 +00003677 I.getOperand(1), DstOff);
Evan Cheng74d0aa92006-02-15 21:59:04 +00003678 }
Evan Chengc080d6f2006-02-15 01:54:51 +00003679 OutChains.push_back(Store);
Evan Cheng74d0aa92006-02-15 21:59:04 +00003680 SrcOff += VTSize;
3681 DstOff += VTSize;
Evan Chengc080d6f2006-02-15 01:54:51 +00003682 }
3683 }
3684 break;
3685 }
3686 }
3687
3688 if (!OutChains.empty()) {
Chris Lattnerbd564bf2006-08-08 02:23:42 +00003689 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other,
3690 &OutChains[0], OutChains.size()));
Evan Chengc080d6f2006-02-15 01:54:51 +00003691 return;
Evan Cheng1db92f92006-02-14 08:22:34 +00003692 }
3693 }
3694
Chris Lattnerbd564bf2006-08-08 02:23:42 +00003695 DAG.setRoot(DAG.getNode(Op, MVT::Other, getRoot(), Op1, Op2, Op3, Op4));
Chris Lattner1c08c712005-01-07 07:47:53 +00003696}
3697
Chris Lattner7041ee32005-01-11 05:56:49 +00003698//===----------------------------------------------------------------------===//
3699// SelectionDAGISel code
3700//===----------------------------------------------------------------------===//
Chris Lattner1c08c712005-01-07 07:47:53 +00003701
3702unsigned SelectionDAGISel::MakeReg(MVT::ValueType VT) {
3703 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
3704}
3705
Chris Lattner495a0b52005-08-17 06:37:43 +00003706void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattner36b708f2005-08-18 17:35:14 +00003707 // FIXME: we only modify the CFG to split critical edges. This
3708 // updates dom and loop info.
Jim Laskeyc7c3f112006-10-16 20:52:31 +00003709 AU.addRequired<AliasAnalysis>();
Evan Cheng3cd4e502007-03-16 08:46:27 +00003710 AU.addRequired<LoopInfo>();
3711 AU.setPreservesAll();
Chris Lattner495a0b52005-08-17 06:37:43 +00003712}
Chris Lattner1c08c712005-01-07 07:47:53 +00003713
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003714
Chris Lattner90323642006-05-05 21:17:49 +00003715/// OptimizeNoopCopyExpression - We have determined that the specified cast
3716/// instruction is a noop copy (e.g. it's casting from one pointer type to
3717/// another, int->uint, or int->sbyte on PPC.
3718///
3719/// Return true if any changes are made.
3720static bool OptimizeNoopCopyExpression(CastInst *CI) {
3721 BasicBlock *DefBB = CI->getParent();
3722
3723 /// InsertedCasts - Only insert a cast in each block once.
3724 std::map<BasicBlock*, CastInst*> InsertedCasts;
3725
3726 bool MadeChange = false;
3727 for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
3728 UI != E; ) {
3729 Use &TheUse = UI.getUse();
3730 Instruction *User = cast<Instruction>(*UI);
3731
3732 // Figure out which BB this cast is used in. For PHI's this is the
3733 // appropriate predecessor block.
3734 BasicBlock *UserBB = User->getParent();
3735 if (PHINode *PN = dyn_cast<PHINode>(User)) {
3736 unsigned OpVal = UI.getOperandNo()/2;
3737 UserBB = PN->getIncomingBlock(OpVal);
3738 }
3739
3740 // Preincrement use iterator so we don't invalidate it.
3741 ++UI;
3742
3743 // If this user is in the same block as the cast, don't change the cast.
3744 if (UserBB == DefBB) continue;
3745
3746 // If we have already inserted a cast into this block, use it.
3747 CastInst *&InsertedCast = InsertedCasts[UserBB];
3748
3749 if (!InsertedCast) {
3750 BasicBlock::iterator InsertPt = UserBB->begin();
3751 while (isa<PHINode>(InsertPt)) ++InsertPt;
3752
3753 InsertedCast =
Reid Spencer7b06bd52006-12-13 00:50:17 +00003754 CastInst::create(CI->getOpcode(), CI->getOperand(0), CI->getType(), "",
3755 InsertPt);
Chris Lattner90323642006-05-05 21:17:49 +00003756 MadeChange = true;
3757 }
3758
3759 // Replace a use of the cast with a use of the new casat.
3760 TheUse = InsertedCast;
3761 }
3762
3763 // If we removed all uses, nuke the cast.
3764 if (CI->use_empty())
3765 CI->eraseFromParent();
3766
3767 return MadeChange;
3768}
3769
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003770/// InsertGEPComputeCode - Insert code into BB to compute Ptr+PtrOffset,
3771/// casting to the type of GEPI.
Chris Lattnerf0df8822006-05-06 09:10:37 +00003772static Instruction *InsertGEPComputeCode(Instruction *&V, BasicBlock *BB,
3773 Instruction *GEPI, Value *Ptr,
3774 Value *PtrOffset) {
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003775 if (V) return V; // Already computed.
3776
Reid Spencer3da59db2006-11-27 01:05:10 +00003777 // Figure out the insertion point
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003778 BasicBlock::iterator InsertPt;
3779 if (BB == GEPI->getParent()) {
Reid Spencer3da59db2006-11-27 01:05:10 +00003780 // If GEP is already inserted into BB, insert right after the GEP.
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003781 InsertPt = GEPI;
3782 ++InsertPt;
3783 } else {
3784 // Otherwise, insert at the top of BB, after any PHI nodes
3785 InsertPt = BB->begin();
3786 while (isa<PHINode>(InsertPt)) ++InsertPt;
3787 }
3788
Chris Lattnerc78b0b72005-12-08 08:00:12 +00003789 // If Ptr is itself a cast, but in some other BB, emit a copy of the cast into
3790 // BB so that there is only one value live across basic blocks (the cast
3791 // operand).
3792 if (CastInst *CI = dyn_cast<CastInst>(Ptr))
3793 if (CI->getParent() != BB && isa<PointerType>(CI->getOperand(0)->getType()))
Reid Spencer7b06bd52006-12-13 00:50:17 +00003794 Ptr = CastInst::create(CI->getOpcode(), CI->getOperand(0), CI->getType(),
3795 "", InsertPt);
Chris Lattnerc78b0b72005-12-08 08:00:12 +00003796
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003797 // Add the offset, cast it to the right type.
3798 Ptr = BinaryOperator::createAdd(Ptr, PtrOffset, "", InsertPt);
Reid Spencer3da59db2006-11-27 01:05:10 +00003799 // Ptr is an integer type, GEPI is pointer type ==> IntToPtr
3800 return V = CastInst::create(Instruction::IntToPtr, Ptr, GEPI->getType(),
3801 "", InsertPt);
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003802}
3803
Chris Lattner90323642006-05-05 21:17:49 +00003804/// ReplaceUsesOfGEPInst - Replace all uses of RepPtr with inserted code to
3805/// compute its value. The RepPtr value can be computed with Ptr+PtrOffset. One
3806/// trivial way of doing this would be to evaluate Ptr+PtrOffset in RepPtr's
3807/// block, then ReplaceAllUsesWith'ing everything. However, we would prefer to
3808/// sink PtrOffset into user blocks where doing so will likely allow us to fold
3809/// the constant add into a load or store instruction. Additionally, if a user
3810/// is a pointer-pointer cast, we look through it to find its users.
3811static void ReplaceUsesOfGEPInst(Instruction *RepPtr, Value *Ptr,
3812 Constant *PtrOffset, BasicBlock *DefBB,
3813 GetElementPtrInst *GEPI,
Chris Lattnerf0df8822006-05-06 09:10:37 +00003814 std::map<BasicBlock*,Instruction*> &InsertedExprs) {
Chris Lattner90323642006-05-05 21:17:49 +00003815 while (!RepPtr->use_empty()) {
3816 Instruction *User = cast<Instruction>(RepPtr->use_back());
Chris Lattner7e598092006-05-05 01:04:50 +00003817
Reid Spencer3da59db2006-11-27 01:05:10 +00003818 // If the user is a Pointer-Pointer cast, recurse. Only BitCast can be
3819 // used for a Pointer-Pointer cast.
3820 if (isa<BitCastInst>(User)) {
Chris Lattner90323642006-05-05 21:17:49 +00003821 ReplaceUsesOfGEPInst(User, Ptr, PtrOffset, DefBB, GEPI, InsertedExprs);
Chris Lattner7e598092006-05-05 01:04:50 +00003822
Chris Lattner90323642006-05-05 21:17:49 +00003823 // Drop the use of RepPtr. The cast is dead. Don't delete it now, else we
3824 // could invalidate an iterator.
3825 User->setOperand(0, UndefValue::get(RepPtr->getType()));
3826 continue;
Chris Lattner7e598092006-05-05 01:04:50 +00003827 }
3828
Chris Lattner90323642006-05-05 21:17:49 +00003829 // If this is a load of the pointer, or a store through the pointer, emit
3830 // the increment into the load/store block.
Chris Lattnerf0df8822006-05-06 09:10:37 +00003831 Instruction *NewVal;
Chris Lattner90323642006-05-05 21:17:49 +00003832 if (isa<LoadInst>(User) ||
3833 (isa<StoreInst>(User) && User->getOperand(0) != RepPtr)) {
3834 NewVal = InsertGEPComputeCode(InsertedExprs[User->getParent()],
3835 User->getParent(), GEPI,
3836 Ptr, PtrOffset);
3837 } else {
3838 // If this use is not foldable into the addressing mode, use a version
3839 // emitted in the GEP block.
3840 NewVal = InsertGEPComputeCode(InsertedExprs[DefBB], DefBB, GEPI,
3841 Ptr, PtrOffset);
3842 }
3843
Chris Lattnerf0df8822006-05-06 09:10:37 +00003844 if (GEPI->getType() != RepPtr->getType()) {
3845 BasicBlock::iterator IP = NewVal;
3846 ++IP;
Reid Spencer3da59db2006-11-27 01:05:10 +00003847 // NewVal must be a GEP which must be pointer type, so BitCast
3848 NewVal = new BitCastInst(NewVal, RepPtr->getType(), "", IP);
Chris Lattnerf0df8822006-05-06 09:10:37 +00003849 }
Chris Lattner90323642006-05-05 21:17:49 +00003850 User->replaceUsesOfWith(RepPtr, NewVal);
Chris Lattner7e598092006-05-05 01:04:50 +00003851 }
3852}
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003853
Chris Lattner90323642006-05-05 21:17:49 +00003854
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003855/// OptimizeGEPExpression - Since we are doing basic-block-at-a-time instruction
3856/// selection, we want to be a bit careful about some things. In particular, if
3857/// we have a GEP instruction that is used in a different block than it is
3858/// defined, the addressing expression of the GEP cannot be folded into loads or
3859/// stores that use it. In this case, decompose the GEP and move constant
3860/// indices into blocks that use it.
Chris Lattner90323642006-05-05 21:17:49 +00003861static bool OptimizeGEPExpression(GetElementPtrInst *GEPI,
Owen Andersona69571c2006-05-03 01:29:57 +00003862 const TargetData *TD) {
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003863 // If this GEP is only used inside the block it is defined in, there is no
3864 // need to rewrite it.
3865 bool isUsedOutsideDefBB = false;
3866 BasicBlock *DefBB = GEPI->getParent();
3867 for (Value::use_iterator UI = GEPI->use_begin(), E = GEPI->use_end();
3868 UI != E; ++UI) {
3869 if (cast<Instruction>(*UI)->getParent() != DefBB) {
3870 isUsedOutsideDefBB = true;
3871 break;
3872 }
3873 }
Chris Lattner90323642006-05-05 21:17:49 +00003874 if (!isUsedOutsideDefBB) return false;
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003875
3876 // If this GEP has no non-zero constant indices, there is nothing we can do,
3877 // ignore it.
3878 bool hasConstantIndex = false;
Chris Lattner90323642006-05-05 21:17:49 +00003879 bool hasVariableIndex = false;
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003880 for (GetElementPtrInst::op_iterator OI = GEPI->op_begin()+1,
3881 E = GEPI->op_end(); OI != E; ++OI) {
Chris Lattner90323642006-05-05 21:17:49 +00003882 if (ConstantInt *CI = dyn_cast<ConstantInt>(*OI)) {
Reid Spencerb83eb642006-10-20 07:07:24 +00003883 if (CI->getZExtValue()) {
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003884 hasConstantIndex = true;
3885 break;
3886 }
Chris Lattner90323642006-05-05 21:17:49 +00003887 } else {
3888 hasVariableIndex = true;
3889 }
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003890 }
Chris Lattner90323642006-05-05 21:17:49 +00003891
3892 // If this is a "GEP X, 0, 0, 0", turn this into a cast.
3893 if (!hasConstantIndex && !hasVariableIndex) {
Reid Spencer3da59db2006-11-27 01:05:10 +00003894 /// The GEP operand must be a pointer, so must its result -> BitCast
3895 Value *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
Chris Lattner90323642006-05-05 21:17:49 +00003896 GEPI->getName(), GEPI);
3897 GEPI->replaceAllUsesWith(NC);
3898 GEPI->eraseFromParent();
3899 return true;
3900 }
3901
Chris Lattner3802c252005-12-11 09:05:13 +00003902 // If this is a GEP &Alloca, 0, 0, forward subst the frame index into uses.
Chris Lattner90323642006-05-05 21:17:49 +00003903 if (!hasConstantIndex && !isa<AllocaInst>(GEPI->getOperand(0)))
3904 return false;
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003905
3906 // Otherwise, decompose the GEP instruction into multiplies and adds. Sum the
3907 // constant offset (which we now know is non-zero) and deal with it later.
3908 uint64_t ConstantOffset = 0;
Owen Andersona69571c2006-05-03 01:29:57 +00003909 const Type *UIntPtrTy = TD->getIntPtrType();
Reid Spencer3da59db2006-11-27 01:05:10 +00003910 Value *Ptr = new PtrToIntInst(GEPI->getOperand(0), UIntPtrTy, "", GEPI);
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003911 const Type *Ty = GEPI->getOperand(0)->getType();
3912
3913 for (GetElementPtrInst::op_iterator OI = GEPI->op_begin()+1,
3914 E = GEPI->op_end(); OI != E; ++OI) {
3915 Value *Idx = *OI;
3916 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
Reid Spencerb83eb642006-10-20 07:07:24 +00003917 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003918 if (Field)
Chris Lattnerb1919e22007-02-10 19:55:17 +00003919 ConstantOffset += TD->getStructLayout(StTy)->getElementOffset(Field);
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003920 Ty = StTy->getElementType(Field);
3921 } else {
3922 Ty = cast<SequentialType>(Ty)->getElementType();
3923
3924 // Handle constant subscripts.
3925 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
Reid Spencerb83eb642006-10-20 07:07:24 +00003926 if (CI->getZExtValue() == 0) continue;
Reid Spencer47857812006-12-31 05:55:36 +00003927 ConstantOffset += (int64_t)TD->getTypeSize(Ty)*CI->getSExtValue();
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003928 continue;
3929 }
3930
3931 // Ptr = Ptr + Idx * ElementSize;
3932
3933 // Cast Idx to UIntPtrTy if needed.
Reid Spencer7b06bd52006-12-13 00:50:17 +00003934 Idx = CastInst::createIntegerCast(Idx, UIntPtrTy, true/*SExt*/, "", GEPI);
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003935
Owen Andersona69571c2006-05-03 01:29:57 +00003936 uint64_t ElementSize = TD->getTypeSize(Ty);
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003937 // Mask off bits that should not be set.
3938 ElementSize &= ~0ULL >> (64-UIntPtrTy->getPrimitiveSizeInBits());
Reid Spencerb83eb642006-10-20 07:07:24 +00003939 Constant *SizeCst = ConstantInt::get(UIntPtrTy, ElementSize);
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003940
3941 // Multiply by the element size and add to the base.
3942 Idx = BinaryOperator::createMul(Idx, SizeCst, "", GEPI);
3943 Ptr = BinaryOperator::createAdd(Ptr, Idx, "", GEPI);
3944 }
3945 }
3946
3947 // Make sure that the offset fits in uintptr_t.
3948 ConstantOffset &= ~0ULL >> (64-UIntPtrTy->getPrimitiveSizeInBits());
Reid Spencerb83eb642006-10-20 07:07:24 +00003949 Constant *PtrOffset = ConstantInt::get(UIntPtrTy, ConstantOffset);
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003950
3951 // Okay, we have now emitted all of the variable index parts to the BB that
3952 // the GEP is defined in. Loop over all of the using instructions, inserting
3953 // an "add Ptr, ConstantOffset" into each block that uses it and update the
Chris Lattnerc78b0b72005-12-08 08:00:12 +00003954 // instruction to use the newly computed value, making GEPI dead. When the
3955 // user is a load or store instruction address, we emit the add into the user
3956 // block, otherwise we use a canonical version right next to the gep (these
3957 // won't be foldable as addresses, so we might as well share the computation).
3958
Chris Lattnerf0df8822006-05-06 09:10:37 +00003959 std::map<BasicBlock*,Instruction*> InsertedExprs;
Chris Lattner90323642006-05-05 21:17:49 +00003960 ReplaceUsesOfGEPInst(GEPI, Ptr, PtrOffset, DefBB, GEPI, InsertedExprs);
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003961
3962 // Finally, the GEP is dead, remove it.
3963 GEPI->eraseFromParent();
Chris Lattner90323642006-05-05 21:17:49 +00003964
3965 return true;
Chris Lattnerc88d8e92005-12-05 07:10:48 +00003966}
3967
Evan Cheng3cd4e502007-03-16 08:46:27 +00003968/// isLoopInvariantInst - Returns true if all operands of the instruction are
3969/// loop invariants in the specified loop.
3970static bool isLoopInvariantInst(Instruction *I, Loop *L) {
3971 // The instruction is loop invariant if all of its operands are loop-invariant
3972 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
3973 if (!L->isLoopInvariant(I->getOperand(i)))
3974 return false;
3975 return true;
3976}
3977
3978/// SinkInvariantGEPIndex - If a GEP instruction has a variable index that has
3979/// been hoisted out of the loop by LICM pass, sink it back into the use BB
3980/// if it can be determined that the index computation can be folded into the
3981/// addressing mode of the load / store uses.
3982static bool SinkInvariantGEPIndex(BinaryOperator *BinOp, LoopInfo *loopInfo,
3983 const TargetLowering &TLI) {
3984 if (!EnableGEPIndexSink)
3985 return false;
3986
3987 // Only look at Add / Sub for now.
3988 if (BinOp->getOpcode() != Instruction::Add &&
3989 BinOp->getOpcode() != Instruction::Sub)
3990 return false;
3991
3992 /// InsertedOps - Only insert a duplicate in each block once.
3993 std::map<BasicBlock*, BinaryOperator*> InsertedOps;
3994
3995 bool MadeChange = false;
3996 BasicBlock *DefBB = BinOp->getParent();
3997 for (Value::use_iterator UI = BinOp->use_begin(), E = BinOp->use_end();
3998 UI != E; ) {
3999 Instruction *User = cast<Instruction>(*UI);
4000
4001 // Preincrement use iterator so we don't invalidate it.
4002 ++UI;
4003
4004 // Only look for GEP use in another block.
4005 if (User->getParent() == DefBB) continue;
4006
4007 if (isa<GetElementPtrInst>(User)) {
4008 BasicBlock *UserBB = User->getParent();
4009 Loop *L = loopInfo->getLoopFor(UserBB);
4010
4011 // Only sink if expression is a loop invariant in the use BB.
Evan Cheng9f5ead92007-03-16 17:50:20 +00004012 if (L && isLoopInvariantInst(BinOp, L) && !User->use_empty()) {
Evan Cheng3cd4e502007-03-16 08:46:27 +00004013 const Type *UseTy = NULL;
4014 // FIXME: We are assuming all the uses of the GEP will have the
4015 // same type.
4016 Instruction *GEPUser = cast<Instruction>(*User->use_begin());
4017 if (LoadInst *Load = dyn_cast<LoadInst>(GEPUser))
4018 UseTy = Load->getType();
4019 else if (StoreInst *Store = dyn_cast<StoreInst>(GEPUser))
4020 UseTy = Store->getOperand(0)->getType();
4021
4022 // Check if it is possible to fold the expression to address mode.
4023 if (UseTy &&
4024 TLI.isLegalAddressExpression(Instruction::Add, BinOp->getOperand(0),
4025 BinOp->getOperand(1), UseTy)) {
4026 // Sink it into user block.
4027 BinaryOperator *&InsertedOp = InsertedOps[UserBB];
4028 if (!InsertedOp) {
4029 BasicBlock::iterator InsertPt = UserBB->begin();
4030 while (isa<PHINode>(InsertPt)) ++InsertPt;
4031
4032 InsertedOp =
4033 BinaryOperator::create(BinOp->getOpcode(), BinOp->getOperand(0),
4034 BinOp->getOperand(1), "", InsertPt);
4035 }
4036
4037 User->replaceUsesOfWith(BinOp, InsertedOp);
4038 MadeChange = true;
4039 }
4040 }
4041 }
4042 }
4043
4044 if (BinOp->use_empty())
4045 BinOp->eraseFromParent();
4046
4047 return MadeChange;
4048}
4049
Chris Lattnerbad7f482006-10-28 19:22:10 +00004050
4051/// SplitEdgeNicely - Split the critical edge from TI to it's specified
4052/// successor if it will improve codegen. We only do this if the successor has
4053/// phi nodes (otherwise critical edges are ok). If there is already another
4054/// predecessor of the succ that is empty (and thus has no phi nodes), use it
4055/// instead of introducing a new block.
4056static void SplitEdgeNicely(TerminatorInst *TI, unsigned SuccNum, Pass *P) {
4057 BasicBlock *TIBB = TI->getParent();
4058 BasicBlock *Dest = TI->getSuccessor(SuccNum);
4059 assert(isa<PHINode>(Dest->begin()) &&
4060 "This should only be called if Dest has a PHI!");
4061
4062 /// TIPHIValues - This array is lazily computed to determine the values of
4063 /// PHIs in Dest that TI would provide.
4064 std::vector<Value*> TIPHIValues;
4065
4066 // Check to see if Dest has any blocks that can be used as a split edge for
4067 // this terminator.
4068 for (pred_iterator PI = pred_begin(Dest), E = pred_end(Dest); PI != E; ++PI) {
4069 BasicBlock *Pred = *PI;
4070 // To be usable, the pred has to end with an uncond branch to the dest.
4071 BranchInst *PredBr = dyn_cast<BranchInst>(Pred->getTerminator());
4072 if (!PredBr || !PredBr->isUnconditional() ||
4073 // Must be empty other than the branch.
4074 &Pred->front() != PredBr)
4075 continue;
4076
4077 // Finally, since we know that Dest has phi nodes in it, we have to make
4078 // sure that jumping to Pred will have the same affect as going to Dest in
4079 // terms of PHI values.
4080 PHINode *PN;
4081 unsigned PHINo = 0;
4082 bool FoundMatch = true;
4083 for (BasicBlock::iterator I = Dest->begin();
4084 (PN = dyn_cast<PHINode>(I)); ++I, ++PHINo) {
4085 if (PHINo == TIPHIValues.size())
4086 TIPHIValues.push_back(PN->getIncomingValueForBlock(TIBB));
4087
4088 // If the PHI entry doesn't work, we can't use this pred.
4089 if (TIPHIValues[PHINo] != PN->getIncomingValueForBlock(Pred)) {
4090 FoundMatch = false;
4091 break;
4092 }
4093 }
4094
4095 // If we found a workable predecessor, change TI to branch to Succ.
4096 if (FoundMatch) {
4097 Dest->removePredecessor(TIBB);
4098 TI->setSuccessor(SuccNum, Pred);
4099 return;
4100 }
4101 }
4102
4103 SplitCriticalEdge(TI, SuccNum, P, true);
4104}
4105
4106
Chris Lattner1c08c712005-01-07 07:47:53 +00004107bool SelectionDAGISel::runOnFunction(Function &Fn) {
4108 MachineFunction &MF = MachineFunction::construct(&Fn, TLI.getTargetMachine());
4109 RegMap = MF.getSSARegMap();
Bill Wendling832171c2006-12-07 20:04:42 +00004110 DOUT << "\n\n\n=== " << Fn.getName() << "\n";
Chris Lattner1c08c712005-01-07 07:47:53 +00004111
Evan Cheng3cd4e502007-03-16 08:46:27 +00004112 LoopInfo *loopInfo = &getAnalysis<LoopInfo>();
4113
Chris Lattner47e32e62006-10-28 17:04:37 +00004114 // First, split all critical edges.
Chris Lattnerc88d8e92005-12-05 07:10:48 +00004115 //
Chris Lattner7e598092006-05-05 01:04:50 +00004116 // In this pass we also look for GEP and cast instructions that are used
4117 // across basic blocks and rewrite them to improve basic-block-at-a-time
4118 // selection.
4119 //
Chris Lattner90323642006-05-05 21:17:49 +00004120 bool MadeChange = true;
4121 while (MadeChange) {
4122 MadeChange = false;
Evan Cheng15699fc2007-02-10 01:08:18 +00004123 for (Function::iterator FNI = Fn.begin(), E = Fn.end(); FNI != E; ++FNI) {
Chris Lattnerbad7f482006-10-28 19:22:10 +00004124 // Split all critical edges where the dest block has a PHI.
Evan Cheng15699fc2007-02-10 01:08:18 +00004125 TerminatorInst *BBTI = FNI->getTerminator();
Chris Lattner47e32e62006-10-28 17:04:37 +00004126 if (BBTI->getNumSuccessors() > 1) {
4127 for (unsigned i = 0, e = BBTI->getNumSuccessors(); i != e; ++i)
Chris Lattnerbad7f482006-10-28 19:22:10 +00004128 if (isa<PHINode>(BBTI->getSuccessor(i)->begin()) &&
4129 isCriticalEdge(BBTI, i, true))
4130 SplitEdgeNicely(BBTI, i, this);
Chris Lattner47e32e62006-10-28 17:04:37 +00004131 }
4132
Chris Lattnerc88d8e92005-12-05 07:10:48 +00004133
Evan Cheng15699fc2007-02-10 01:08:18 +00004134 for (BasicBlock::iterator BBI = FNI->begin(), E = FNI->end(); BBI != E; ) {
Chris Lattner7e598092006-05-05 01:04:50 +00004135 Instruction *I = BBI++;
Chris Lattner3f7927c2006-11-29 01:12:32 +00004136
4137 if (CallInst *CI = dyn_cast<CallInst>(I)) {
4138 // If we found an inline asm expession, and if the target knows how to
4139 // lower it to normal LLVM code, do so now.
4140 if (isa<InlineAsm>(CI->getCalledValue()))
4141 if (const TargetAsmInfo *TAI =
4142 TLI.getTargetMachine().getTargetAsmInfo()) {
4143 if (TAI->ExpandInlineAsm(CI))
Evan Cheng15699fc2007-02-10 01:08:18 +00004144 BBI = FNI->begin();
Chris Lattner3f7927c2006-11-29 01:12:32 +00004145 }
4146 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
Chris Lattner90323642006-05-05 21:17:49 +00004147 MadeChange |= OptimizeGEPExpression(GEPI, TLI.getTargetData());
Chris Lattner7e598092006-05-05 01:04:50 +00004148 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
Chris Lattnerc970f062006-09-13 06:02:42 +00004149 // If the source of the cast is a constant, then this should have
4150 // already been constant folded. The only reason NOT to constant fold
4151 // it is if something (e.g. LSR) was careful to place the constant
4152 // evaluation in a block other than then one that uses it (e.g. to hoist
4153 // the address of globals out of a loop). If this is the case, we don't
4154 // want to forward-subst the cast.
4155 if (isa<Constant>(CI->getOperand(0)))
4156 continue;
4157
Chris Lattner7e598092006-05-05 01:04:50 +00004158 // If this is a noop copy, sink it into user blocks to reduce the number
4159 // of virtual registers that must be created and coallesced.
4160 MVT::ValueType SrcVT = TLI.getValueType(CI->getOperand(0)->getType());
4161 MVT::ValueType DstVT = TLI.getValueType(CI->getType());
4162
4163 // This is an fp<->int conversion?
4164 if (MVT::isInteger(SrcVT) != MVT::isInteger(DstVT))
4165 continue;
4166
4167 // If this is an extension, it will be a zero or sign extension, which
4168 // isn't a noop.
4169 if (SrcVT < DstVT) continue;
4170
4171 // If these values will be promoted, find out what they will be promoted
4172 // to. This helps us consider truncates on PPC as noop copies when they
4173 // are.
4174 if (TLI.getTypeAction(SrcVT) == TargetLowering::Promote)
4175 SrcVT = TLI.getTypeToTransformTo(SrcVT);
4176 if (TLI.getTypeAction(DstVT) == TargetLowering::Promote)
4177 DstVT = TLI.getTypeToTransformTo(DstVT);
4178
4179 // If, after promotion, these are the same types, this is a noop copy.
4180 if (SrcVT == DstVT)
Chris Lattner90323642006-05-05 21:17:49 +00004181 MadeChange |= OptimizeNoopCopyExpression(CI);
Evan Cheng3cd4e502007-03-16 08:46:27 +00004182 } else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(I)) {
4183 MadeChange |= SinkInvariantGEPIndex(BinOp, loopInfo, TLI);
Chris Lattner7e598092006-05-05 01:04:50 +00004184 }
4185 }
Chris Lattner36b708f2005-08-18 17:35:14 +00004186 }
Chris Lattner90323642006-05-05 21:17:49 +00004187 }
Chris Lattnerc9ea6fd2005-11-09 19:44:01 +00004188
Chris Lattner1c08c712005-01-07 07:47:53 +00004189 FunctionLoweringInfo FuncInfo(TLI, Fn, MF);
4190
4191 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
4192 SelectBasicBlock(I, MF, FuncInfo);
Misha Brukmanedf128a2005-04-21 22:36:52 +00004193
Evan Chengad2070c2007-02-10 02:43:39 +00004194 // Add function live-ins to entry block live-in set.
4195 BasicBlock *EntryBB = &Fn.getEntryBlock();
4196 BB = FuncInfo.MBBMap[EntryBB];
4197 if (!MF.livein_empty())
4198 for (MachineFunction::livein_iterator I = MF.livein_begin(),
4199 E = MF.livein_end(); I != E; ++I)
4200 BB->addLiveIn(I->first);
4201
Chris Lattner1c08c712005-01-07 07:47:53 +00004202 return true;
4203}
4204
Chris Lattner571e4342006-10-27 21:36:01 +00004205SDOperand SelectionDAGLowering::CopyValueToVirtualRegister(Value *V,
4206 unsigned Reg) {
4207 SDOperand Op = getValue(V);
Chris Lattner18c2f132005-01-13 20:50:02 +00004208 assert((Op.getOpcode() != ISD::CopyFromReg ||
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00004209 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
Chris Lattner18c2f132005-01-13 20:50:02 +00004210 "Copy from a reg to the same reg!");
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00004211
4212 // If this type is not legal, we must make sure to not create an invalid
4213 // register use.
4214 MVT::ValueType SrcVT = Op.getValueType();
4215 MVT::ValueType DestVT = TLI.getTypeToTransformTo(SrcVT);
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00004216 if (SrcVT == DestVT) {
Chris Lattner571e4342006-10-27 21:36:01 +00004217 return DAG.getCopyToReg(getRoot(), Reg, Op);
Chris Lattner1c6191f2006-03-21 19:20:37 +00004218 } else if (SrcVT == MVT::Vector) {
Chris Lattner70c2a612006-03-31 02:06:56 +00004219 // Handle copies from generic vectors to registers.
4220 MVT::ValueType PTyElementVT, PTyLegalElementVT;
Reid Spencer9d6565a2007-02-15 02:26:10 +00004221 unsigned NE = TLI.getVectorTypeBreakdown(cast<VectorType>(V->getType()),
Chris Lattner70c2a612006-03-31 02:06:56 +00004222 PTyElementVT, PTyLegalElementVT);
Chris Lattner1c6191f2006-03-21 19:20:37 +00004223
Chris Lattner70c2a612006-03-31 02:06:56 +00004224 // Insert a VBIT_CONVERT of the input vector to a "N x PTyElementVT"
4225 // MVT::Vector type.
4226 Op = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, Op,
4227 DAG.getConstant(NE, MVT::i32),
4228 DAG.getValueType(PTyElementVT));
Chris Lattner1c6191f2006-03-21 19:20:37 +00004229
Chris Lattner70c2a612006-03-31 02:06:56 +00004230 // Loop over all of the elements of the resultant vector,
4231 // VEXTRACT_VECTOR_ELT'ing them, converting them to PTyLegalElementVT, then
4232 // copying them into output registers.
Chris Lattnerbd564bf2006-08-08 02:23:42 +00004233 SmallVector<SDOperand, 8> OutChains;
Chris Lattner571e4342006-10-27 21:36:01 +00004234 SDOperand Root = getRoot();
Chris Lattner70c2a612006-03-31 02:06:56 +00004235 for (unsigned i = 0; i != NE; ++i) {
4236 SDOperand Elt = DAG.getNode(ISD::VEXTRACT_VECTOR_ELT, PTyElementVT,
Evan Chenga8441262006-06-15 08:11:54 +00004237 Op, DAG.getConstant(i, TLI.getPointerTy()));
Chris Lattner70c2a612006-03-31 02:06:56 +00004238 if (PTyElementVT == PTyLegalElementVT) {
4239 // Elements are legal.
4240 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Elt));
4241 } else if (PTyLegalElementVT > PTyElementVT) {
4242 // Elements are promoted.
4243 if (MVT::isFloatingPoint(PTyLegalElementVT))
4244 Elt = DAG.getNode(ISD::FP_EXTEND, PTyLegalElementVT, Elt);
4245 else
4246 Elt = DAG.getNode(ISD::ANY_EXTEND, PTyLegalElementVT, Elt);
4247 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Elt));
4248 } else {
4249 // Elements are expanded.
4250 // The src value is expanded into multiple registers.
4251 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, PTyLegalElementVT,
Evan Chenga8441262006-06-15 08:11:54 +00004252 Elt, DAG.getConstant(0, TLI.getPointerTy()));
Chris Lattner70c2a612006-03-31 02:06:56 +00004253 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, PTyLegalElementVT,
Evan Chenga8441262006-06-15 08:11:54 +00004254 Elt, DAG.getConstant(1, TLI.getPointerTy()));
Chris Lattner70c2a612006-03-31 02:06:56 +00004255 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Lo));
4256 OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Hi));
4257 }
Chris Lattner1c6191f2006-03-21 19:20:37 +00004258 }
Chris Lattnerbd564bf2006-08-08 02:23:42 +00004259 return DAG.getNode(ISD::TokenFactor, MVT::Other,
4260 &OutChains[0], OutChains.size());
Evan Cheng9f877882006-12-13 20:57:08 +00004261 } else if (TLI.getTypeAction(SrcVT) == TargetLowering::Promote) {
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00004262 // The src value is promoted to the register.
Chris Lattnerfae59b92005-08-17 06:06:25 +00004263 if (MVT::isFloatingPoint(SrcVT))
4264 Op = DAG.getNode(ISD::FP_EXTEND, DestVT, Op);
4265 else
Chris Lattnerfab08872005-09-02 00:19:37 +00004266 Op = DAG.getNode(ISD::ANY_EXTEND, DestVT, Op);
Chris Lattner571e4342006-10-27 21:36:01 +00004267 return DAG.getCopyToReg(getRoot(), Reg, Op);
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00004268 } else {
Evan Cheng9f877882006-12-13 20:57:08 +00004269 DestVT = TLI.getTypeToExpandTo(SrcVT);
4270 unsigned NumVals = TLI.getNumElements(SrcVT);
4271 if (NumVals == 1)
4272 return DAG.getCopyToReg(getRoot(), Reg,
4273 DAG.getNode(ISD::BIT_CONVERT, DestVT, Op));
4274 assert(NumVals == 2 && "1 to 4 (and more) expansion not implemented!");
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00004275 // The src value is expanded into multiple registers.
4276 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
Evan Chenga8441262006-06-15 08:11:54 +00004277 Op, DAG.getConstant(0, TLI.getPointerTy()));
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00004278 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
Evan Chenga8441262006-06-15 08:11:54 +00004279 Op, DAG.getConstant(1, TLI.getPointerTy()));
Chris Lattner571e4342006-10-27 21:36:01 +00004280 Op = DAG.getCopyToReg(getRoot(), Reg, Lo);
Chris Lattnerd5d0f9b2005-08-16 21:55:35 +00004281 return DAG.getCopyToReg(Op, Reg+1, Hi);
4282 }
Chris Lattner1c08c712005-01-07 07:47:53 +00004283}
4284
Chris Lattner068a81e2005-01-17 17:15:02 +00004285void SelectionDAGISel::
Evan Cheng15699fc2007-02-10 01:08:18 +00004286LowerArguments(BasicBlock *LLVMBB, SelectionDAGLowering &SDL,
Chris Lattner068a81e2005-01-17 17:15:02 +00004287 std::vector<SDOperand> &UnorderedChains) {
4288 // If this is the entry block, emit arguments.
Evan Cheng15699fc2007-02-10 01:08:18 +00004289 Function &F = *LLVMBB->getParent();
Chris Lattner0afa8e32005-01-17 17:55:19 +00004290 FunctionLoweringInfo &FuncInfo = SDL.FuncInfo;
Chris Lattnerbf209482005-10-30 19:42:35 +00004291 SDOperand OldRoot = SDL.DAG.getRoot();
4292 std::vector<SDOperand> Args = TLI.LowerArguments(F, SDL.DAG);
Chris Lattner068a81e2005-01-17 17:15:02 +00004293
Chris Lattnerbf209482005-10-30 19:42:35 +00004294 unsigned a = 0;
4295 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
4296 AI != E; ++AI, ++a)
4297 if (!AI->use_empty()) {
4298 SDL.setValue(AI, Args[a]);
Evan Chengf7179bb2006-04-27 08:29:42 +00004299
Chris Lattnerbf209482005-10-30 19:42:35 +00004300 // If this argument is live outside of the entry block, insert a copy from
4301 // whereever we got it to the vreg that other BB's will reference it as.
Chris Lattner251db182007-02-25 18:40:32 +00004302 DenseMap<const Value*, unsigned>::iterator VMI=FuncInfo.ValueMap.find(AI);
4303 if (VMI != FuncInfo.ValueMap.end()) {
4304 SDOperand Copy = SDL.CopyValueToVirtualRegister(AI, VMI->second);
Chris Lattnerbf209482005-10-30 19:42:35 +00004305 UnorderedChains.push_back(Copy);
4306 }
Chris Lattner0afa8e32005-01-17 17:55:19 +00004307 }
Chris Lattnerbf209482005-10-30 19:42:35 +00004308
Chris Lattnerbf209482005-10-30 19:42:35 +00004309 // Finally, if the target has anything special to do, allow it to do so.
Chris Lattner96645412006-05-16 06:10:58 +00004310 // FIXME: this should insert code into the DAG!
Chris Lattnerbf209482005-10-30 19:42:35 +00004311 EmitFunctionEntryCode(F, SDL.DAG.getMachineFunction());
Chris Lattner068a81e2005-01-17 17:15:02 +00004312}
4313
Chris Lattner1c08c712005-01-07 07:47:53 +00004314void SelectionDAGISel::BuildSelectionDAG(SelectionDAG &DAG, BasicBlock *LLVMBB,
4315 std::vector<std::pair<MachineInstr*, unsigned> > &PHINodesToUpdate,
Nate Begemanf15485a2006-03-27 01:32:24 +00004316 FunctionLoweringInfo &FuncInfo) {
Chris Lattner1c08c712005-01-07 07:47:53 +00004317 SelectionDAGLowering SDL(DAG, TLI, FuncInfo);
Chris Lattnerddb870b2005-01-13 17:59:43 +00004318
4319 std::vector<SDOperand> UnorderedChains;
Misha Brukmanedf128a2005-04-21 22:36:52 +00004320
Chris Lattnerbf209482005-10-30 19:42:35 +00004321 // Lower any arguments needed in this block if this is the entry block.
4322 if (LLVMBB == &LLVMBB->getParent()->front())
4323 LowerArguments(LLVMBB, SDL, UnorderedChains);
Chris Lattner1c08c712005-01-07 07:47:53 +00004324
4325 BB = FuncInfo.MBBMap[LLVMBB];
4326 SDL.setCurrentBasicBlock(BB);
4327
4328 // Lower all of the non-terminator instructions.
4329 for (BasicBlock::iterator I = LLVMBB->begin(), E = --LLVMBB->end();
4330 I != E; ++I)
4331 SDL.visit(*I);
Jim Laskey183f47f2007-02-25 21:43:59 +00004332
4333 // Lower call part of invoke.
4334 InvokeInst *Invoke = dyn_cast<InvokeInst>(LLVMBB->getTerminator());
4335 if (Invoke) SDL.visitInvoke(*Invoke, false);
Nate Begemanf15485a2006-03-27 01:32:24 +00004336
Chris Lattner1c08c712005-01-07 07:47:53 +00004337 // Ensure that all instructions which are used outside of their defining
4338 // blocks are available as virtual registers.
4339 for (BasicBlock::iterator I = LLVMBB->begin(), E = LLVMBB->end(); I != E;++I)
Chris Lattnerf1fdaca2005-01-11 22:03:46 +00004340 if (!I->use_empty() && !isa<PHINode>(I)) {
Chris Lattner9f24ad72007-02-04 01:35:11 +00004341 DenseMap<const Value*, unsigned>::iterator VMI =FuncInfo.ValueMap.find(I);
Chris Lattner1c08c712005-01-07 07:47:53 +00004342 if (VMI != FuncInfo.ValueMap.end())
Chris Lattnerddb870b2005-01-13 17:59:43 +00004343 UnorderedChains.push_back(
Chris Lattner571e4342006-10-27 21:36:01 +00004344 SDL.CopyValueToVirtualRegister(I, VMI->second));
Chris Lattner1c08c712005-01-07 07:47:53 +00004345 }
4346
4347 // Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
4348 // ensure constants are generated when needed. Remember the virtual registers
4349 // that need to be added to the Machine PHI nodes as input. We cannot just
4350 // directly add them, because expansion might result in multiple MBB's for one
4351 // BB. As such, the start of the BB might correspond to a different MBB than
4352 // the end.
Misha Brukmanedf128a2005-04-21 22:36:52 +00004353 //
Chris Lattner8c494ab2006-10-27 23:50:33 +00004354 TerminatorInst *TI = LLVMBB->getTerminator();
Chris Lattner1c08c712005-01-07 07:47:53 +00004355
4356 // Emit constants only once even if used by multiple PHI nodes.
4357 std::map<Constant*, unsigned> ConstantsOut;
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004358
Chris Lattner8c494ab2006-10-27 23:50:33 +00004359 // Vector bool would be better, but vector<bool> is really slow.
4360 std::vector<unsigned char> SuccsHandled;
4361 if (TI->getNumSuccessors())
4362 SuccsHandled.resize(BB->getParent()->getNumBlockIDs());
4363
Chris Lattner1c08c712005-01-07 07:47:53 +00004364 // Check successor nodes PHI nodes that expect a constant to be available from
4365 // this block.
Chris Lattner1c08c712005-01-07 07:47:53 +00004366 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
4367 BasicBlock *SuccBB = TI->getSuccessor(succ);
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004368 if (!isa<PHINode>(SuccBB->begin())) continue;
Chris Lattner8c494ab2006-10-27 23:50:33 +00004369 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004370
Chris Lattner8c494ab2006-10-27 23:50:33 +00004371 // If this terminator has multiple identical successors (common for
4372 // switches), only handle each succ once.
4373 unsigned SuccMBBNo = SuccMBB->getNumber();
4374 if (SuccsHandled[SuccMBBNo]) continue;
4375 SuccsHandled[SuccMBBNo] = true;
4376
4377 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
Chris Lattner1c08c712005-01-07 07:47:53 +00004378 PHINode *PN;
4379
4380 // At this point we know that there is a 1-1 correspondence between LLVM PHI
4381 // nodes and Machine PHI nodes, but the incoming operands have not been
4382 // emitted yet.
4383 for (BasicBlock::iterator I = SuccBB->begin();
Chris Lattner8c494ab2006-10-27 23:50:33 +00004384 (PN = dyn_cast<PHINode>(I)); ++I) {
4385 // Ignore dead phi's.
4386 if (PN->use_empty()) continue;
4387
4388 unsigned Reg;
4389 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
Chris Lattner3f7927c2006-11-29 01:12:32 +00004390
Chris Lattner8c494ab2006-10-27 23:50:33 +00004391 if (Constant *C = dyn_cast<Constant>(PHIOp)) {
4392 unsigned &RegOut = ConstantsOut[C];
4393 if (RegOut == 0) {
4394 RegOut = FuncInfo.CreateRegForValue(C);
4395 UnorderedChains.push_back(
4396 SDL.CopyValueToVirtualRegister(C, RegOut));
Chris Lattner1c08c712005-01-07 07:47:53 +00004397 }
Chris Lattner8c494ab2006-10-27 23:50:33 +00004398 Reg = RegOut;
4399 } else {
4400 Reg = FuncInfo.ValueMap[PHIOp];
4401 if (Reg == 0) {
4402 assert(isa<AllocaInst>(PHIOp) &&
4403 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
4404 "Didn't codegen value into a register!??");
4405 Reg = FuncInfo.CreateRegForValue(PHIOp);
4406 UnorderedChains.push_back(
4407 SDL.CopyValueToVirtualRegister(PHIOp, Reg));
Chris Lattner7e021512006-03-31 02:12:18 +00004408 }
Chris Lattner1c08c712005-01-07 07:47:53 +00004409 }
Chris Lattner8c494ab2006-10-27 23:50:33 +00004410
4411 // Remember that this register needs to added to the machine PHI node as
4412 // the input for this MBB.
4413 MVT::ValueType VT = TLI.getValueType(PN->getType());
4414 unsigned NumElements;
4415 if (VT != MVT::Vector)
4416 NumElements = TLI.getNumElements(VT);
4417 else {
4418 MVT::ValueType VT1,VT2;
4419 NumElements =
Reid Spencer9d6565a2007-02-15 02:26:10 +00004420 TLI.getVectorTypeBreakdown(cast<VectorType>(PN->getType()),
Chris Lattner8c494ab2006-10-27 23:50:33 +00004421 VT1, VT2);
4422 }
4423 for (unsigned i = 0, e = NumElements; i != e; ++i)
4424 PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
4425 }
Chris Lattner1c08c712005-01-07 07:47:53 +00004426 }
4427 ConstantsOut.clear();
4428
Chris Lattnerddb870b2005-01-13 17:59:43 +00004429 // Turn all of the unordered chains into one factored node.
Chris Lattner5a6c6d92005-01-13 19:53:14 +00004430 if (!UnorderedChains.empty()) {
Chris Lattner7436b572005-11-09 05:03:03 +00004431 SDOperand Root = SDL.getRoot();
4432 if (Root.getOpcode() != ISD::EntryToken) {
4433 unsigned i = 0, e = UnorderedChains.size();
4434 for (; i != e; ++i) {
4435 assert(UnorderedChains[i].Val->getNumOperands() > 1);
4436 if (UnorderedChains[i].Val->getOperand(0) == Root)
4437 break; // Don't add the root if we already indirectly depend on it.
4438 }
4439
4440 if (i == e)
4441 UnorderedChains.push_back(Root);
4442 }
Chris Lattnerbd564bf2006-08-08 02:23:42 +00004443 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other,
4444 &UnorderedChains[0], UnorderedChains.size()));
Chris Lattnerddb870b2005-01-13 17:59:43 +00004445 }
4446
Chris Lattner1c08c712005-01-07 07:47:53 +00004447 // Lower the terminator after the copies are emitted.
Jim Laskey183f47f2007-02-25 21:43:59 +00004448 if (Invoke) {
4449 // Just the branch part of invoke.
4450 SDL.visitInvoke(*Invoke, true);
4451 } else {
4452 SDL.visit(*LLVMBB->getTerminator());
4453 }
Chris Lattnera651cf62005-01-17 19:43:36 +00004454
Nate Begemanf15485a2006-03-27 01:32:24 +00004455 // Copy over any CaseBlock records that may now exist due to SwitchInst
Nate Begeman37efe672006-04-22 18:53:45 +00004456 // lowering, as well as any jump table information.
Nate Begemanf15485a2006-03-27 01:32:24 +00004457 SwitchCases.clear();
4458 SwitchCases = SDL.SwitchCases;
Nate Begeman37efe672006-04-22 18:53:45 +00004459 JT = SDL.JT;
Nate Begemanf15485a2006-03-27 01:32:24 +00004460
Chris Lattnera651cf62005-01-17 19:43:36 +00004461 // Make sure the root of the DAG is up-to-date.
4462 DAG.setRoot(SDL.getRoot());
Chris Lattner1c08c712005-01-07 07:47:53 +00004463}
4464
Nate Begemanf15485a2006-03-27 01:32:24 +00004465void SelectionDAGISel::CodeGenAndEmitDAG(SelectionDAG &DAG) {
Jim Laskeyc7c3f112006-10-16 20:52:31 +00004466 // Get alias analysis for load/store combining.
4467 AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
4468
Chris Lattneraf21d552005-10-10 16:47:10 +00004469 // Run the DAG combiner in pre-legalize mode.
Jim Laskeyc7c3f112006-10-16 20:52:31 +00004470 DAG.Combine(false, AA);
Nate Begeman2300f552005-09-07 00:15:36 +00004471
Bill Wendling832171c2006-12-07 20:04:42 +00004472 DOUT << "Lowered selection DAG:\n";
Chris Lattner1c08c712005-01-07 07:47:53 +00004473 DEBUG(DAG.dump());
Nate Begemanf15485a2006-03-27 01:32:24 +00004474
Chris Lattner1c08c712005-01-07 07:47:53 +00004475 // Second step, hack on the DAG until it only uses operations and types that
4476 // the target supports.
Chris Lattnerac9dc082005-01-23 04:36:26 +00004477 DAG.Legalize();
Nate Begemanf15485a2006-03-27 01:32:24 +00004478
Bill Wendling832171c2006-12-07 20:04:42 +00004479 DOUT << "Legalized selection DAG:\n";
Chris Lattner1c08c712005-01-07 07:47:53 +00004480 DEBUG(DAG.dump());
Nate Begemanf15485a2006-03-27 01:32:24 +00004481
Chris Lattneraf21d552005-10-10 16:47:10 +00004482 // Run the DAG combiner in post-legalize mode.
Jim Laskeyc7c3f112006-10-16 20:52:31 +00004483 DAG.Combine(true, AA);
Nate Begeman2300f552005-09-07 00:15:36 +00004484
Evan Chenga9c20912006-01-21 02:32:06 +00004485 if (ViewISelDAGs) DAG.viewGraph();
Evan Cheng552c4a82006-04-28 02:09:19 +00004486
Chris Lattnera33ef482005-03-30 01:10:47 +00004487 // Third, instruction select all of the operations to machine code, adding the
4488 // code to the MachineBasicBlock.
Chris Lattner1c08c712005-01-07 07:47:53 +00004489 InstructionSelectBasicBlock(DAG);
Nate Begemanf15485a2006-03-27 01:32:24 +00004490
Bill Wendling832171c2006-12-07 20:04:42 +00004491 DOUT << "Selected machine code:\n";
Chris Lattner1c08c712005-01-07 07:47:53 +00004492 DEBUG(BB->dump());
Nate Begemanf15485a2006-03-27 01:32:24 +00004493}
Chris Lattner1c08c712005-01-07 07:47:53 +00004494
Nate Begemanf15485a2006-03-27 01:32:24 +00004495void SelectionDAGISel::SelectBasicBlock(BasicBlock *LLVMBB, MachineFunction &MF,
4496 FunctionLoweringInfo &FuncInfo) {
4497 std::vector<std::pair<MachineInstr*, unsigned> > PHINodesToUpdate;
4498 {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00004499 SelectionDAG DAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
Nate Begemanf15485a2006-03-27 01:32:24 +00004500 CurDAG = &DAG;
4501
4502 // First step, lower LLVM code to some DAG. This DAG may use operations and
4503 // types that are not supported by the target.
4504 BuildSelectionDAG(DAG, LLVMBB, PHINodesToUpdate, FuncInfo);
4505
4506 // Second step, emit the lowered DAG as machine code.
4507 CodeGenAndEmitDAG(DAG);
4508 }
4509
Chris Lattnera33ef482005-03-30 01:10:47 +00004510 // Next, now that we know what the last MBB the LLVM BB expanded is, update
Chris Lattner1c08c712005-01-07 07:47:53 +00004511 // PHI nodes in successors.
Nate Begeman37efe672006-04-22 18:53:45 +00004512 if (SwitchCases.empty() && JT.Reg == 0) {
Nate Begemanf15485a2006-03-27 01:32:24 +00004513 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
4514 MachineInstr *PHI = PHINodesToUpdate[i].first;
4515 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
4516 "This is not a machine PHI node that we are updating!");
Chris Lattner09e46062006-09-05 02:31:13 +00004517 PHI->addRegOperand(PHINodesToUpdate[i].second, false);
Nate Begemanf15485a2006-03-27 01:32:24 +00004518 PHI->addMachineBasicBlockOperand(BB);
4519 }
4520 return;
Chris Lattner1c08c712005-01-07 07:47:53 +00004521 }
Nate Begemanf15485a2006-03-27 01:32:24 +00004522
Nate Begeman9453eea2006-04-23 06:26:20 +00004523 // If the JumpTable record is filled in, then we need to emit a jump table.
4524 // Updating the PHI nodes is tricky in this case, since we need to determine
4525 // whether the PHI is a successor of the range check MBB or the jump table MBB
Nate Begeman37efe672006-04-22 18:53:45 +00004526 if (JT.Reg) {
4527 assert(SwitchCases.empty() && "Cannot have jump table and lowered switch");
Jim Laskey44c3b9f2007-01-26 21:22:28 +00004528 SelectionDAG SDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
Nate Begeman37efe672006-04-22 18:53:45 +00004529 CurDAG = &SDAG;
4530 SelectionDAGLowering SDL(SDAG, TLI, FuncInfo);
Nate Begeman9453eea2006-04-23 06:26:20 +00004531 MachineBasicBlock *RangeBB = BB;
Nate Begeman37efe672006-04-22 18:53:45 +00004532 // Set the current basic block to the mbb we wish to insert the code into
4533 BB = JT.MBB;
4534 SDL.setCurrentBasicBlock(BB);
4535 // Emit the code
4536 SDL.visitJumpTable(JT);
4537 SDAG.setRoot(SDL.getRoot());
4538 CodeGenAndEmitDAG(SDAG);
4539 // Update PHI Nodes
4540 for (unsigned pi = 0, pe = PHINodesToUpdate.size(); pi != pe; ++pi) {
4541 MachineInstr *PHI = PHINodesToUpdate[pi].first;
4542 MachineBasicBlock *PHIBB = PHI->getParent();
4543 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
4544 "This is not a machine PHI node that we are updating!");
Nate Begemanf4360a42006-05-03 03:48:02 +00004545 if (PHIBB == JT.Default) {
Chris Lattner09e46062006-09-05 02:31:13 +00004546 PHI->addRegOperand(PHINodesToUpdate[pi].second, false);
Nate Begemanf4360a42006-05-03 03:48:02 +00004547 PHI->addMachineBasicBlockOperand(RangeBB);
4548 }
4549 if (BB->succ_end() != std::find(BB->succ_begin(),BB->succ_end(), PHIBB)) {
Chris Lattner09e46062006-09-05 02:31:13 +00004550 PHI->addRegOperand(PHINodesToUpdate[pi].second, false);
Nate Begemanf4360a42006-05-03 03:48:02 +00004551 PHI->addMachineBasicBlockOperand(BB);
Nate Begeman37efe672006-04-22 18:53:45 +00004552 }
4553 }
4554 return;
4555 }
4556
Chris Lattnerb2e806e2006-10-22 23:00:53 +00004557 // If the switch block involved a branch to one of the actual successors, we
4558 // need to update PHI nodes in that block.
4559 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
4560 MachineInstr *PHI = PHINodesToUpdate[i].first;
4561 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
4562 "This is not a machine PHI node that we are updating!");
4563 if (BB->isSuccessor(PHI->getParent())) {
4564 PHI->addRegOperand(PHINodesToUpdate[i].second, false);
4565 PHI->addMachineBasicBlockOperand(BB);
4566 }
4567 }
4568
Nate Begemanf15485a2006-03-27 01:32:24 +00004569 // If we generated any switch lowering information, build and codegen any
4570 // additional DAGs necessary.
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004571 for (unsigned i = 0, e = SwitchCases.size(); i != e; ++i) {
Jim Laskey44c3b9f2007-01-26 21:22:28 +00004572 SelectionDAG SDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
Nate Begemanf15485a2006-03-27 01:32:24 +00004573 CurDAG = &SDAG;
4574 SelectionDAGLowering SDL(SDAG, TLI, FuncInfo);
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004575
Nate Begemanf15485a2006-03-27 01:32:24 +00004576 // Set the current basic block to the mbb we wish to insert the code into
4577 BB = SwitchCases[i].ThisBB;
4578 SDL.setCurrentBasicBlock(BB);
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004579
Nate Begemanf15485a2006-03-27 01:32:24 +00004580 // Emit the code
4581 SDL.visitSwitchCase(SwitchCases[i]);
4582 SDAG.setRoot(SDL.getRoot());
4583 CodeGenAndEmitDAG(SDAG);
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004584
4585 // Handle any PHI nodes in successors of this chunk, as if we were coming
4586 // from the original BB before switch expansion. Note that PHI nodes can
4587 // occur multiple times in PHINodesToUpdate. We have to be very careful to
4588 // handle them the right number of times.
Chris Lattner57ab6592006-10-24 17:57:59 +00004589 while ((BB = SwitchCases[i].TrueBB)) { // Handle LHS and RHS.
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004590 for (MachineBasicBlock::iterator Phi = BB->begin();
4591 Phi != BB->end() && Phi->getOpcode() == TargetInstrInfo::PHI; ++Phi){
4592 // This value for this PHI node is recorded in PHINodesToUpdate, get it.
4593 for (unsigned pn = 0; ; ++pn) {
4594 assert(pn != PHINodesToUpdate.size() && "Didn't find PHI entry!");
4595 if (PHINodesToUpdate[pn].first == Phi) {
4596 Phi->addRegOperand(PHINodesToUpdate[pn].second, false);
4597 Phi->addMachineBasicBlockOperand(SwitchCases[i].ThisBB);
4598 break;
4599 }
4600 }
Nate Begemanf15485a2006-03-27 01:32:24 +00004601 }
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004602
4603 // Don't process RHS if same block as LHS.
Chris Lattner57ab6592006-10-24 17:57:59 +00004604 if (BB == SwitchCases[i].FalseBB)
4605 SwitchCases[i].FalseBB = 0;
Chris Lattnerd5e93c02006-09-07 01:59:34 +00004606
4607 // If we haven't handled the RHS, do so now. Otherwise, we're done.
Chris Lattner24525952006-10-24 18:07:37 +00004608 SwitchCases[i].TrueBB = SwitchCases[i].FalseBB;
Chris Lattner57ab6592006-10-24 17:57:59 +00004609 SwitchCases[i].FalseBB = 0;
Nate Begemanf15485a2006-03-27 01:32:24 +00004610 }
Chris Lattner57ab6592006-10-24 17:57:59 +00004611 assert(SwitchCases[i].TrueBB == 0 && SwitchCases[i].FalseBB == 0);
Chris Lattnera33ef482005-03-30 01:10:47 +00004612 }
Chris Lattner1c08c712005-01-07 07:47:53 +00004613}
Evan Chenga9c20912006-01-21 02:32:06 +00004614
Jim Laskey13ec7022006-08-01 14:21:23 +00004615
Evan Chenga9c20912006-01-21 02:32:06 +00004616//===----------------------------------------------------------------------===//
4617/// ScheduleAndEmitDAG - Pick a safe ordering and emit instructions for each
4618/// target node in the graph.
4619void SelectionDAGISel::ScheduleAndEmitDAG(SelectionDAG &DAG) {
4620 if (ViewSchedDAGs) DAG.viewGraph();
Evan Cheng4ef10862006-01-23 07:01:07 +00004621
Jim Laskeyeb577ba2006-08-02 12:30:23 +00004622 RegisterScheduler::FunctionPassCtor Ctor = RegisterScheduler::getDefault();
Jim Laskey13ec7022006-08-01 14:21:23 +00004623
4624 if (!Ctor) {
Jim Laskeyeb577ba2006-08-02 12:30:23 +00004625 Ctor = ISHeuristic;
Jim Laskey9373beb2006-08-01 19:14:14 +00004626 RegisterScheduler::setDefault(Ctor);
Evan Cheng4ef10862006-01-23 07:01:07 +00004627 }
Jim Laskey13ec7022006-08-01 14:21:23 +00004628
Jim Laskey9ff542f2006-08-01 18:29:48 +00004629 ScheduleDAG *SL = Ctor(this, &DAG, BB);
Chris Lattnera3818e62006-01-21 19:12:11 +00004630 BB = SL->Run();
Evan Chengcccf1232006-02-04 06:49:00 +00004631 delete SL;
Evan Chenga9c20912006-01-21 02:32:06 +00004632}
Chris Lattner0e43f2b2006-02-24 02:13:54 +00004633
Chris Lattner03fc53c2006-03-06 00:22:00 +00004634
Jim Laskey9ff542f2006-08-01 18:29:48 +00004635HazardRecognizer *SelectionDAGISel::CreateTargetHazardRecognizer() {
4636 return new HazardRecognizer();
4637}
4638
Chris Lattner75548062006-10-11 03:58:02 +00004639//===----------------------------------------------------------------------===//
4640// Helper functions used by the generated instruction selector.
4641//===----------------------------------------------------------------------===//
4642// Calls to these methods are generated by tblgen.
4643
4644/// CheckAndMask - The isel is trying to match something like (and X, 255). If
4645/// the dag combiner simplified the 255, we still want to match. RHS is the
4646/// actual value in the DAG on the RHS of an AND, and DesiredMaskS is the value
4647/// specified in the .td file (e.g. 255).
4648bool SelectionDAGISel::CheckAndMask(SDOperand LHS, ConstantSDNode *RHS,
4649 int64_t DesiredMaskS) {
4650 uint64_t ActualMask = RHS->getValue();
4651 uint64_t DesiredMask =DesiredMaskS & MVT::getIntVTBitMask(LHS.getValueType());
4652
4653 // If the actual mask exactly matches, success!
4654 if (ActualMask == DesiredMask)
4655 return true;
4656
4657 // If the actual AND mask is allowing unallowed bits, this doesn't match.
4658 if (ActualMask & ~DesiredMask)
4659 return false;
4660
4661 // Otherwise, the DAG Combiner may have proven that the value coming in is
4662 // either already zero or is not demanded. Check for known zero input bits.
4663 uint64_t NeededMask = DesiredMask & ~ActualMask;
4664 if (getTargetLowering().MaskedValueIsZero(LHS, NeededMask))
4665 return true;
4666
4667 // TODO: check to see if missing bits are just not demanded.
4668
4669 // Otherwise, this pattern doesn't match.
4670 return false;
4671}
4672
4673/// CheckOrMask - The isel is trying to match something like (or X, 255). If
4674/// the dag combiner simplified the 255, we still want to match. RHS is the
4675/// actual value in the DAG on the RHS of an OR, and DesiredMaskS is the value
4676/// specified in the .td file (e.g. 255).
4677bool SelectionDAGISel::CheckOrMask(SDOperand LHS, ConstantSDNode *RHS,
4678 int64_t DesiredMaskS) {
4679 uint64_t ActualMask = RHS->getValue();
4680 uint64_t DesiredMask =DesiredMaskS & MVT::getIntVTBitMask(LHS.getValueType());
4681
4682 // If the actual mask exactly matches, success!
4683 if (ActualMask == DesiredMask)
4684 return true;
4685
4686 // If the actual AND mask is allowing unallowed bits, this doesn't match.
4687 if (ActualMask & ~DesiredMask)
4688 return false;
4689
4690 // Otherwise, the DAG Combiner may have proven that the value coming in is
4691 // either already zero or is not demanded. Check for known zero input bits.
4692 uint64_t NeededMask = DesiredMask & ~ActualMask;
4693
4694 uint64_t KnownZero, KnownOne;
4695 getTargetLowering().ComputeMaskedBits(LHS, NeededMask, KnownZero, KnownOne);
4696
4697 // If all the missing bits in the or are already known to be set, match!
4698 if ((NeededMask & KnownOne) == NeededMask)
4699 return true;
4700
4701 // TODO: check to see if missing bits are just not demanded.
4702
4703 // Otherwise, this pattern doesn't match.
4704 return false;
4705}
4706
Jim Laskey9ff542f2006-08-01 18:29:48 +00004707
Chris Lattner0e43f2b2006-02-24 02:13:54 +00004708/// SelectInlineAsmMemoryOperands - Calls to this are automatically generated
4709/// by tblgen. Others should not call it.
4710void SelectionDAGISel::
4711SelectInlineAsmMemoryOperands(std::vector<SDOperand> &Ops, SelectionDAG &DAG) {
4712 std::vector<SDOperand> InOps;
4713 std::swap(InOps, Ops);
4714
4715 Ops.push_back(InOps[0]); // input chain.
4716 Ops.push_back(InOps[1]); // input asm string.
4717
Chris Lattner0e43f2b2006-02-24 02:13:54 +00004718 unsigned i = 2, e = InOps.size();
4719 if (InOps[e-1].getValueType() == MVT::Flag)
4720 --e; // Don't process a flag operand if it is here.
4721
4722 while (i != e) {
4723 unsigned Flags = cast<ConstantSDNode>(InOps[i])->getValue();
4724 if ((Flags & 7) != 4 /*MEM*/) {
4725 // Just skip over this operand, copying the operands verbatim.
4726 Ops.insert(Ops.end(), InOps.begin()+i, InOps.begin()+i+(Flags >> 3) + 1);
4727 i += (Flags >> 3) + 1;
4728 } else {
4729 assert((Flags >> 3) == 1 && "Memory operand with multiple values?");
4730 // Otherwise, this is a memory operand. Ask the target to select it.
4731 std::vector<SDOperand> SelOps;
4732 if (SelectInlineAsmMemoryOperand(InOps[i+1], 'm', SelOps, DAG)) {
Bill Wendling832171c2006-12-07 20:04:42 +00004733 cerr << "Could not match memory address. Inline asm failure!\n";
Chris Lattner0e43f2b2006-02-24 02:13:54 +00004734 exit(1);
4735 }
4736
4737 // Add this to the output node.
Chris Lattner36d43962006-12-16 21:14:48 +00004738 Ops.push_back(DAG.getTargetConstant(4/*MEM*/ | (SelOps.size() << 3),
4739 MVT::i32));
Chris Lattner0e43f2b2006-02-24 02:13:54 +00004740 Ops.insert(Ops.end(), SelOps.begin(), SelOps.end());
4741 i += 2;
4742 }
4743 }
4744
4745 // Add the flag input back if present.
4746 if (e != InOps.size())
4747 Ops.push_back(InOps.back());
4748}