blob: 6b93a703cf248929e9121575bc7570a099de3834 [file] [log] [blame]
Chris Lattner7a60d912005-01-07 07:47:53 +00001//===-- SelectionDAGISel.cpp - Implement the SelectionDAGISel class -------===//
Misha Brukman835702a2005-04-21 22:36:52 +00002//
Chris Lattner7a60d912005-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 Brukman835702a2005-04-21 22:36:52 +00007//
Chris Lattner7a60d912005-01-07 07:47:53 +00008//===----------------------------------------------------------------------===//
9//
10// This implements the SelectionDAGISel class.
11//
12//===----------------------------------------------------------------------===//
13
14#define DEBUG_TYPE "isel"
15#include "llvm/CodeGen/SelectionDAGISel.h"
Evan Cheng739a6a42006-01-21 02:32:06 +000016#include "llvm/CodeGen/ScheduleDAG.h"
Chris Lattner2e77db62005-05-13 18:50:42 +000017#include "llvm/CallingConv.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000018#include "llvm/Constants.h"
19#include "llvm/DerivedTypes.h"
20#include "llvm/Function.h"
Chris Lattner435b4022005-11-29 06:21:05 +000021#include "llvm/GlobalVariable.h"
Chris Lattner476e67b2006-01-26 22:24:51 +000022#include "llvm/InlineAsm.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000023#include "llvm/Instructions.h"
24#include "llvm/Intrinsics.h"
Chris Lattnerf2b62f32005-11-16 07:22:30 +000025#include "llvm/CodeGen/IntrinsicLowering.h"
Jim Laskey219d5592006-01-04 22:28:25 +000026#include "llvm/CodeGen/MachineDebugInfo.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000027#include "llvm/CodeGen/MachineFunction.h"
28#include "llvm/CodeGen/MachineFrameInfo.h"
29#include "llvm/CodeGen/MachineInstrBuilder.h"
30#include "llvm/CodeGen/SelectionDAG.h"
31#include "llvm/CodeGen/SSARegMap.h"
Chris Lattnerd4382f02005-09-13 19:30:54 +000032#include "llvm/Target/MRegisterInfo.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000033#include "llvm/Target/TargetData.h"
34#include "llvm/Target/TargetFrameInfo.h"
35#include "llvm/Target/TargetInstrInfo.h"
36#include "llvm/Target/TargetLowering.h"
37#include "llvm/Target/TargetMachine.h"
Chris Lattnerc9950c12005-08-17 06:37:43 +000038#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Chris Lattnere05a4612005-01-12 03:41:21 +000039#include "llvm/Support/CommandLine.h"
Chris Lattner43535a12005-11-09 04:45:33 +000040#include "llvm/Support/MathExtras.h"
Chris Lattner7a60d912005-01-07 07:47:53 +000041#include "llvm/Support/Debug.h"
42#include <map>
Chris Lattner1558fc62006-02-01 18:59:47 +000043#include <set>
Chris Lattner7a60d912005-01-07 07:47:53 +000044#include <iostream>
Jeff Cohen83c22e02006-02-24 02:52:40 +000045#include <algorithm>
Chris Lattner7a60d912005-01-07 07:47:53 +000046using namespace llvm;
47
Chris Lattner975f5c92005-09-01 18:44:10 +000048#ifndef NDEBUG
Chris Lattnere05a4612005-01-12 03:41:21 +000049static cl::opt<bool>
Evan Cheng739a6a42006-01-21 02:32:06 +000050ViewISelDAGs("view-isel-dags", cl::Hidden,
51 cl::desc("Pop up a window to show isel dags as they are selected"));
52static cl::opt<bool>
53ViewSchedDAGs("view-sched-dags", cl::Hidden,
54 cl::desc("Pop up a window to show sched dags as they are processed"));
Chris Lattnere05a4612005-01-12 03:41:21 +000055#else
Evan Cheng739a6a42006-01-21 02:32:06 +000056static const bool ViewISelDAGs = 0;
57static const bool ViewSchedDAGs = 0;
Chris Lattnere05a4612005-01-12 03:41:21 +000058#endif
59
Evan Chengc1e1d972006-01-23 07:01:07 +000060namespace {
61 cl::opt<SchedHeuristics>
62 ISHeuristic(
63 "sched",
64 cl::desc("Choose scheduling style"),
Evan Chenga6eff8a2006-01-25 09:12:57 +000065 cl::init(defaultScheduling),
Evan Chengc1e1d972006-01-23 07:01:07 +000066 cl::values(
Evan Chenga6eff8a2006-01-25 09:12:57 +000067 clEnumValN(defaultScheduling, "default",
68 "Target preferred scheduling style"),
Evan Chengc1e1d972006-01-23 07:01:07 +000069 clEnumValN(noScheduling, "none",
Jim Laskeyb8566fa2006-01-23 13:34:04 +000070 "No scheduling: breadth first sequencing"),
Evan Chengc1e1d972006-01-23 07:01:07 +000071 clEnumValN(simpleScheduling, "simple",
72 "Simple two pass scheduling: minimize critical path "
73 "and maximize processor utilization"),
74 clEnumValN(simpleNoItinScheduling, "simple-noitin",
75 "Simple two pass scheduling: Same as simple "
76 "except using generic latency"),
Evan Chenga6eff8a2006-01-25 09:12:57 +000077 clEnumValN(listSchedulingBURR, "list-burr",
Evan Cheng31272342006-01-23 08:26:10 +000078 "Bottom up register reduction list scheduling"),
Evan Chengc1e1d972006-01-23 07:01:07 +000079 clEnumValEnd));
80} // namespace
81
Chris Lattner6f87d182006-02-22 22:37:12 +000082namespace {
83 /// RegsForValue - This struct represents the physical registers that a
84 /// particular value is assigned and the type information about the value.
85 /// This is needed because values can be promoted into larger registers and
86 /// expanded into multiple smaller registers than the value.
87 struct RegsForValue {
88 /// Regs - This list hold the register (for legal and promoted values)
89 /// or register set (for expanded values) that the value should be assigned
90 /// to.
91 std::vector<unsigned> Regs;
92
93 /// RegVT - The value type of each register.
94 ///
95 MVT::ValueType RegVT;
96
97 /// ValueVT - The value type of the LLVM value, which may be promoted from
98 /// RegVT or made from merging the two expanded parts.
99 MVT::ValueType ValueVT;
100
101 RegsForValue() : RegVT(MVT::Other), ValueVT(MVT::Other) {}
102
103 RegsForValue(unsigned Reg, MVT::ValueType regvt, MVT::ValueType valuevt)
104 : RegVT(regvt), ValueVT(valuevt) {
105 Regs.push_back(Reg);
106 }
107 RegsForValue(const std::vector<unsigned> &regs,
108 MVT::ValueType regvt, MVT::ValueType valuevt)
109 : Regs(regs), RegVT(regvt), ValueVT(valuevt) {
110 }
111
112 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
113 /// this value and returns the result as a ValueVT value. This uses
114 /// Chain/Flag as the input and updates them for the output Chain/Flag.
115 SDOperand getCopyFromRegs(SelectionDAG &DAG,
Chris Lattnere7c0ffb2006-02-23 20:06:57 +0000116 SDOperand &Chain, SDOperand &Flag) const;
Chris Lattner571d9642006-02-23 19:21:04 +0000117
118 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
119 /// specified value into the registers specified by this object. This uses
120 /// Chain/Flag as the input and updates them for the output Chain/Flag.
121 void getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
Chris Lattnere7c0ffb2006-02-23 20:06:57 +0000122 SDOperand &Chain, SDOperand &Flag) const;
Chris Lattner571d9642006-02-23 19:21:04 +0000123
124 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
125 /// operand list. This adds the code marker and includes the number of
126 /// values added into it.
127 void AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
Chris Lattnere7c0ffb2006-02-23 20:06:57 +0000128 std::vector<SDOperand> &Ops) const;
Chris Lattner6f87d182006-02-22 22:37:12 +0000129 };
130}
Evan Chengc1e1d972006-01-23 07:01:07 +0000131
Chris Lattner7a60d912005-01-07 07:47:53 +0000132namespace llvm {
133 //===--------------------------------------------------------------------===//
134 /// FunctionLoweringInfo - This contains information that is global to a
135 /// function that is used when lowering a region of the function.
Chris Lattnerd0061952005-01-08 19:52:31 +0000136 class FunctionLoweringInfo {
137 public:
Chris Lattner7a60d912005-01-07 07:47:53 +0000138 TargetLowering &TLI;
139 Function &Fn;
140 MachineFunction &MF;
141 SSARegMap *RegMap;
142
143 FunctionLoweringInfo(TargetLowering &TLI, Function &Fn,MachineFunction &MF);
144
145 /// MBBMap - A mapping from LLVM basic blocks to their machine code entry.
146 std::map<const BasicBlock*, MachineBasicBlock *> MBBMap;
147
148 /// ValueMap - Since we emit code for the function a basic block at a time,
149 /// we must remember which virtual registers hold the values for
150 /// cross-basic-block values.
151 std::map<const Value*, unsigned> ValueMap;
152
153 /// StaticAllocaMap - Keep track of frame indices for fixed sized allocas in
154 /// the entry block. This allows the allocas to be efficiently referenced
155 /// anywhere in the function.
156 std::map<const AllocaInst*, int> StaticAllocaMap;
157
158 unsigned MakeReg(MVT::ValueType VT) {
159 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
160 }
Misha Brukman835702a2005-04-21 22:36:52 +0000161
Chris Lattner7a60d912005-01-07 07:47:53 +0000162 unsigned CreateRegForValue(const Value *V) {
163 MVT::ValueType VT = TLI.getValueType(V->getType());
164 // The common case is that we will only create one register for this
165 // value. If we have that case, create and return the virtual register.
166 unsigned NV = TLI.getNumElements(VT);
Chris Lattnera8d34fb2005-01-16 00:37:38 +0000167 if (NV == 1) {
168 // If we are promoting this value, pick the next largest supported type.
Chris Lattnerd58384f2005-01-16 01:11:19 +0000169 return MakeReg(TLI.getTypeToTransformTo(VT));
Chris Lattnera8d34fb2005-01-16 00:37:38 +0000170 }
Misha Brukman835702a2005-04-21 22:36:52 +0000171
Chris Lattner7a60d912005-01-07 07:47:53 +0000172 // If this value is represented with multiple target registers, make sure
Chris Lattner6f87d182006-02-22 22:37:12 +0000173 // to create enough consecutive registers of the right (smaller) type.
Chris Lattner7a60d912005-01-07 07:47:53 +0000174 unsigned NT = VT-1; // Find the type to use.
175 while (TLI.getNumElements((MVT::ValueType)NT) != 1)
176 --NT;
Misha Brukman835702a2005-04-21 22:36:52 +0000177
Chris Lattner7a60d912005-01-07 07:47:53 +0000178 unsigned R = MakeReg((MVT::ValueType)NT);
179 for (unsigned i = 1; i != NV; ++i)
180 MakeReg((MVT::ValueType)NT);
181 return R;
182 }
Misha Brukman835702a2005-04-21 22:36:52 +0000183
Chris Lattner7a60d912005-01-07 07:47:53 +0000184 unsigned InitializeRegForValue(const Value *V) {
185 unsigned &R = ValueMap[V];
186 assert(R == 0 && "Already initialized this value register!");
187 return R = CreateRegForValue(V);
188 }
189 };
190}
191
192/// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by
193/// PHI nodes or outside of the basic block that defines it.
194static bool isUsedOutsideOfDefiningBlock(Instruction *I) {
195 if (isa<PHINode>(I)) return true;
196 BasicBlock *BB = I->getParent();
197 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; ++UI)
198 if (cast<Instruction>(*UI)->getParent() != BB || isa<PHINode>(*UI))
199 return true;
200 return false;
201}
202
Chris Lattner6871b232005-10-30 19:42:35 +0000203/// isOnlyUsedInEntryBlock - If the specified argument is only used in the
204/// entry block, return true.
205static bool isOnlyUsedInEntryBlock(Argument *A) {
206 BasicBlock *Entry = A->getParent()->begin();
207 for (Value::use_iterator UI = A->use_begin(), E = A->use_end(); UI != E; ++UI)
208 if (cast<Instruction>(*UI)->getParent() != Entry)
209 return false; // Use not in entry block.
210 return true;
211}
212
Chris Lattner7a60d912005-01-07 07:47:53 +0000213FunctionLoweringInfo::FunctionLoweringInfo(TargetLowering &tli,
Misha Brukman835702a2005-04-21 22:36:52 +0000214 Function &fn, MachineFunction &mf)
Chris Lattner7a60d912005-01-07 07:47:53 +0000215 : TLI(tli), Fn(fn), MF(mf), RegMap(MF.getSSARegMap()) {
216
Chris Lattner6871b232005-10-30 19:42:35 +0000217 // Create a vreg for each argument register that is not dead and is used
218 // outside of the entry block for the function.
219 for (Function::arg_iterator AI = Fn.arg_begin(), E = Fn.arg_end();
220 AI != E; ++AI)
221 if (!isOnlyUsedInEntryBlock(AI))
222 InitializeRegForValue(AI);
223
Chris Lattner7a60d912005-01-07 07:47:53 +0000224 // Initialize the mapping of values to registers. This is only set up for
225 // instruction values that are used outside of the block that defines
226 // them.
Jeff Cohenf8a5e5ae2005-10-01 03:57:14 +0000227 Function::iterator BB = Fn.begin(), EB = Fn.end();
Chris Lattner7a60d912005-01-07 07:47:53 +0000228 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
229 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
230 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(AI->getArraySize())) {
231 const Type *Ty = AI->getAllocatedType();
232 uint64_t TySize = TLI.getTargetData().getTypeSize(Ty);
Nate Begeman3ee3e692005-11-06 09:00:38 +0000233 unsigned Align =
234 std::max((unsigned)TLI.getTargetData().getTypeAlignment(Ty),
235 AI->getAlignment());
Chris Lattnercbefe722005-05-13 23:14:17 +0000236
237 // If the alignment of the value is smaller than the size of the value,
238 // and if the size of the value is particularly small (<= 8 bytes),
239 // round up to the size of the value for potentially better performance.
240 //
241 // FIXME: This could be made better with a preferred alignment hook in
242 // TargetData. It serves primarily to 8-byte align doubles for X86.
243 if (Align < TySize && TySize <= 8) Align = TySize;
Chris Lattner8396a302005-10-18 22:11:42 +0000244 TySize *= CUI->getValue(); // Get total allocated size.
Chris Lattner0a71a9a2005-10-18 22:14:06 +0000245 if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
Chris Lattner7a60d912005-01-07 07:47:53 +0000246 StaticAllocaMap[AI] =
Chris Lattnerd0061952005-01-08 19:52:31 +0000247 MF.getFrameInfo()->CreateStackObject((unsigned)TySize, Align);
Chris Lattner7a60d912005-01-07 07:47:53 +0000248 }
249
Jeff Cohenf8a5e5ae2005-10-01 03:57:14 +0000250 for (; BB != EB; ++BB)
251 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
Chris Lattner7a60d912005-01-07 07:47:53 +0000252 if (!I->use_empty() && isUsedOutsideOfDefiningBlock(I))
253 if (!isa<AllocaInst>(I) ||
254 !StaticAllocaMap.count(cast<AllocaInst>(I)))
255 InitializeRegForValue(I);
256
257 // Create an initial MachineBasicBlock for each LLVM BasicBlock in F. This
258 // also creates the initial PHI MachineInstrs, though none of the input
259 // operands are populated.
Jeff Cohenf8a5e5ae2005-10-01 03:57:14 +0000260 for (BB = Fn.begin(), EB = Fn.end(); BB != EB; ++BB) {
Chris Lattner7a60d912005-01-07 07:47:53 +0000261 MachineBasicBlock *MBB = new MachineBasicBlock(BB);
262 MBBMap[BB] = MBB;
263 MF.getBasicBlockList().push_back(MBB);
264
265 // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
266 // appropriate.
267 PHINode *PN;
268 for (BasicBlock::iterator I = BB->begin();
Chris Lattner8ea875f2005-01-07 21:34:19 +0000269 (PN = dyn_cast<PHINode>(I)); ++I)
270 if (!PN->use_empty()) {
271 unsigned NumElements =
272 TLI.getNumElements(TLI.getValueType(PN->getType()));
273 unsigned PHIReg = ValueMap[PN];
274 assert(PHIReg &&"PHI node does not have an assigned virtual register!");
275 for (unsigned i = 0; i != NumElements; ++i)
276 BuildMI(MBB, TargetInstrInfo::PHI, PN->getNumOperands(), PHIReg+i);
277 }
Chris Lattner7a60d912005-01-07 07:47:53 +0000278 }
279}
280
281
282
283//===----------------------------------------------------------------------===//
284/// SelectionDAGLowering - This is the common target-independent lowering
285/// implementation that is parameterized by a TargetLowering object.
286/// Also, targets can overload any lowering method.
287///
288namespace llvm {
289class SelectionDAGLowering {
290 MachineBasicBlock *CurMBB;
291
292 std::map<const Value*, SDOperand> NodeMap;
293
Chris Lattner4d9651c2005-01-17 22:19:26 +0000294 /// PendingLoads - Loads are not emitted to the program immediately. We bunch
295 /// them up and then emit token factor nodes when possible. This allows us to
296 /// get simple disambiguation between loads without worrying about alias
297 /// analysis.
298 std::vector<SDOperand> PendingLoads;
299
Chris Lattner7a60d912005-01-07 07:47:53 +0000300public:
301 // TLI - This is information that describes the available target features we
302 // need for lowering. This indicates when operations are unavailable,
303 // implemented with a libcall, etc.
304 TargetLowering &TLI;
305 SelectionDAG &DAG;
306 const TargetData &TD;
307
308 /// FuncInfo - Information about the function as a whole.
309 ///
310 FunctionLoweringInfo &FuncInfo;
311
312 SelectionDAGLowering(SelectionDAG &dag, TargetLowering &tli,
Misha Brukman835702a2005-04-21 22:36:52 +0000313 FunctionLoweringInfo &funcinfo)
Chris Lattner7a60d912005-01-07 07:47:53 +0000314 : TLI(tli), DAG(dag), TD(DAG.getTarget().getTargetData()),
315 FuncInfo(funcinfo) {
316 }
317
Chris Lattner4108bb02005-01-17 19:43:36 +0000318 /// getRoot - Return the current virtual root of the Selection DAG.
319 ///
320 SDOperand getRoot() {
Chris Lattner4d9651c2005-01-17 22:19:26 +0000321 if (PendingLoads.empty())
322 return DAG.getRoot();
Misha Brukman835702a2005-04-21 22:36:52 +0000323
Chris Lattner4d9651c2005-01-17 22:19:26 +0000324 if (PendingLoads.size() == 1) {
325 SDOperand Root = PendingLoads[0];
326 DAG.setRoot(Root);
327 PendingLoads.clear();
328 return Root;
329 }
330
331 // Otherwise, we have to make a token factor node.
332 SDOperand Root = DAG.getNode(ISD::TokenFactor, MVT::Other, PendingLoads);
333 PendingLoads.clear();
334 DAG.setRoot(Root);
335 return Root;
Chris Lattner4108bb02005-01-17 19:43:36 +0000336 }
337
Chris Lattner7a60d912005-01-07 07:47:53 +0000338 void visit(Instruction &I) { visit(I.getOpcode(), I); }
339
340 void visit(unsigned Opcode, User &I) {
341 switch (Opcode) {
342 default: assert(0 && "Unknown instruction type encountered!");
343 abort();
344 // Build the switch statement using the Instruction.def file.
345#define HANDLE_INST(NUM, OPCODE, CLASS) \
346 case Instruction::OPCODE:return visit##OPCODE((CLASS&)I);
347#include "llvm/Instruction.def"
348 }
349 }
350
351 void setCurrentBasicBlock(MachineBasicBlock *MBB) { CurMBB = MBB; }
352
353
354 SDOperand getIntPtrConstant(uint64_t Val) {
355 return DAG.getConstant(Val, TLI.getPointerTy());
356 }
357
358 SDOperand getValue(const Value *V) {
359 SDOperand &N = NodeMap[V];
360 if (N.Val) return N;
361
Nate Begeman41b1cdc2005-12-06 06:18:55 +0000362 const Type *VTy = V->getType();
363 MVT::ValueType VT = TLI.getValueType(VTy);
Chris Lattner7a60d912005-01-07 07:47:53 +0000364 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V)))
365 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
366 visit(CE->getOpcode(), *CE);
367 assert(N.Val && "visit didn't populate the ValueMap!");
368 return N;
369 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(C)) {
370 return N = DAG.getGlobalAddress(GV, VT);
371 } else if (isa<ConstantPointerNull>(C)) {
372 return N = DAG.getConstant(0, TLI.getPointerTy());
373 } else if (isa<UndefValue>(C)) {
Nate Begemanaf1c0f72005-04-12 23:12:17 +0000374 return N = DAG.getNode(ISD::UNDEF, VT);
Chris Lattner7a60d912005-01-07 07:47:53 +0000375 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
376 return N = DAG.getConstantFP(CFP->getValue(), VT);
Nate Begeman41b1cdc2005-12-06 06:18:55 +0000377 } else if (const PackedType *PTy = dyn_cast<PackedType>(VTy)) {
378 unsigned NumElements = PTy->getNumElements();
379 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
380 MVT::ValueType TVT = MVT::getVectorType(PVT, NumElements);
381
382 // Now that we know the number and type of the elements, push a
383 // Constant or ConstantFP node onto the ops list for each element of
384 // the packed constant.
385 std::vector<SDOperand> Ops;
Chris Lattner803a5752005-12-21 02:43:26 +0000386 if (ConstantPacked *CP = dyn_cast<ConstantPacked>(C)) {
387 if (MVT::isFloatingPoint(PVT)) {
388 for (unsigned i = 0; i != NumElements; ++i) {
389 const ConstantFP *El = cast<ConstantFP>(CP->getOperand(i));
390 Ops.push_back(DAG.getConstantFP(El->getValue(), PVT));
391 }
392 } else {
393 for (unsigned i = 0; i != NumElements; ++i) {
394 const ConstantIntegral *El =
395 cast<ConstantIntegral>(CP->getOperand(i));
396 Ops.push_back(DAG.getConstant(El->getRawValue(), PVT));
397 }
398 }
399 } else {
400 assert(isa<ConstantAggregateZero>(C) && "Unknown packed constant!");
401 SDOperand Op;
Nate Begeman41b1cdc2005-12-06 06:18:55 +0000402 if (MVT::isFloatingPoint(PVT))
Chris Lattner803a5752005-12-21 02:43:26 +0000403 Op = DAG.getConstantFP(0, PVT);
Nate Begeman41b1cdc2005-12-06 06:18:55 +0000404 else
Chris Lattner803a5752005-12-21 02:43:26 +0000405 Op = DAG.getConstant(0, PVT);
406 Ops.assign(NumElements, Op);
Nate Begeman41b1cdc2005-12-06 06:18:55 +0000407 }
Chris Lattner803a5752005-12-21 02:43:26 +0000408
Nate Begeman41b1cdc2005-12-06 06:18:55 +0000409 // Handle the case where we have a 1-element vector, in which
410 // case we want to immediately turn it into a scalar constant.
Nate Begemanae89d862005-12-07 19:48:11 +0000411 if (Ops.size() == 1) {
Nate Begeman41b1cdc2005-12-06 06:18:55 +0000412 return N = Ops[0];
Nate Begemanae89d862005-12-07 19:48:11 +0000413 } else if (TVT != MVT::Other && TLI.isTypeLegal(TVT)) {
414 return N = DAG.getNode(ISD::ConstantVec, TVT, Ops);
415 } else {
416 // If the packed type isn't legal, then create a ConstantVec node with
417 // generic Vector type instead.
418 return N = DAG.getNode(ISD::ConstantVec, MVT::Vector, Ops);
419 }
Chris Lattner7a60d912005-01-07 07:47:53 +0000420 } else {
421 // Canonicalize all constant ints to be unsigned.
422 return N = DAG.getConstant(cast<ConstantIntegral>(C)->getRawValue(),VT);
423 }
424
425 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
426 std::map<const AllocaInst*, int>::iterator SI =
427 FuncInfo.StaticAllocaMap.find(AI);
428 if (SI != FuncInfo.StaticAllocaMap.end())
429 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
430 }
431
432 std::map<const Value*, unsigned>::const_iterator VMI =
433 FuncInfo.ValueMap.find(V);
434 assert(VMI != FuncInfo.ValueMap.end() && "Value not in map!");
Chris Lattner209f5852005-01-16 02:23:07 +0000435
Chris Lattner33182322005-08-16 21:55:35 +0000436 unsigned InReg = VMI->second;
437
438 // If this type is not legal, make it so now.
439 MVT::ValueType DestVT = TLI.getTypeToTransformTo(VT);
440
441 N = DAG.getCopyFromReg(DAG.getEntryNode(), InReg, DestVT);
442 if (DestVT < VT) {
443 // Source must be expanded. This input value is actually coming from the
444 // register pair VMI->second and VMI->second+1.
445 N = DAG.getNode(ISD::BUILD_PAIR, VT, N,
446 DAG.getCopyFromReg(DAG.getEntryNode(), InReg+1, DestVT));
447 } else {
448 if (DestVT > VT) { // Promotion case
449 if (MVT::isFloatingPoint(VT))
450 N = DAG.getNode(ISD::FP_ROUND, VT, N);
451 else
452 N = DAG.getNode(ISD::TRUNCATE, VT, N);
453 }
454 }
455
456 return N;
Chris Lattner7a60d912005-01-07 07:47:53 +0000457 }
458
459 const SDOperand &setValue(const Value *V, SDOperand NewN) {
460 SDOperand &N = NodeMap[V];
461 assert(N.Val == 0 && "Already set a value for this node!");
462 return N = NewN;
463 }
Chris Lattner1558fc62006-02-01 18:59:47 +0000464
Chris Lattner6f87d182006-02-22 22:37:12 +0000465 RegsForValue GetRegistersForValue(const std::string &ConstrCode,
466 MVT::ValueType VT,
467 bool OutReg, bool InReg,
468 std::set<unsigned> &OutputRegs,
469 std::set<unsigned> &InputRegs);
470
Chris Lattner7a60d912005-01-07 07:47:53 +0000471 // Terminator instructions.
472 void visitRet(ReturnInst &I);
473 void visitBr(BranchInst &I);
474 void visitUnreachable(UnreachableInst &I) { /* noop */ }
475
476 // These all get lowered before this pass.
Robert Bocchino2c966e72006-01-10 19:04:57 +0000477 void visitExtractElement(ExtractElementInst &I) { assert(0 && "TODO"); }
Robert Bocchino03e95af2006-01-17 20:06:42 +0000478 void visitInsertElement(InsertElementInst &I) { assert(0 && "TODO"); }
Chris Lattner7a60d912005-01-07 07:47:53 +0000479 void visitSwitch(SwitchInst &I) { assert(0 && "TODO"); }
480 void visitInvoke(InvokeInst &I) { assert(0 && "TODO"); }
481 void visitUnwind(UnwindInst &I) { assert(0 && "TODO"); }
482
483 //
Nate Begemanb2e089c2005-11-19 00:36:38 +0000484 void visitBinary(User &I, unsigned IntOp, unsigned FPOp, unsigned VecOp);
Nate Begeman127321b2005-11-18 07:42:56 +0000485 void visitShift(User &I, unsigned Opcode);
Nate Begemanb2e089c2005-11-19 00:36:38 +0000486 void visitAdd(User &I) {
487 visitBinary(I, ISD::ADD, ISD::FADD, ISD::VADD);
Chris Lattner6f3b5772005-09-28 22:28:18 +0000488 }
Chris Lattnerf68fd0b2005-04-02 05:04:50 +0000489 void visitSub(User &I);
Nate Begemanb2e089c2005-11-19 00:36:38 +0000490 void visitMul(User &I) {
491 visitBinary(I, ISD::MUL, ISD::FMUL, ISD::VMUL);
Chris Lattner6f3b5772005-09-28 22:28:18 +0000492 }
Chris Lattner7a60d912005-01-07 07:47:53 +0000493 void visitDiv(User &I) {
Chris Lattner6f3b5772005-09-28 22:28:18 +0000494 const Type *Ty = I.getType();
Nate Begemanb2e089c2005-11-19 00:36:38 +0000495 visitBinary(I, Ty->isSigned() ? ISD::SDIV : ISD::UDIV, ISD::FDIV, 0);
Chris Lattner7a60d912005-01-07 07:47:53 +0000496 }
497 void visitRem(User &I) {
Chris Lattner6f3b5772005-09-28 22:28:18 +0000498 const Type *Ty = I.getType();
Nate Begemanb2e089c2005-11-19 00:36:38 +0000499 visitBinary(I, Ty->isSigned() ? ISD::SREM : ISD::UREM, ISD::FREM, 0);
Chris Lattner7a60d912005-01-07 07:47:53 +0000500 }
Nate Begemanb2e089c2005-11-19 00:36:38 +0000501 void visitAnd(User &I) { visitBinary(I, ISD::AND, 0, 0); }
502 void visitOr (User &I) { visitBinary(I, ISD::OR, 0, 0); }
503 void visitXor(User &I) { visitBinary(I, ISD::XOR, 0, 0); }
Nate Begeman127321b2005-11-18 07:42:56 +0000504 void visitShl(User &I) { visitShift(I, ISD::SHL); }
505 void visitShr(User &I) {
506 visitShift(I, I.getType()->isUnsigned() ? ISD::SRL : ISD::SRA);
Chris Lattner7a60d912005-01-07 07:47:53 +0000507 }
508
509 void visitSetCC(User &I, ISD::CondCode SignedOpc, ISD::CondCode UnsignedOpc);
510 void visitSetEQ(User &I) { visitSetCC(I, ISD::SETEQ, ISD::SETEQ); }
511 void visitSetNE(User &I) { visitSetCC(I, ISD::SETNE, ISD::SETNE); }
512 void visitSetLE(User &I) { visitSetCC(I, ISD::SETLE, ISD::SETULE); }
513 void visitSetGE(User &I) { visitSetCC(I, ISD::SETGE, ISD::SETUGE); }
514 void visitSetLT(User &I) { visitSetCC(I, ISD::SETLT, ISD::SETULT); }
515 void visitSetGT(User &I) { visitSetCC(I, ISD::SETGT, ISD::SETUGT); }
516
517 void visitGetElementPtr(User &I);
518 void visitCast(User &I);
519 void visitSelect(User &I);
520 //
521
522 void visitMalloc(MallocInst &I);
523 void visitFree(FreeInst &I);
524 void visitAlloca(AllocaInst &I);
525 void visitLoad(LoadInst &I);
526 void visitStore(StoreInst &I);
527 void visitPHI(PHINode &I) { } // PHI nodes are handled specially.
528 void visitCall(CallInst &I);
Chris Lattner476e67b2006-01-26 22:24:51 +0000529 void visitInlineAsm(CallInst &I);
Chris Lattnercd6f0f42005-11-09 19:44:01 +0000530 const char *visitIntrinsicCall(CallInst &I, unsigned Intrinsic);
Chris Lattner7a60d912005-01-07 07:47:53 +0000531
Chris Lattner7a60d912005-01-07 07:47:53 +0000532 void visitVAStart(CallInst &I);
Chris Lattner7a60d912005-01-07 07:47:53 +0000533 void visitVAArg(VAArgInst &I);
534 void visitVAEnd(CallInst &I);
535 void visitVACopy(CallInst &I);
Chris Lattner58cfd792005-01-09 00:00:49 +0000536 void visitFrameReturnAddress(CallInst &I, bool isFrameAddress);
Chris Lattner7a60d912005-01-07 07:47:53 +0000537
Chris Lattner875def92005-01-11 05:56:49 +0000538 void visitMemIntrinsic(CallInst &I, unsigned Op);
Chris Lattner7a60d912005-01-07 07:47:53 +0000539
540 void visitUserOp1(Instruction &I) {
541 assert(0 && "UserOp1 should not exist at instruction selection time!");
542 abort();
543 }
544 void visitUserOp2(Instruction &I) {
545 assert(0 && "UserOp2 should not exist at instruction selection time!");
546 abort();
547 }
548};
549} // end namespace llvm
550
551void SelectionDAGLowering::visitRet(ReturnInst &I) {
552 if (I.getNumOperands() == 0) {
Chris Lattner4108bb02005-01-17 19:43:36 +0000553 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getRoot()));
Chris Lattner7a60d912005-01-07 07:47:53 +0000554 return;
555 }
Nate Begeman8c47c3a2006-01-27 21:09:22 +0000556 std::vector<SDOperand> NewValues;
557 NewValues.push_back(getRoot());
558 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
559 SDOperand RetOp = getValue(I.getOperand(i));
560
561 // If this is an integer return value, we need to promote it ourselves to
562 // the full width of a register, since LegalizeOp will use ANY_EXTEND rather
563 // than sign/zero.
564 if (MVT::isInteger(RetOp.getValueType()) &&
565 RetOp.getValueType() < MVT::i64) {
566 MVT::ValueType TmpVT;
567 if (TLI.getTypeAction(MVT::i32) == TargetLowering::Promote)
568 TmpVT = TLI.getTypeToTransformTo(MVT::i32);
569 else
570 TmpVT = MVT::i32;
Chris Lattner7a60d912005-01-07 07:47:53 +0000571
Nate Begeman8c47c3a2006-01-27 21:09:22 +0000572 if (I.getOperand(i)->getType()->isSigned())
573 RetOp = DAG.getNode(ISD::SIGN_EXTEND, TmpVT, RetOp);
574 else
575 RetOp = DAG.getNode(ISD::ZERO_EXTEND, TmpVT, RetOp);
576 }
577 NewValues.push_back(RetOp);
Chris Lattner7a60d912005-01-07 07:47:53 +0000578 }
Nate Begeman8c47c3a2006-01-27 21:09:22 +0000579 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, NewValues));
Chris Lattner7a60d912005-01-07 07:47:53 +0000580}
581
582void SelectionDAGLowering::visitBr(BranchInst &I) {
583 // Update machine-CFG edges.
584 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
Chris Lattner7a60d912005-01-07 07:47:53 +0000585
586 // Figure out which block is immediately after the current one.
587 MachineBasicBlock *NextBlock = 0;
588 MachineFunction::iterator BBI = CurMBB;
589 if (++BBI != CurMBB->getParent()->end())
590 NextBlock = BBI;
591
592 if (I.isUnconditional()) {
593 // If this is not a fall-through branch, emit the branch.
594 if (Succ0MBB != NextBlock)
Chris Lattner4108bb02005-01-17 19:43:36 +0000595 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
Misha Brukman77451162005-04-22 04:01:18 +0000596 DAG.getBasicBlock(Succ0MBB)));
Chris Lattner7a60d912005-01-07 07:47:53 +0000597 } else {
598 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
Chris Lattner7a60d912005-01-07 07:47:53 +0000599
600 SDOperand Cond = getValue(I.getCondition());
Chris Lattner7a60d912005-01-07 07:47:53 +0000601 if (Succ1MBB == NextBlock) {
602 // If the condition is false, fall through. This means we should branch
603 // if the condition is true to Succ #0.
Chris Lattner4108bb02005-01-17 19:43:36 +0000604 DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(),
Misha Brukman77451162005-04-22 04:01:18 +0000605 Cond, DAG.getBasicBlock(Succ0MBB)));
Chris Lattner7a60d912005-01-07 07:47:53 +0000606 } else if (Succ0MBB == NextBlock) {
607 // If the condition is true, fall through. This means we should branch if
608 // the condition is false to Succ #1. Invert the condition first.
609 SDOperand True = DAG.getConstant(1, Cond.getValueType());
610 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
Chris Lattner4108bb02005-01-17 19:43:36 +0000611 DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(),
Misha Brukman77451162005-04-22 04:01:18 +0000612 Cond, DAG.getBasicBlock(Succ1MBB)));
Chris Lattner7a60d912005-01-07 07:47:53 +0000613 } else {
Chris Lattner8a98c7f2005-04-09 03:30:29 +0000614 std::vector<SDOperand> Ops;
615 Ops.push_back(getRoot());
Evan Cheng42c01c82006-02-16 08:27:56 +0000616 // If the false case is the current basic block, then this is a self
617 // loop. We do not want to emit "Loop: ... brcond Out; br Loop", as it
618 // adds an extra instruction in the loop. Instead, invert the
619 // condition and emit "Loop: ... br!cond Loop; br Out.
620 if (CurMBB == Succ1MBB) {
621 std::swap(Succ0MBB, Succ1MBB);
622 SDOperand True = DAG.getConstant(1, Cond.getValueType());
623 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
624 }
Chris Lattner8a98c7f2005-04-09 03:30:29 +0000625 Ops.push_back(Cond);
626 Ops.push_back(DAG.getBasicBlock(Succ0MBB));
627 Ops.push_back(DAG.getBasicBlock(Succ1MBB));
628 DAG.setRoot(DAG.getNode(ISD::BRCONDTWOWAY, MVT::Other, Ops));
Chris Lattner7a60d912005-01-07 07:47:53 +0000629 }
630 }
631}
632
Chris Lattnerf68fd0b2005-04-02 05:04:50 +0000633void SelectionDAGLowering::visitSub(User &I) {
634 // -0.0 - X --> fneg
Chris Lattner6f3b5772005-09-28 22:28:18 +0000635 if (I.getType()->isFloatingPoint()) {
636 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
637 if (CFP->isExactlyValue(-0.0)) {
638 SDOperand Op2 = getValue(I.getOperand(1));
639 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
640 return;
641 }
Chris Lattner6f3b5772005-09-28 22:28:18 +0000642 }
Nate Begemanb2e089c2005-11-19 00:36:38 +0000643 visitBinary(I, ISD::SUB, ISD::FSUB, ISD::VSUB);
Chris Lattnerf68fd0b2005-04-02 05:04:50 +0000644}
645
Nate Begemanb2e089c2005-11-19 00:36:38 +0000646void SelectionDAGLowering::visitBinary(User &I, unsigned IntOp, unsigned FPOp,
647 unsigned VecOp) {
648 const Type *Ty = I.getType();
Chris Lattner7a60d912005-01-07 07:47:53 +0000649 SDOperand Op1 = getValue(I.getOperand(0));
650 SDOperand Op2 = getValue(I.getOperand(1));
Chris Lattner96c26752005-01-19 22:31:21 +0000651
Chris Lattner19baba62005-11-19 18:40:42 +0000652 if (Ty->isIntegral()) {
Nate Begemanb2e089c2005-11-19 00:36:38 +0000653 setValue(&I, DAG.getNode(IntOp, Op1.getValueType(), Op1, Op2));
654 } else if (Ty->isFloatingPoint()) {
655 setValue(&I, DAG.getNode(FPOp, Op1.getValueType(), Op1, Op2));
656 } else {
657 const PackedType *PTy = cast<PackedType>(Ty);
Nate Begeman07890bb2005-11-22 01:29:36 +0000658 unsigned NumElements = PTy->getNumElements();
659 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
Nate Begeman1064d6e2005-11-30 08:22:07 +0000660 MVT::ValueType TVT = MVT::getVectorType(PVT, NumElements);
Nate Begeman07890bb2005-11-22 01:29:36 +0000661
662 // Immediately scalarize packed types containing only one element, so that
Nate Begeman1064d6e2005-11-30 08:22:07 +0000663 // the Legalize pass does not have to deal with them. Similarly, if the
664 // abstract vector is going to turn into one that the target natively
665 // supports, generate that type now so that Legalize doesn't have to deal
666 // with that either. These steps ensure that Legalize only has to handle
667 // vector types in its Expand case.
668 unsigned Opc = MVT::isFloatingPoint(PVT) ? FPOp : IntOp;
Nate Begeman07890bb2005-11-22 01:29:36 +0000669 if (NumElements == 1) {
Nate Begeman07890bb2005-11-22 01:29:36 +0000670 setValue(&I, DAG.getNode(Opc, PVT, Op1, Op2));
Nate Begeman1064d6e2005-11-30 08:22:07 +0000671 } else if (TVT != MVT::Other && TLI.isTypeLegal(TVT)) {
672 setValue(&I, DAG.getNode(Opc, TVT, Op1, Op2));
Nate Begeman07890bb2005-11-22 01:29:36 +0000673 } else {
674 SDOperand Num = DAG.getConstant(NumElements, MVT::i32);
675 SDOperand Typ = DAG.getValueType(PVT);
Nate Begemand37c1312005-11-22 18:16:00 +0000676 setValue(&I, DAG.getNode(VecOp, MVT::Vector, Op1, Op2, Num, Typ));
Nate Begeman07890bb2005-11-22 01:29:36 +0000677 }
Nate Begemanb2e089c2005-11-19 00:36:38 +0000678 }
Nate Begeman127321b2005-11-18 07:42:56 +0000679}
Chris Lattner96c26752005-01-19 22:31:21 +0000680
Nate Begeman127321b2005-11-18 07:42:56 +0000681void SelectionDAGLowering::visitShift(User &I, unsigned Opcode) {
682 SDOperand Op1 = getValue(I.getOperand(0));
683 SDOperand Op2 = getValue(I.getOperand(1));
684
685 Op2 = DAG.getNode(ISD::ANY_EXTEND, TLI.getShiftAmountTy(), Op2);
686
Chris Lattner7a60d912005-01-07 07:47:53 +0000687 setValue(&I, DAG.getNode(Opcode, Op1.getValueType(), Op1, Op2));
688}
689
690void SelectionDAGLowering::visitSetCC(User &I,ISD::CondCode SignedOpcode,
691 ISD::CondCode UnsignedOpcode) {
692 SDOperand Op1 = getValue(I.getOperand(0));
693 SDOperand Op2 = getValue(I.getOperand(1));
694 ISD::CondCode Opcode = SignedOpcode;
695 if (I.getOperand(0)->getType()->isUnsigned())
696 Opcode = UnsignedOpcode;
Chris Lattnerd47675e2005-08-09 20:20:18 +0000697 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Opcode));
Chris Lattner7a60d912005-01-07 07:47:53 +0000698}
699
700void SelectionDAGLowering::visitSelect(User &I) {
701 SDOperand Cond = getValue(I.getOperand(0));
702 SDOperand TrueVal = getValue(I.getOperand(1));
703 SDOperand FalseVal = getValue(I.getOperand(2));
704 setValue(&I, DAG.getNode(ISD::SELECT, TrueVal.getValueType(), Cond,
705 TrueVal, FalseVal));
706}
707
708void SelectionDAGLowering::visitCast(User &I) {
709 SDOperand N = getValue(I.getOperand(0));
710 MVT::ValueType SrcTy = TLI.getValueType(I.getOperand(0)->getType());
711 MVT::ValueType DestTy = TLI.getValueType(I.getType());
712
713 if (N.getValueType() == DestTy) {
714 setValue(&I, N); // noop cast.
Chris Lattner2d8b55c2005-05-09 22:17:13 +0000715 } else if (DestTy == MVT::i1) {
716 // Cast to bool is a comparison against zero, not truncation to zero.
717 SDOperand Zero = isInteger(SrcTy) ? DAG.getConstant(0, N.getValueType()) :
718 DAG.getConstantFP(0.0, N.getValueType());
Chris Lattnerd47675e2005-08-09 20:20:18 +0000719 setValue(&I, DAG.getSetCC(MVT::i1, N, Zero, ISD::SETNE));
Chris Lattner2a6db3c2005-01-08 08:08:56 +0000720 } else if (isInteger(SrcTy)) {
721 if (isInteger(DestTy)) { // Int -> Int cast
722 if (DestTy < SrcTy) // Truncating cast?
723 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestTy, N));
724 else if (I.getOperand(0)->getType()->isSigned())
725 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, DestTy, N));
726 else
727 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestTy, N));
728 } else { // Int -> FP cast
729 if (I.getOperand(0)->getType()->isSigned())
730 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, DestTy, N));
731 else
732 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, DestTy, N));
733 }
Chris Lattner7a60d912005-01-07 07:47:53 +0000734 } else {
Chris Lattner2a6db3c2005-01-08 08:08:56 +0000735 assert(isFloatingPoint(SrcTy) && "Unknown value type!");
736 if (isFloatingPoint(DestTy)) { // FP -> FP cast
737 if (DestTy < SrcTy) // Rounding cast?
738 setValue(&I, DAG.getNode(ISD::FP_ROUND, DestTy, N));
739 else
740 setValue(&I, DAG.getNode(ISD::FP_EXTEND, DestTy, N));
741 } else { // FP -> Int cast.
742 if (I.getType()->isSigned())
743 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, DestTy, N));
744 else
745 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, DestTy, N));
746 }
Chris Lattner7a60d912005-01-07 07:47:53 +0000747 }
748}
749
750void SelectionDAGLowering::visitGetElementPtr(User &I) {
751 SDOperand N = getValue(I.getOperand(0));
752 const Type *Ty = I.getOperand(0)->getType();
753 const Type *UIntPtrTy = TD.getIntPtrType();
754
755 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
756 OI != E; ++OI) {
757 Value *Idx = *OI;
Chris Lattner35397782005-12-05 07:10:48 +0000758 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
Chris Lattner7a60d912005-01-07 07:47:53 +0000759 unsigned Field = cast<ConstantUInt>(Idx)->getValue();
760 if (Field) {
761 // N = N + Offset
762 uint64_t Offset = TD.getStructLayout(StTy)->MemberOffsets[Field];
763 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
Misha Brukman77451162005-04-22 04:01:18 +0000764 getIntPtrConstant(Offset));
Chris Lattner7a60d912005-01-07 07:47:53 +0000765 }
766 Ty = StTy->getElementType(Field);
767 } else {
768 Ty = cast<SequentialType>(Ty)->getElementType();
Chris Lattner19a83992005-01-07 21:56:57 +0000769
Chris Lattner43535a12005-11-09 04:45:33 +0000770 // If this is a constant subscript, handle it quickly.
771 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
772 if (CI->getRawValue() == 0) continue;
Chris Lattner19a83992005-01-07 21:56:57 +0000773
Chris Lattner43535a12005-11-09 04:45:33 +0000774 uint64_t Offs;
775 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(CI))
776 Offs = (int64_t)TD.getTypeSize(Ty)*CSI->getValue();
777 else
778 Offs = TD.getTypeSize(Ty)*cast<ConstantUInt>(CI)->getValue();
779 N = DAG.getNode(ISD::ADD, N.getValueType(), N, getIntPtrConstant(Offs));
780 continue;
Chris Lattner7a60d912005-01-07 07:47:53 +0000781 }
Chris Lattner43535a12005-11-09 04:45:33 +0000782
783 // N = N + Idx * ElementSize;
784 uint64_t ElementSize = TD.getTypeSize(Ty);
785 SDOperand IdxN = getValue(Idx);
786
787 // If the index is smaller or larger than intptr_t, truncate or extend
788 // it.
789 if (IdxN.getValueType() < N.getValueType()) {
790 if (Idx->getType()->isSigned())
791 IdxN = DAG.getNode(ISD::SIGN_EXTEND, N.getValueType(), IdxN);
792 else
793 IdxN = DAG.getNode(ISD::ZERO_EXTEND, N.getValueType(), IdxN);
794 } else if (IdxN.getValueType() > N.getValueType())
795 IdxN = DAG.getNode(ISD::TRUNCATE, N.getValueType(), IdxN);
796
797 // If this is a multiply by a power of two, turn it into a shl
798 // immediately. This is a very common case.
799 if (isPowerOf2_64(ElementSize)) {
800 unsigned Amt = Log2_64(ElementSize);
801 IdxN = DAG.getNode(ISD::SHL, N.getValueType(), IdxN,
Chris Lattner41fd6d52005-11-09 16:50:40 +0000802 DAG.getConstant(Amt, TLI.getShiftAmountTy()));
Chris Lattner43535a12005-11-09 04:45:33 +0000803 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
804 continue;
805 }
806
807 SDOperand Scale = getIntPtrConstant(ElementSize);
808 IdxN = DAG.getNode(ISD::MUL, N.getValueType(), IdxN, Scale);
809 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
Chris Lattner7a60d912005-01-07 07:47:53 +0000810 }
811 }
812 setValue(&I, N);
813}
814
815void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
816 // If this is a fixed sized alloca in the entry block of the function,
817 // allocate it statically on the stack.
818 if (FuncInfo.StaticAllocaMap.count(&I))
819 return; // getValue will auto-populate this.
820
821 const Type *Ty = I.getAllocatedType();
822 uint64_t TySize = TLI.getTargetData().getTypeSize(Ty);
Nate Begeman3ee3e692005-11-06 09:00:38 +0000823 unsigned Align = std::max((unsigned)TLI.getTargetData().getTypeAlignment(Ty),
824 I.getAlignment());
Chris Lattner7a60d912005-01-07 07:47:53 +0000825
826 SDOperand AllocSize = getValue(I.getArraySize());
Chris Lattnereccb73d2005-01-22 23:04:37 +0000827 MVT::ValueType IntPtr = TLI.getPointerTy();
828 if (IntPtr < AllocSize.getValueType())
829 AllocSize = DAG.getNode(ISD::TRUNCATE, IntPtr, AllocSize);
830 else if (IntPtr > AllocSize.getValueType())
831 AllocSize = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, AllocSize);
Chris Lattner7a60d912005-01-07 07:47:53 +0000832
Chris Lattnereccb73d2005-01-22 23:04:37 +0000833 AllocSize = DAG.getNode(ISD::MUL, IntPtr, AllocSize,
Chris Lattner7a60d912005-01-07 07:47:53 +0000834 getIntPtrConstant(TySize));
835
836 // Handle alignment. If the requested alignment is less than or equal to the
837 // stack alignment, ignore it and round the size of the allocation up to the
838 // stack alignment size. If the size is greater than the stack alignment, we
839 // note this in the DYNAMIC_STACKALLOC node.
840 unsigned StackAlign =
841 TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
842 if (Align <= StackAlign) {
843 Align = 0;
844 // Add SA-1 to the size.
845 AllocSize = DAG.getNode(ISD::ADD, AllocSize.getValueType(), AllocSize,
846 getIntPtrConstant(StackAlign-1));
847 // Mask out the low bits for alignment purposes.
848 AllocSize = DAG.getNode(ISD::AND, AllocSize.getValueType(), AllocSize,
849 getIntPtrConstant(~(uint64_t)(StackAlign-1)));
850 }
851
Chris Lattner96c262e2005-05-14 07:29:57 +0000852 std::vector<MVT::ValueType> VTs;
853 VTs.push_back(AllocSize.getValueType());
854 VTs.push_back(MVT::Other);
855 std::vector<SDOperand> Ops;
856 Ops.push_back(getRoot());
857 Ops.push_back(AllocSize);
858 Ops.push_back(getIntPtrConstant(Align));
859 SDOperand DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, VTs, Ops);
Chris Lattner7a60d912005-01-07 07:47:53 +0000860 DAG.setRoot(setValue(&I, DSA).getValue(1));
861
862 // Inform the Frame Information that we have just allocated a variable-sized
863 // object.
864 CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
865}
866
Chris Lattner435b4022005-11-29 06:21:05 +0000867/// getStringValue - Turn an LLVM constant pointer that eventually points to a
868/// global into a string value. Return an empty string if we can't do it.
869///
Evan Cheng6781b6e2006-02-15 21:59:04 +0000870static std::string getStringValue(GlobalVariable *GV, unsigned Offset = 0) {
871 if (GV->hasInitializer() && isa<ConstantArray>(GV->getInitializer())) {
872 ConstantArray *Init = cast<ConstantArray>(GV->getInitializer());
873 if (Init->isString()) {
874 std::string Result = Init->getAsString();
875 if (Offset < Result.size()) {
876 // If we are pointing INTO The string, erase the beginning...
877 Result.erase(Result.begin(), Result.begin()+Offset);
878 return Result;
Chris Lattner435b4022005-11-29 06:21:05 +0000879 }
880 }
881 }
882 return "";
883}
Chris Lattner7a60d912005-01-07 07:47:53 +0000884
885void SelectionDAGLowering::visitLoad(LoadInst &I) {
886 SDOperand Ptr = getValue(I.getOperand(0));
Misha Brukman835702a2005-04-21 22:36:52 +0000887
Chris Lattner4d9651c2005-01-17 22:19:26 +0000888 SDOperand Root;
889 if (I.isVolatile())
890 Root = getRoot();
891 else {
892 // Do not serialize non-volatile loads against each other.
893 Root = DAG.getRoot();
894 }
Nate Begemanb2e089c2005-11-19 00:36:38 +0000895
896 const Type *Ty = I.getType();
897 SDOperand L;
898
Nate Begeman41b1cdc2005-12-06 06:18:55 +0000899 if (const PackedType *PTy = dyn_cast<PackedType>(Ty)) {
Nate Begeman07890bb2005-11-22 01:29:36 +0000900 unsigned NumElements = PTy->getNumElements();
901 MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
Nate Begeman1064d6e2005-11-30 08:22:07 +0000902 MVT::ValueType TVT = MVT::getVectorType(PVT, NumElements);
Nate Begeman07890bb2005-11-22 01:29:36 +0000903
904 // Immediately scalarize packed types containing only one element, so that
905 // the Legalize pass does not have to deal with them.
906 if (NumElements == 1) {
907 L = DAG.getLoad(PVT, Root, Ptr, DAG.getSrcValue(I.getOperand(0)));
Nate Begeman1064d6e2005-11-30 08:22:07 +0000908 } else if (TVT != MVT::Other && TLI.isTypeLegal(TVT)) {
909 L = DAG.getLoad(TVT, Root, Ptr, DAG.getSrcValue(I.getOperand(0)));
Nate Begeman07890bb2005-11-22 01:29:36 +0000910 } else {
911 L = DAG.getVecLoad(NumElements, PVT, Root, Ptr,
912 DAG.getSrcValue(I.getOperand(0)));
913 }
Nate Begemanb2e089c2005-11-19 00:36:38 +0000914 } else {
915 L = DAG.getLoad(TLI.getValueType(Ty), Root, Ptr,
916 DAG.getSrcValue(I.getOperand(0)));
917 }
Chris Lattner4d9651c2005-01-17 22:19:26 +0000918 setValue(&I, L);
919
920 if (I.isVolatile())
921 DAG.setRoot(L.getValue(1));
922 else
923 PendingLoads.push_back(L.getValue(1));
Chris Lattner7a60d912005-01-07 07:47:53 +0000924}
925
926
927void SelectionDAGLowering::visitStore(StoreInst &I) {
928 Value *SrcV = I.getOperand(0);
929 SDOperand Src = getValue(SrcV);
930 SDOperand Ptr = getValue(I.getOperand(1));
Chris Lattnerf5675a02005-05-09 04:08:33 +0000931 DAG.setRoot(DAG.getNode(ISD::STORE, MVT::Other, getRoot(), Src, Ptr,
Andrew Lenharth2edc1882005-06-29 18:54:02 +0000932 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner7a60d912005-01-07 07:47:53 +0000933}
934
Chris Lattnercd6f0f42005-11-09 19:44:01 +0000935/// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
936/// we want to emit this as a call to a named external function, return the name
937/// otherwise lower it and return null.
938const char *
939SelectionDAGLowering::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
940 switch (Intrinsic) {
941 case Intrinsic::vastart: visitVAStart(I); return 0;
942 case Intrinsic::vaend: visitVAEnd(I); return 0;
943 case Intrinsic::vacopy: visitVACopy(I); return 0;
944 case Intrinsic::returnaddress: visitFrameReturnAddress(I, false); return 0;
945 case Intrinsic::frameaddress: visitFrameReturnAddress(I, true); return 0;
946 case Intrinsic::setjmp:
947 return "_setjmp"+!TLI.usesUnderscoreSetJmpLongJmp();
948 break;
949 case Intrinsic::longjmp:
950 return "_longjmp"+!TLI.usesUnderscoreSetJmpLongJmp();
951 break;
952 case Intrinsic::memcpy: visitMemIntrinsic(I, ISD::MEMCPY); return 0;
953 case Intrinsic::memset: visitMemIntrinsic(I, ISD::MEMSET); return 0;
954 case Intrinsic::memmove: visitMemIntrinsic(I, ISD::MEMMOVE); return 0;
955
956 case Intrinsic::readport:
957 case Intrinsic::readio: {
958 std::vector<MVT::ValueType> VTs;
959 VTs.push_back(TLI.getValueType(I.getType()));
960 VTs.push_back(MVT::Other);
961 std::vector<SDOperand> Ops;
962 Ops.push_back(getRoot());
963 Ops.push_back(getValue(I.getOperand(1)));
964 SDOperand Tmp = DAG.getNode(Intrinsic == Intrinsic::readport ?
965 ISD::READPORT : ISD::READIO, VTs, Ops);
966
967 setValue(&I, Tmp);
968 DAG.setRoot(Tmp.getValue(1));
969 return 0;
970 }
971 case Intrinsic::writeport:
972 case Intrinsic::writeio:
973 DAG.setRoot(DAG.getNode(Intrinsic == Intrinsic::writeport ?
974 ISD::WRITEPORT : ISD::WRITEIO, MVT::Other,
975 getRoot(), getValue(I.getOperand(1)),
976 getValue(I.getOperand(2))));
977 return 0;
Chris Lattnerf2b62f32005-11-16 07:22:30 +0000978
Chris Lattner5d4e61d2005-12-13 17:40:33 +0000979 case Intrinsic::dbg_stoppoint: {
Chris Lattnerf2b62f32005-11-16 07:22:30 +0000980 if (TLI.getTargetMachine().getIntrinsicLowering().EmitDebugFunctions())
981 return "llvm_debugger_stop";
Chris Lattner435b4022005-11-29 06:21:05 +0000982
Jim Laskey5995d012006-02-11 01:01:30 +0000983 MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
984 if (DebugInfo && DebugInfo->Verify(I.getOperand(4))) {
985 std::vector<SDOperand> Ops;
Chris Lattner435b4022005-11-29 06:21:05 +0000986
Jim Laskey5995d012006-02-11 01:01:30 +0000987 // Input Chain
988 Ops.push_back(getRoot());
989
990 // line number
991 Ops.push_back(getValue(I.getOperand(2)));
992
993 // column
994 Ops.push_back(getValue(I.getOperand(3)));
Chris Lattner435b4022005-11-29 06:21:05 +0000995
Jim Laskey390c63e2006-02-13 12:50:39 +0000996 DebugInfoDesc *DD = DebugInfo->getDescFor(I.getOperand(4));
Jim Laskey5995d012006-02-11 01:01:30 +0000997 assert(DD && "Not a debug information descriptor");
998 CompileUnitDesc *CompileUnit = dyn_cast<CompileUnitDesc>(DD);
999 assert(CompileUnit && "Not a compile unit");
1000 Ops.push_back(DAG.getString(CompileUnit->getFileName()));
1001 Ops.push_back(DAG.getString(CompileUnit->getDirectory()));
1002
1003 if (Ops.size() == 5) // Found filename/workingdir.
1004 DAG.setRoot(DAG.getNode(ISD::LOCATION, MVT::Other, Ops));
Chris Lattner5d4e61d2005-12-13 17:40:33 +00001005 }
1006
Chris Lattner8782b782005-12-03 18:50:48 +00001007 setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())));
Chris Lattnerf2b62f32005-11-16 07:22:30 +00001008 return 0;
Chris Lattner435b4022005-11-29 06:21:05 +00001009 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001010 case Intrinsic::dbg_region_start:
Chris Lattnerf2b62f32005-11-16 07:22:30 +00001011 if (TLI.getTargetMachine().getIntrinsicLowering().EmitDebugFunctions())
1012 return "llvm_dbg_region_start";
1013 if (I.getType() != Type::VoidTy)
1014 setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())));
1015 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001016 case Intrinsic::dbg_region_end:
Chris Lattnerf2b62f32005-11-16 07:22:30 +00001017 if (TLI.getTargetMachine().getIntrinsicLowering().EmitDebugFunctions())
1018 return "llvm_dbg_region_end";
1019 if (I.getType() != Type::VoidTy)
1020 setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())));
1021 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001022 case Intrinsic::dbg_func_start:
Chris Lattnerf2b62f32005-11-16 07:22:30 +00001023 if (TLI.getTargetMachine().getIntrinsicLowering().EmitDebugFunctions())
1024 return "llvm_dbg_subprogram";
1025 if (I.getType() != Type::VoidTy)
1026 setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())));
1027 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001028 case Intrinsic::dbg_declare:
1029 if (I.getType() != Type::VoidTy)
1030 setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())));
1031 return 0;
1032
Reid Spencerb4f9a6f2006-01-16 21:12:35 +00001033 case Intrinsic::isunordered_f32:
1034 case Intrinsic::isunordered_f64:
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001035 setValue(&I, DAG.getSetCC(MVT::i1,getValue(I.getOperand(1)),
1036 getValue(I.getOperand(2)), ISD::SETUO));
1037 return 0;
1038
Reid Spencerb4f9a6f2006-01-16 21:12:35 +00001039 case Intrinsic::sqrt_f32:
1040 case Intrinsic::sqrt_f64:
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001041 setValue(&I, DAG.getNode(ISD::FSQRT,
1042 getValue(I.getOperand(1)).getValueType(),
1043 getValue(I.getOperand(1))));
1044 return 0;
1045 case Intrinsic::pcmarker: {
1046 SDOperand Tmp = getValue(I.getOperand(1));
1047 DAG.setRoot(DAG.getNode(ISD::PCMARKER, MVT::Other, getRoot(), Tmp));
1048 return 0;
1049 }
Andrew Lenharthde1b5d62005-11-11 22:48:54 +00001050 case Intrinsic::readcyclecounter: {
1051 std::vector<MVT::ValueType> VTs;
1052 VTs.push_back(MVT::i64);
1053 VTs.push_back(MVT::Other);
1054 std::vector<SDOperand> Ops;
1055 Ops.push_back(getRoot());
1056 SDOperand Tmp = DAG.getNode(ISD::READCYCLECOUNTER, VTs, Ops);
1057 setValue(&I, Tmp);
1058 DAG.setRoot(Tmp.getValue(1));
Andrew Lenharth01aa5632005-11-11 16:47:30 +00001059 return 0;
Andrew Lenharthde1b5d62005-11-11 22:48:54 +00001060 }
Nate Begeman2fba8a32006-01-14 03:14:10 +00001061 case Intrinsic::bswap_i16:
Nate Begeman2fba8a32006-01-14 03:14:10 +00001062 case Intrinsic::bswap_i32:
Nate Begeman2fba8a32006-01-14 03:14:10 +00001063 case Intrinsic::bswap_i64:
1064 setValue(&I, DAG.getNode(ISD::BSWAP,
1065 getValue(I.getOperand(1)).getValueType(),
1066 getValue(I.getOperand(1))));
1067 return 0;
Reid Spencerb4f9a6f2006-01-16 21:12:35 +00001068 case Intrinsic::cttz_i8:
1069 case Intrinsic::cttz_i16:
1070 case Intrinsic::cttz_i32:
1071 case Intrinsic::cttz_i64:
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001072 setValue(&I, DAG.getNode(ISD::CTTZ,
1073 getValue(I.getOperand(1)).getValueType(),
1074 getValue(I.getOperand(1))));
1075 return 0;
Reid Spencerb4f9a6f2006-01-16 21:12:35 +00001076 case Intrinsic::ctlz_i8:
1077 case Intrinsic::ctlz_i16:
1078 case Intrinsic::ctlz_i32:
1079 case Intrinsic::ctlz_i64:
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001080 setValue(&I, DAG.getNode(ISD::CTLZ,
1081 getValue(I.getOperand(1)).getValueType(),
1082 getValue(I.getOperand(1))));
1083 return 0;
Reid Spencerb4f9a6f2006-01-16 21:12:35 +00001084 case Intrinsic::ctpop_i8:
1085 case Intrinsic::ctpop_i16:
1086 case Intrinsic::ctpop_i32:
1087 case Intrinsic::ctpop_i64:
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001088 setValue(&I, DAG.getNode(ISD::CTPOP,
1089 getValue(I.getOperand(1)).getValueType(),
1090 getValue(I.getOperand(1))));
1091 return 0;
Chris Lattnerb3266452006-01-13 02:50:02 +00001092 case Intrinsic::stacksave: {
1093 std::vector<MVT::ValueType> VTs;
1094 VTs.push_back(TLI.getPointerTy());
1095 VTs.push_back(MVT::Other);
1096 std::vector<SDOperand> Ops;
1097 Ops.push_back(getRoot());
1098 SDOperand Tmp = DAG.getNode(ISD::STACKSAVE, VTs, Ops);
1099 setValue(&I, Tmp);
1100 DAG.setRoot(Tmp.getValue(1));
1101 return 0;
1102 }
Chris Lattnerdeda32a2006-01-23 05:22:07 +00001103 case Intrinsic::stackrestore: {
1104 SDOperand Tmp = getValue(I.getOperand(1));
1105 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, MVT::Other, getRoot(), Tmp));
Chris Lattnerb3266452006-01-13 02:50:02 +00001106 return 0;
Chris Lattnerdeda32a2006-01-23 05:22:07 +00001107 }
Chris Lattner9e8b6332005-12-12 22:51:16 +00001108 case Intrinsic::prefetch:
1109 // FIXME: Currently discarding prefetches.
1110 return 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001111 default:
1112 std::cerr << I;
1113 assert(0 && "This intrinsic is not implemented yet!");
1114 return 0;
1115 }
1116}
1117
1118
Chris Lattner7a60d912005-01-07 07:47:53 +00001119void SelectionDAGLowering::visitCall(CallInst &I) {
Chris Lattner18d2b342005-01-08 22:48:57 +00001120 const char *RenameFn = 0;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001121 if (Function *F = I.getCalledFunction()) {
Chris Lattner0c140002005-04-02 05:26:53 +00001122 if (F->isExternal())
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001123 if (unsigned IID = F->getIntrinsicID()) {
1124 RenameFn = visitIntrinsicCall(I, IID);
1125 if (!RenameFn)
1126 return;
1127 } else { // Not an LLVM intrinsic.
1128 const std::string &Name = F->getName();
1129 if (Name[0] == 'f' && (Name == "fabs" || Name == "fabsf")) {
Chris Lattner0c140002005-04-02 05:26:53 +00001130 if (I.getNumOperands() == 2 && // Basic sanity checks.
1131 I.getOperand(1)->getType()->isFloatingPoint() &&
1132 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001133 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattner0c140002005-04-02 05:26:53 +00001134 setValue(&I, DAG.getNode(ISD::FABS, Tmp.getValueType(), Tmp));
1135 return;
1136 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001137 } else if (Name[0] == 's' && (Name == "sin" || Name == "sinf")) {
Chris Lattner80026402005-04-30 04:43:14 +00001138 if (I.getNumOperands() == 2 && // Basic sanity checks.
1139 I.getOperand(1)->getType()->isFloatingPoint() &&
Chris Lattner1784a9d22006-02-14 05:39:35 +00001140 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001141 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattner80026402005-04-30 04:43:14 +00001142 setValue(&I, DAG.getNode(ISD::FSIN, Tmp.getValueType(), Tmp));
1143 return;
1144 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001145 } else if (Name[0] == 'c' && (Name == "cos" || Name == "cosf")) {
Chris Lattner80026402005-04-30 04:43:14 +00001146 if (I.getNumOperands() == 2 && // Basic sanity checks.
1147 I.getOperand(1)->getType()->isFloatingPoint() &&
Chris Lattner1784a9d22006-02-14 05:39:35 +00001148 I.getType() == I.getOperand(1)->getType()) {
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001149 SDOperand Tmp = getValue(I.getOperand(1));
Chris Lattner80026402005-04-30 04:43:14 +00001150 setValue(&I, DAG.getNode(ISD::FCOS, Tmp.getValueType(), Tmp));
1151 return;
1152 }
1153 }
Chris Lattnere4f71d02005-05-14 13:56:55 +00001154 }
Chris Lattner476e67b2006-01-26 22:24:51 +00001155 } else if (isa<InlineAsm>(I.getOperand(0))) {
1156 visitInlineAsm(I);
1157 return;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001158 }
Misha Brukman835702a2005-04-21 22:36:52 +00001159
Chris Lattner18d2b342005-01-08 22:48:57 +00001160 SDOperand Callee;
1161 if (!RenameFn)
1162 Callee = getValue(I.getOperand(0));
1163 else
1164 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
Chris Lattner7a60d912005-01-07 07:47:53 +00001165 std::vector<std::pair<SDOperand, const Type*> > Args;
Chris Lattnercd6f0f42005-11-09 19:44:01 +00001166 Args.reserve(I.getNumOperands());
Chris Lattner7a60d912005-01-07 07:47:53 +00001167 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
1168 Value *Arg = I.getOperand(i);
1169 SDOperand ArgNode = getValue(Arg);
1170 Args.push_back(std::make_pair(ArgNode, Arg->getType()));
1171 }
Misha Brukman835702a2005-04-21 22:36:52 +00001172
Nate Begemanf6565252005-03-26 01:29:23 +00001173 const PointerType *PT = cast<PointerType>(I.getCalledValue()->getType());
1174 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
Misha Brukman835702a2005-04-21 22:36:52 +00001175
Chris Lattner1f45cd72005-01-08 19:26:18 +00001176 std::pair<SDOperand,SDOperand> Result =
Chris Lattner111778e2005-05-12 19:56:57 +00001177 TLI.LowerCallTo(getRoot(), I.getType(), FTy->isVarArg(), I.getCallingConv(),
Chris Lattner2e77db62005-05-13 18:50:42 +00001178 I.isTailCall(), Callee, Args, DAG);
Chris Lattner7a60d912005-01-07 07:47:53 +00001179 if (I.getType() != Type::VoidTy)
Chris Lattner1f45cd72005-01-08 19:26:18 +00001180 setValue(&I, Result.first);
1181 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +00001182}
1183
Chris Lattner6f87d182006-02-22 22:37:12 +00001184SDOperand RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00001185 SDOperand &Chain, SDOperand &Flag)const{
Chris Lattner6f87d182006-02-22 22:37:12 +00001186 SDOperand Val = DAG.getCopyFromReg(Chain, Regs[0], RegVT, Flag);
1187 Chain = Val.getValue(1);
1188 Flag = Val.getValue(2);
1189
1190 // If the result was expanded, copy from the top part.
1191 if (Regs.size() > 1) {
1192 assert(Regs.size() == 2 &&
1193 "Cannot expand to more than 2 elts yet!");
1194 SDOperand Hi = DAG.getCopyFromReg(Chain, Regs[1], RegVT, Flag);
1195 Chain = Val.getValue(1);
1196 Flag = Val.getValue(2);
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00001197 if (DAG.getTargetLoweringInfo().isLittleEndian())
1198 return DAG.getNode(ISD::BUILD_PAIR, ValueVT, Val, Hi);
1199 else
1200 return DAG.getNode(ISD::BUILD_PAIR, ValueVT, Hi, Val);
Chris Lattner6f87d182006-02-22 22:37:12 +00001201 }
Chris Lattner1558fc62006-02-01 18:59:47 +00001202
Chris Lattner6f87d182006-02-22 22:37:12 +00001203 // Otherwise, if the return value was promoted, truncate it to the
1204 // appropriate type.
1205 if (RegVT == ValueVT)
1206 return Val;
1207
1208 if (MVT::isInteger(RegVT))
1209 return DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
1210 else
1211 return DAG.getNode(ISD::FP_ROUND, ValueVT, Val);
1212}
1213
Chris Lattner571d9642006-02-23 19:21:04 +00001214/// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
1215/// specified value into the registers specified by this object. This uses
1216/// Chain/Flag as the input and updates them for the output Chain/Flag.
1217void RegsForValue::getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00001218 SDOperand &Chain, SDOperand &Flag) const {
Chris Lattner571d9642006-02-23 19:21:04 +00001219 if (Regs.size() == 1) {
1220 // If there is a single register and the types differ, this must be
1221 // a promotion.
1222 if (RegVT != ValueVT) {
1223 if (MVT::isInteger(RegVT))
1224 Val = DAG.getNode(ISD::ANY_EXTEND, RegVT, Val);
1225 else
1226 Val = DAG.getNode(ISD::FP_EXTEND, RegVT, Val);
1227 }
1228 Chain = DAG.getCopyToReg(Chain, Regs[0], Val, Flag);
1229 Flag = Chain.getValue(1);
1230 } else {
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00001231 std::vector<unsigned> R(Regs);
1232 if (!DAG.getTargetLoweringInfo().isLittleEndian())
1233 std::reverse(R.begin(), R.end());
1234
1235 for (unsigned i = 0, e = R.size(); i != e; ++i) {
Chris Lattner571d9642006-02-23 19:21:04 +00001236 SDOperand Part = DAG.getNode(ISD::EXTRACT_ELEMENT, RegVT, Val,
1237 DAG.getConstant(i, MVT::i32));
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00001238 Chain = DAG.getCopyToReg(Chain, R[i], Part, Flag);
Chris Lattner571d9642006-02-23 19:21:04 +00001239 Flag = Chain.getValue(1);
1240 }
1241 }
1242}
Chris Lattner6f87d182006-02-22 22:37:12 +00001243
Chris Lattner571d9642006-02-23 19:21:04 +00001244/// AddInlineAsmOperands - Add this value to the specified inlineasm node
1245/// operand list. This adds the code marker and includes the number of
1246/// values added into it.
1247void RegsForValue::AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
Chris Lattnere7c0ffb2006-02-23 20:06:57 +00001248 std::vector<SDOperand> &Ops) const {
Chris Lattner571d9642006-02-23 19:21:04 +00001249 Ops.push_back(DAG.getConstant(Code | (Regs.size() << 3), MVT::i32));
1250 for (unsigned i = 0, e = Regs.size(); i != e; ++i)
1251 Ops.push_back(DAG.getRegister(Regs[i], RegVT));
1252}
Chris Lattner6f87d182006-02-22 22:37:12 +00001253
1254/// isAllocatableRegister - If the specified register is safe to allocate,
1255/// i.e. it isn't a stack pointer or some other special register, return the
1256/// register class for the register. Otherwise, return null.
1257static const TargetRegisterClass *
Chris Lattnerb1124f32006-02-22 23:09:03 +00001258isAllocatableRegister(unsigned Reg, MachineFunction &MF,
1259 const TargetLowering &TLI, const MRegisterInfo *MRI) {
1260 for (MRegisterInfo::regclass_iterator RCI = MRI->regclass_begin(),
1261 E = MRI->regclass_end(); RCI != E; ++RCI) {
1262 const TargetRegisterClass *RC = *RCI;
1263 // If none of the the value types for this register class are valid, we
1264 // can't use it. For example, 64-bit reg classes on 32-bit targets.
1265 bool isLegal = false;
1266 for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
1267 I != E; ++I) {
1268 if (TLI.isTypeLegal(*I)) {
1269 isLegal = true;
1270 break;
1271 }
1272 }
1273
1274 if (!isLegal) continue;
1275
Chris Lattner6f87d182006-02-22 22:37:12 +00001276 // NOTE: This isn't ideal. In particular, this might allocate the
1277 // frame pointer in functions that need it (due to them not being taken
1278 // out of allocation, because a variable sized allocation hasn't been seen
1279 // yet). This is a slight code pessimization, but should still work.
Chris Lattnerb1124f32006-02-22 23:09:03 +00001280 for (TargetRegisterClass::iterator I = RC->allocation_order_begin(MF),
1281 E = RC->allocation_order_end(MF); I != E; ++I)
Chris Lattner6f87d182006-02-22 22:37:12 +00001282 if (*I == Reg)
Chris Lattnerb1124f32006-02-22 23:09:03 +00001283 return RC;
Chris Lattner1558fc62006-02-01 18:59:47 +00001284 }
1285 return 0;
Chris Lattner6f87d182006-02-22 22:37:12 +00001286}
1287
1288RegsForValue SelectionDAGLowering::
1289GetRegistersForValue(const std::string &ConstrCode,
1290 MVT::ValueType VT, bool isOutReg, bool isInReg,
1291 std::set<unsigned> &OutputRegs,
1292 std::set<unsigned> &InputRegs) {
1293 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
1294 TLI.getRegForInlineAsmConstraint(ConstrCode, VT);
1295 std::vector<unsigned> Regs;
1296
1297 unsigned NumRegs = VT != MVT::Other ? TLI.getNumElements(VT) : 1;
1298 MVT::ValueType RegVT;
1299 MVT::ValueType ValueVT = VT;
1300
1301 if (PhysReg.first) {
1302 if (VT == MVT::Other)
1303 ValueVT = *PhysReg.second->vt_begin();
1304 RegVT = VT;
1305
1306 // This is a explicit reference to a physical register.
1307 Regs.push_back(PhysReg.first);
1308
1309 // If this is an expanded reference, add the rest of the regs to Regs.
1310 if (NumRegs != 1) {
1311 RegVT = *PhysReg.second->vt_begin();
1312 TargetRegisterClass::iterator I = PhysReg.second->begin();
1313 TargetRegisterClass::iterator E = PhysReg.second->end();
1314 for (; *I != PhysReg.first; ++I)
1315 assert(I != E && "Didn't find reg!");
1316
1317 // Already added the first reg.
1318 --NumRegs; ++I;
1319 for (; NumRegs; --NumRegs, ++I) {
1320 assert(I != E && "Ran out of registers to allocate!");
1321 Regs.push_back(*I);
1322 }
1323 }
1324 return RegsForValue(Regs, RegVT, ValueVT);
1325 }
1326
1327 // This is a reference to a register class. Allocate NumRegs consecutive,
1328 // available, registers from the class.
1329 std::vector<unsigned> RegClassRegs =
1330 TLI.getRegClassForInlineAsmConstraint(ConstrCode, VT);
1331
1332 const MRegisterInfo *MRI = DAG.getTarget().getRegisterInfo();
1333 MachineFunction &MF = *CurMBB->getParent();
1334 unsigned NumAllocated = 0;
1335 for (unsigned i = 0, e = RegClassRegs.size(); i != e; ++i) {
1336 unsigned Reg = RegClassRegs[i];
1337 // See if this register is available.
1338 if ((isOutReg && OutputRegs.count(Reg)) || // Already used.
1339 (isInReg && InputRegs.count(Reg))) { // Already used.
1340 // Make sure we find consecutive registers.
1341 NumAllocated = 0;
1342 continue;
1343 }
1344
1345 // Check to see if this register is allocatable (i.e. don't give out the
1346 // stack pointer).
Chris Lattnerb1124f32006-02-22 23:09:03 +00001347 const TargetRegisterClass *RC = isAllocatableRegister(Reg, MF, TLI, MRI);
Chris Lattner6f87d182006-02-22 22:37:12 +00001348 if (!RC) {
1349 // Make sure we find consecutive registers.
1350 NumAllocated = 0;
1351 continue;
1352 }
1353
1354 // Okay, this register is good, we can use it.
1355 ++NumAllocated;
1356
1357 // If we allocated enough consecutive
1358 if (NumAllocated == NumRegs) {
1359 unsigned RegStart = (i-NumAllocated)+1;
1360 unsigned RegEnd = i+1;
1361 // Mark all of the allocated registers used.
1362 for (unsigned i = RegStart; i != RegEnd; ++i) {
1363 unsigned Reg = RegClassRegs[i];
1364 Regs.push_back(Reg);
1365 if (isOutReg) OutputRegs.insert(Reg); // Mark reg used.
1366 if (isInReg) InputRegs.insert(Reg); // Mark reg used.
1367 }
1368
1369 return RegsForValue(Regs, *RC->vt_begin(), VT);
1370 }
1371 }
1372
1373 // Otherwise, we couldn't allocate enough registers for this.
1374 return RegsForValue();
Chris Lattner1558fc62006-02-01 18:59:47 +00001375}
1376
Chris Lattner6f87d182006-02-22 22:37:12 +00001377
Chris Lattner476e67b2006-01-26 22:24:51 +00001378/// visitInlineAsm - Handle a call to an InlineAsm object.
1379///
1380void SelectionDAGLowering::visitInlineAsm(CallInst &I) {
1381 InlineAsm *IA = cast<InlineAsm>(I.getOperand(0));
1382
1383 SDOperand AsmStr = DAG.getTargetExternalSymbol(IA->getAsmString().c_str(),
1384 MVT::Other);
1385
1386 // Note, we treat inline asms both with and without side-effects as the same.
1387 // If an inline asm doesn't have side effects and doesn't access memory, we
1388 // could not choose to not chain it.
1389 bool hasSideEffects = IA->hasSideEffects();
1390
Chris Lattner3a5ed552006-02-01 01:28:23 +00001391 std::vector<InlineAsm::ConstraintInfo> Constraints = IA->ParseConstraints();
Chris Lattner7ad77df2006-02-22 00:56:39 +00001392 std::vector<MVT::ValueType> ConstraintVTs;
Chris Lattner476e67b2006-01-26 22:24:51 +00001393
1394 /// AsmNodeOperands - A list of pairs. The first element is a register, the
1395 /// second is a bitfield where bit #0 is set if it is a use and bit #1 is set
1396 /// if it is a def of that register.
1397 std::vector<SDOperand> AsmNodeOperands;
1398 AsmNodeOperands.push_back(SDOperand()); // reserve space for input chain
1399 AsmNodeOperands.push_back(AsmStr);
1400
1401 SDOperand Chain = getRoot();
1402 SDOperand Flag;
1403
Chris Lattner1558fc62006-02-01 18:59:47 +00001404 // We fully assign registers here at isel time. This is not optimal, but
1405 // should work. For register classes that correspond to LLVM classes, we
1406 // could let the LLVM RA do its thing, but we currently don't. Do a prepass
1407 // over the constraints, collecting fixed registers that we know we can't use.
1408 std::set<unsigned> OutputRegs, InputRegs;
Chris Lattner7ad77df2006-02-22 00:56:39 +00001409 unsigned OpNum = 1;
Chris Lattner1558fc62006-02-01 18:59:47 +00001410 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
1411 assert(Constraints[i].Codes.size() == 1 && "Only handles one code so far!");
1412 std::string &ConstraintCode = Constraints[i].Codes[0];
Chris Lattner7f5880b2006-02-02 00:25:23 +00001413
Chris Lattner7ad77df2006-02-22 00:56:39 +00001414 MVT::ValueType OpVT;
1415
1416 // Compute the value type for each operand and add it to ConstraintVTs.
1417 switch (Constraints[i].Type) {
1418 case InlineAsm::isOutput:
1419 if (!Constraints[i].isIndirectOutput) {
1420 assert(I.getType() != Type::VoidTy && "Bad inline asm!");
1421 OpVT = TLI.getValueType(I.getType());
1422 } else {
1423 Value *CallOperand = I.getOperand(OpNum);
1424 const Type *OpTy = CallOperand->getType();
1425 OpVT = TLI.getValueType(cast<PointerType>(OpTy)->getElementType());
1426 OpNum++; // Consumes a call operand.
1427 }
1428 break;
1429 case InlineAsm::isInput:
1430 OpVT = TLI.getValueType(I.getOperand(OpNum)->getType());
1431 OpNum++; // Consumes a call operand.
1432 break;
1433 case InlineAsm::isClobber:
1434 OpVT = MVT::Other;
1435 break;
1436 }
1437
1438 ConstraintVTs.push_back(OpVT);
1439
Chris Lattner6f87d182006-02-22 22:37:12 +00001440 if (TLI.getRegForInlineAsmConstraint(ConstraintCode, OpVT).first == 0)
1441 continue; // Not assigned a fixed reg.
Chris Lattner7ad77df2006-02-22 00:56:39 +00001442
Chris Lattner6f87d182006-02-22 22:37:12 +00001443 // Build a list of regs that this operand uses. This always has a single
1444 // element for promoted/expanded operands.
1445 RegsForValue Regs = GetRegistersForValue(ConstraintCode, OpVT,
1446 false, false,
1447 OutputRegs, InputRegs);
Chris Lattner1558fc62006-02-01 18:59:47 +00001448
1449 switch (Constraints[i].Type) {
1450 case InlineAsm::isOutput:
1451 // We can't assign any other output to this register.
Chris Lattner6f87d182006-02-22 22:37:12 +00001452 OutputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner1558fc62006-02-01 18:59:47 +00001453 // If this is an early-clobber output, it cannot be assigned to the same
1454 // value as the input reg.
Chris Lattner7f5880b2006-02-02 00:25:23 +00001455 if (Constraints[i].isEarlyClobber || Constraints[i].hasMatchingInput)
Chris Lattner6f87d182006-02-22 22:37:12 +00001456 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner1558fc62006-02-01 18:59:47 +00001457 break;
Chris Lattner7ad77df2006-02-22 00:56:39 +00001458 case InlineAsm::isInput:
1459 // We can't assign any other input to this register.
Chris Lattner6f87d182006-02-22 22:37:12 +00001460 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner7ad77df2006-02-22 00:56:39 +00001461 break;
Chris Lattner1558fc62006-02-01 18:59:47 +00001462 case InlineAsm::isClobber:
1463 // Clobbered regs cannot be used as inputs or outputs.
Chris Lattner6f87d182006-02-22 22:37:12 +00001464 InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
1465 OutputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
Chris Lattner1558fc62006-02-01 18:59:47 +00001466 break;
Chris Lattner1558fc62006-02-01 18:59:47 +00001467 }
1468 }
Chris Lattner3a5ed552006-02-01 01:28:23 +00001469
Chris Lattner5c79f982006-02-21 23:12:12 +00001470 // Loop over all of the inputs, copying the operand values into the
1471 // appropriate registers and processing the output regs.
Chris Lattner6f87d182006-02-22 22:37:12 +00001472 RegsForValue RetValRegs;
1473 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
Chris Lattner7ad77df2006-02-22 00:56:39 +00001474 OpNum = 1;
Chris Lattner5c79f982006-02-21 23:12:12 +00001475
Chris Lattner2e56e892006-01-31 02:03:41 +00001476 for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
Chris Lattner3a5ed552006-02-01 01:28:23 +00001477 assert(Constraints[i].Codes.size() == 1 && "Only handles one code so far!");
1478 std::string &ConstraintCode = Constraints[i].Codes[0];
Chris Lattner7ad77df2006-02-22 00:56:39 +00001479
Chris Lattner3a5ed552006-02-01 01:28:23 +00001480 switch (Constraints[i].Type) {
1481 case InlineAsm::isOutput: {
Chris Lattner6f87d182006-02-22 22:37:12 +00001482 // If this is an early-clobber output, or if there is an input
1483 // constraint that matches this, we need to reserve the input register
1484 // so no other inputs allocate to it.
1485 bool UsesInputRegister = false;
1486 if (Constraints[i].isEarlyClobber || Constraints[i].hasMatchingInput)
1487 UsesInputRegister = true;
1488
1489 // Copy the output from the appropriate register. Find a register that
Chris Lattner7ad77df2006-02-22 00:56:39 +00001490 // we can use.
Chris Lattner6f87d182006-02-22 22:37:12 +00001491 RegsForValue Regs =
1492 GetRegistersForValue(ConstraintCode, ConstraintVTs[i],
1493 true, UsesInputRegister,
1494 OutputRegs, InputRegs);
1495 assert(!Regs.Regs.empty() && "Couldn't allocate output reg!");
Chris Lattner7ad77df2006-02-22 00:56:39 +00001496
Chris Lattner3a5ed552006-02-01 01:28:23 +00001497 if (!Constraints[i].isIndirectOutput) {
Chris Lattner6f87d182006-02-22 22:37:12 +00001498 assert(RetValRegs.Regs.empty() &&
Chris Lattner3a5ed552006-02-01 01:28:23 +00001499 "Cannot have multiple output constraints yet!");
Chris Lattner3a5ed552006-02-01 01:28:23 +00001500 assert(I.getType() != Type::VoidTy && "Bad inline asm!");
Chris Lattner6f87d182006-02-22 22:37:12 +00001501 RetValRegs = Regs;
Chris Lattner3a5ed552006-02-01 01:28:23 +00001502 } else {
Chris Lattner7ad77df2006-02-22 00:56:39 +00001503 Value *CallOperand = I.getOperand(OpNum);
Chris Lattner6f87d182006-02-22 22:37:12 +00001504 IndirectStoresToEmit.push_back(std::make_pair(Regs, CallOperand));
Chris Lattner3a5ed552006-02-01 01:28:23 +00001505 OpNum++; // Consumes a call operand.
1506 }
Chris Lattner2e56e892006-01-31 02:03:41 +00001507
1508 // Add information to the INLINEASM node to know that this register is
1509 // set.
Chris Lattner571d9642006-02-23 19:21:04 +00001510 Regs.AddInlineAsmOperands(2 /*REGDEF*/, DAG, AsmNodeOperands);
Chris Lattner2e56e892006-01-31 02:03:41 +00001511 break;
1512 }
1513 case InlineAsm::isInput: {
Chris Lattner7ad77df2006-02-22 00:56:39 +00001514 Value *CallOperand = I.getOperand(OpNum);
Chris Lattner1558fc62006-02-01 18:59:47 +00001515 OpNum++; // Consumes a call operand.
Chris Lattner7f5880b2006-02-02 00:25:23 +00001516
Chris Lattner5c79f982006-02-21 23:12:12 +00001517 SDOperand InOperandVal = getValue(CallOperand);
Chris Lattner65ad53f2006-02-04 02:16:44 +00001518
Chris Lattner7f5880b2006-02-02 00:25:23 +00001519 if (isdigit(ConstraintCode[0])) { // Matching constraint?
1520 // If this is required to match an output register we have already set,
1521 // just use its register.
1522 unsigned OperandNo = atoi(ConstraintCode.c_str());
Chris Lattner65ad53f2006-02-04 02:16:44 +00001523
Chris Lattner571d9642006-02-23 19:21:04 +00001524 // Scan until we find the definition we already emitted of this operand.
1525 // When we find it, create a RegsForValue operand.
1526 unsigned CurOp = 2; // The first operand.
1527 for (; OperandNo; --OperandNo) {
1528 // Advance to the next operand.
1529 unsigned NumOps =
1530 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
1531 assert((NumOps & 7) == 2 /*REGDEF*/ &&
1532 "Skipped past definitions?");
1533 CurOp += (NumOps>>3)+1;
1534 }
1535
1536 unsigned NumOps =
1537 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
1538 assert((NumOps & 7) == 2 /*REGDEF*/ &&
1539 "Skipped past definitions?");
1540
1541 // Add NumOps>>3 registers to MatchedRegs.
1542 RegsForValue MatchedRegs;
1543 MatchedRegs.ValueVT = InOperandVal.getValueType();
1544 MatchedRegs.RegVT = AsmNodeOperands[CurOp+1].getValueType();
1545 for (unsigned i = 0, e = NumOps>>3; i != e; ++i) {
1546 unsigned Reg=cast<RegisterSDNode>(AsmNodeOperands[++CurOp])->getReg();
1547 MatchedRegs.Regs.push_back(Reg);
1548 }
1549
1550 // Use the produced MatchedRegs object to
1551 MatchedRegs.getCopyToRegs(InOperandVal, DAG, Chain, Flag);
1552 MatchedRegs.AddInlineAsmOperands(1 /*REGUSE*/, DAG, AsmNodeOperands);
Chris Lattner571d9642006-02-23 19:21:04 +00001553 break;
Chris Lattner7f5880b2006-02-02 00:25:23 +00001554 }
Chris Lattner7ef7a642006-02-24 01:11:24 +00001555
1556 TargetLowering::ConstraintType CTy = TargetLowering::C_RegisterClass;
1557 if (ConstraintCode.size() == 1) // not a physreg name.
1558 CTy = TLI.getConstraintType(ConstraintCode[0]);
1559
1560 if (CTy == TargetLowering::C_Other) {
1561 if (!TLI.isOperandValidForConstraint(InOperandVal, ConstraintCode[0]))
1562 assert(0 && "MATCH FAIL!");
1563
1564 // Add information to the INLINEASM node to know about this input.
1565 unsigned ResOpType = 3 /*IMM*/ | (1 << 3);
1566 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
1567 AsmNodeOperands.push_back(InOperandVal);
1568 break;
1569 } else if (CTy == TargetLowering::C_Memory) {
1570 // Memory input.
1571
1572 // Check that the operand isn't a float.
1573 if (!MVT::isInteger(InOperandVal.getValueType()))
1574 assert(0 && "MATCH FAIL!");
1575
1576 // Extend/truncate to the right pointer type if needed.
1577 MVT::ValueType PtrType = TLI.getPointerTy();
1578 if (InOperandVal.getValueType() < PtrType)
1579 InOperandVal = DAG.getNode(ISD::ZERO_EXTEND, PtrType, InOperandVal);
1580 else if (InOperandVal.getValueType() > PtrType)
1581 InOperandVal = DAG.getNode(ISD::TRUNCATE, PtrType, InOperandVal);
1582
1583 // Add information to the INLINEASM node to know about this input.
1584 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
1585 AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
1586 AsmNodeOperands.push_back(InOperandVal);
1587 break;
1588 }
1589
1590 assert(CTy == TargetLowering::C_RegisterClass && "Unknown op type!");
1591
1592 // Copy the input into the appropriate registers.
1593 RegsForValue InRegs =
1594 GetRegistersForValue(ConstraintCode, ConstraintVTs[i],
1595 false, true, OutputRegs, InputRegs);
1596 // FIXME: should be match fail.
1597 assert(!InRegs.Regs.empty() && "Couldn't allocate input reg!");
1598
1599 InRegs.getCopyToRegs(InOperandVal, DAG, Chain, Flag);
1600
1601 InRegs.AddInlineAsmOperands(1/*REGUSE*/, DAG, AsmNodeOperands);
Chris Lattner2e56e892006-01-31 02:03:41 +00001602 break;
1603 }
Chris Lattner571d9642006-02-23 19:21:04 +00001604 case InlineAsm::isClobber: {
1605 RegsForValue ClobberedRegs =
1606 GetRegistersForValue(ConstraintCode, MVT::Other, false, false,
1607 OutputRegs, InputRegs);
1608 // Add the clobbered value to the operand list, so that the register
1609 // allocator is aware that the physreg got clobbered.
1610 if (!ClobberedRegs.Regs.empty())
1611 ClobberedRegs.AddInlineAsmOperands(2/*REGDEF*/, DAG, AsmNodeOperands);
Chris Lattner2e56e892006-01-31 02:03:41 +00001612 break;
1613 }
Chris Lattner571d9642006-02-23 19:21:04 +00001614 }
Chris Lattner2e56e892006-01-31 02:03:41 +00001615 }
Chris Lattner476e67b2006-01-26 22:24:51 +00001616
1617 // Finish up input operands.
1618 AsmNodeOperands[0] = Chain;
1619 if (Flag.Val) AsmNodeOperands.push_back(Flag);
1620
1621 std::vector<MVT::ValueType> VTs;
1622 VTs.push_back(MVT::Other);
1623 VTs.push_back(MVT::Flag);
1624 Chain = DAG.getNode(ISD::INLINEASM, VTs, AsmNodeOperands);
1625 Flag = Chain.getValue(1);
1626
Chris Lattner2e56e892006-01-31 02:03:41 +00001627 // If this asm returns a register value, copy the result from that register
1628 // and set it as the value of the call.
Chris Lattner6f87d182006-02-22 22:37:12 +00001629 if (!RetValRegs.Regs.empty())
1630 setValue(&I, RetValRegs.getCopyFromRegs(DAG, Chain, Flag));
Chris Lattner476e67b2006-01-26 22:24:51 +00001631
Chris Lattner2e56e892006-01-31 02:03:41 +00001632 std::vector<std::pair<SDOperand, Value*> > StoresToEmit;
1633
1634 // Process indirect outputs, first output all of the flagged copies out of
1635 // physregs.
1636 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
Chris Lattner6f87d182006-02-22 22:37:12 +00001637 RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
Chris Lattner2e56e892006-01-31 02:03:41 +00001638 Value *Ptr = IndirectStoresToEmit[i].second;
Chris Lattner6f87d182006-02-22 22:37:12 +00001639 SDOperand OutVal = OutRegs.getCopyFromRegs(DAG, Chain, Flag);
1640 StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
Chris Lattner2e56e892006-01-31 02:03:41 +00001641 }
1642
1643 // Emit the non-flagged stores from the physregs.
1644 std::vector<SDOperand> OutChains;
1645 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i)
1646 OutChains.push_back(DAG.getNode(ISD::STORE, MVT::Other, Chain,
1647 StoresToEmit[i].first,
1648 getValue(StoresToEmit[i].second),
1649 DAG.getSrcValue(StoresToEmit[i].second)));
1650 if (!OutChains.empty())
1651 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other, OutChains);
Chris Lattner476e67b2006-01-26 22:24:51 +00001652 DAG.setRoot(Chain);
1653}
1654
1655
Chris Lattner7a60d912005-01-07 07:47:53 +00001656void SelectionDAGLowering::visitMalloc(MallocInst &I) {
1657 SDOperand Src = getValue(I.getOperand(0));
1658
1659 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattnereccb73d2005-01-22 23:04:37 +00001660
1661 if (IntPtr < Src.getValueType())
1662 Src = DAG.getNode(ISD::TRUNCATE, IntPtr, Src);
1663 else if (IntPtr > Src.getValueType())
1664 Src = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, Src);
Chris Lattner7a60d912005-01-07 07:47:53 +00001665
1666 // Scale the source by the type size.
1667 uint64_t ElementSize = TD.getTypeSize(I.getType()->getElementType());
1668 Src = DAG.getNode(ISD::MUL, Src.getValueType(),
1669 Src, getIntPtrConstant(ElementSize));
1670
1671 std::vector<std::pair<SDOperand, const Type*> > Args;
1672 Args.push_back(std::make_pair(Src, TLI.getTargetData().getIntPtrType()));
Chris Lattner1f45cd72005-01-08 19:26:18 +00001673
1674 std::pair<SDOperand,SDOperand> Result =
Chris Lattner2e77db62005-05-13 18:50:42 +00001675 TLI.LowerCallTo(getRoot(), I.getType(), false, CallingConv::C, true,
Chris Lattner1f45cd72005-01-08 19:26:18 +00001676 DAG.getExternalSymbol("malloc", IntPtr),
1677 Args, DAG);
1678 setValue(&I, Result.first); // Pointers always fit in registers
1679 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +00001680}
1681
1682void SelectionDAGLowering::visitFree(FreeInst &I) {
1683 std::vector<std::pair<SDOperand, const Type*> > Args;
1684 Args.push_back(std::make_pair(getValue(I.getOperand(0)),
1685 TLI.getTargetData().getIntPtrType()));
1686 MVT::ValueType IntPtr = TLI.getPointerTy();
Chris Lattner1f45cd72005-01-08 19:26:18 +00001687 std::pair<SDOperand,SDOperand> Result =
Chris Lattner2e77db62005-05-13 18:50:42 +00001688 TLI.LowerCallTo(getRoot(), Type::VoidTy, false, CallingConv::C, true,
Chris Lattner1f45cd72005-01-08 19:26:18 +00001689 DAG.getExternalSymbol("free", IntPtr), Args, DAG);
1690 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +00001691}
1692
Chris Lattner13d7c252005-08-26 20:54:47 +00001693// InsertAtEndOfBasicBlock - This method should be implemented by targets that
1694// mark instructions with the 'usesCustomDAGSchedInserter' flag. These
1695// instructions are special in various ways, which require special support to
1696// insert. The specified MachineInstr is created but not inserted into any
1697// basic blocks, and the scheduler passes ownership of it to this method.
1698MachineBasicBlock *TargetLowering::InsertAtEndOfBasicBlock(MachineInstr *MI,
1699 MachineBasicBlock *MBB) {
1700 std::cerr << "If a target marks an instruction with "
1701 "'usesCustomDAGSchedInserter', it must implement "
1702 "TargetLowering::InsertAtEndOfBasicBlock!\n";
1703 abort();
1704 return 0;
1705}
1706
Chris Lattner58cfd792005-01-09 00:00:49 +00001707void SelectionDAGLowering::visitVAStart(CallInst &I) {
Nate Begemane74795c2006-01-25 18:21:52 +00001708 DAG.setRoot(DAG.getNode(ISD::VASTART, MVT::Other, getRoot(),
1709 getValue(I.getOperand(1)),
1710 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner58cfd792005-01-09 00:00:49 +00001711}
1712
1713void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
Nate Begemane74795c2006-01-25 18:21:52 +00001714 SDOperand V = DAG.getVAArg(TLI.getValueType(I.getType()), getRoot(),
1715 getValue(I.getOperand(0)),
1716 DAG.getSrcValue(I.getOperand(0)));
1717 setValue(&I, V);
1718 DAG.setRoot(V.getValue(1));
Chris Lattner7a60d912005-01-07 07:47:53 +00001719}
1720
1721void SelectionDAGLowering::visitVAEnd(CallInst &I) {
Nate Begemane74795c2006-01-25 18:21:52 +00001722 DAG.setRoot(DAG.getNode(ISD::VAEND, MVT::Other, getRoot(),
1723 getValue(I.getOperand(1)),
1724 DAG.getSrcValue(I.getOperand(1))));
Chris Lattner7a60d912005-01-07 07:47:53 +00001725}
1726
1727void SelectionDAGLowering::visitVACopy(CallInst &I) {
Nate Begemane74795c2006-01-25 18:21:52 +00001728 DAG.setRoot(DAG.getNode(ISD::VACOPY, MVT::Other, getRoot(),
1729 getValue(I.getOperand(1)),
1730 getValue(I.getOperand(2)),
1731 DAG.getSrcValue(I.getOperand(1)),
1732 DAG.getSrcValue(I.getOperand(2))));
Chris Lattner7a60d912005-01-07 07:47:53 +00001733}
1734
Chris Lattner58cfd792005-01-09 00:00:49 +00001735// It is always conservatively correct for llvm.returnaddress and
1736// llvm.frameaddress to return 0.
1737std::pair<SDOperand, SDOperand>
1738TargetLowering::LowerFrameReturnAddress(bool isFrameAddr, SDOperand Chain,
1739 unsigned Depth, SelectionDAG &DAG) {
1740 return std::make_pair(DAG.getConstant(0, getPointerTy()), Chain);
Chris Lattner7a60d912005-01-07 07:47:53 +00001741}
1742
Chris Lattner29dcc712005-05-14 05:50:48 +00001743SDOperand TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
Chris Lattner897cd7d2005-01-16 07:28:41 +00001744 assert(0 && "LowerOperation not implemented for this target!");
1745 abort();
Misha Brukman73e929f2005-02-17 21:39:27 +00001746 return SDOperand();
Chris Lattner897cd7d2005-01-16 07:28:41 +00001747}
1748
Nate Begeman595ec732006-01-28 03:14:31 +00001749SDOperand TargetLowering::CustomPromoteOperation(SDOperand Op,
1750 SelectionDAG &DAG) {
1751 assert(0 && "CustomPromoteOperation not implemented for this target!");
1752 abort();
1753 return SDOperand();
1754}
1755
Chris Lattner58cfd792005-01-09 00:00:49 +00001756void SelectionDAGLowering::visitFrameReturnAddress(CallInst &I, bool isFrame) {
1757 unsigned Depth = (unsigned)cast<ConstantUInt>(I.getOperand(1))->getValue();
1758 std::pair<SDOperand,SDOperand> Result =
Chris Lattner4108bb02005-01-17 19:43:36 +00001759 TLI.LowerFrameReturnAddress(isFrame, getRoot(), Depth, DAG);
Chris Lattner58cfd792005-01-09 00:00:49 +00001760 setValue(&I, Result.first);
1761 DAG.setRoot(Result.second);
Chris Lattner7a60d912005-01-07 07:47:53 +00001762}
1763
Evan Cheng6781b6e2006-02-15 21:59:04 +00001764/// getMemsetValue - Vectorized representation of the memset value
Evan Cheng81fcea82006-02-14 08:22:34 +00001765/// operand.
1766static SDOperand getMemsetValue(SDOperand Value, MVT::ValueType VT,
Evan Cheng93e48652006-02-15 22:12:35 +00001767 SelectionDAG &DAG) {
Evan Cheng81fcea82006-02-14 08:22:34 +00001768 MVT::ValueType CurVT = VT;
1769 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
1770 uint64_t Val = C->getValue() & 255;
1771 unsigned Shift = 8;
1772 while (CurVT != MVT::i8) {
1773 Val = (Val << Shift) | Val;
1774 Shift <<= 1;
1775 CurVT = (MVT::ValueType)((unsigned)CurVT - 1);
Evan Cheng81fcea82006-02-14 08:22:34 +00001776 }
1777 return DAG.getConstant(Val, VT);
1778 } else {
1779 Value = DAG.getNode(ISD::ZERO_EXTEND, VT, Value);
1780 unsigned Shift = 8;
1781 while (CurVT != MVT::i8) {
1782 Value =
1783 DAG.getNode(ISD::OR, VT,
1784 DAG.getNode(ISD::SHL, VT, Value,
1785 DAG.getConstant(Shift, MVT::i8)), Value);
1786 Shift <<= 1;
1787 CurVT = (MVT::ValueType)((unsigned)CurVT - 1);
Evan Cheng81fcea82006-02-14 08:22:34 +00001788 }
1789
1790 return Value;
1791 }
1792}
1793
Evan Cheng6781b6e2006-02-15 21:59:04 +00001794/// getMemsetStringVal - Similar to getMemsetValue. Except this is only
1795/// used when a memcpy is turned into a memset when the source is a constant
1796/// string ptr.
1797static SDOperand getMemsetStringVal(MVT::ValueType VT,
1798 SelectionDAG &DAG, TargetLowering &TLI,
1799 std::string &Str, unsigned Offset) {
1800 MVT::ValueType CurVT = VT;
1801 uint64_t Val = 0;
1802 unsigned MSB = getSizeInBits(VT) / 8;
1803 if (TLI.isLittleEndian())
1804 Offset = Offset + MSB - 1;
1805 for (unsigned i = 0; i != MSB; ++i) {
1806 Val = (Val << 8) | Str[Offset];
1807 Offset += TLI.isLittleEndian() ? -1 : 1;
1808 }
1809 return DAG.getConstant(Val, VT);
1810}
1811
Evan Cheng81fcea82006-02-14 08:22:34 +00001812/// getMemBasePlusOffset - Returns base and offset node for the
1813static SDOperand getMemBasePlusOffset(SDOperand Base, unsigned Offset,
1814 SelectionDAG &DAG, TargetLowering &TLI) {
1815 MVT::ValueType VT = Base.getValueType();
1816 return DAG.getNode(ISD::ADD, VT, Base, DAG.getConstant(Offset, VT));
1817}
1818
Evan Chengdb2a7a72006-02-14 20:12:38 +00001819/// MeetsMaxMemopRequirement - Determines if the number of memory ops required
Evan Chengd5026102006-02-14 09:11:59 +00001820/// to replace the memset / memcpy is below the threshold. It also returns the
1821/// types of the sequence of memory ops to perform memset / memcpy.
Evan Chengdb2a7a72006-02-14 20:12:38 +00001822static bool MeetsMaxMemopRequirement(std::vector<MVT::ValueType> &MemOps,
1823 unsigned Limit, uint64_t Size,
1824 unsigned Align, TargetLowering &TLI) {
Evan Cheng81fcea82006-02-14 08:22:34 +00001825 MVT::ValueType VT;
1826
1827 if (TLI.allowsUnalignedMemoryAccesses()) {
1828 VT = MVT::i64;
1829 } else {
1830 switch (Align & 7) {
1831 case 0:
1832 VT = MVT::i64;
1833 break;
1834 case 4:
1835 VT = MVT::i32;
1836 break;
1837 case 2:
1838 VT = MVT::i16;
1839 break;
1840 default:
1841 VT = MVT::i8;
1842 break;
1843 }
1844 }
1845
Evan Chengd5026102006-02-14 09:11:59 +00001846 MVT::ValueType LVT = MVT::i64;
1847 while (!TLI.isTypeLegal(LVT))
1848 LVT = (MVT::ValueType)((unsigned)LVT - 1);
1849 assert(MVT::isInteger(LVT));
Evan Cheng81fcea82006-02-14 08:22:34 +00001850
Evan Chengd5026102006-02-14 09:11:59 +00001851 if (VT > LVT)
1852 VT = LVT;
1853
Evan Cheng04514992006-02-14 23:05:54 +00001854 unsigned NumMemOps = 0;
Evan Cheng81fcea82006-02-14 08:22:34 +00001855 while (Size != 0) {
1856 unsigned VTSize = getSizeInBits(VT) / 8;
1857 while (VTSize > Size) {
1858 VT = (MVT::ValueType)((unsigned)VT - 1);
Evan Cheng81fcea82006-02-14 08:22:34 +00001859 VTSize >>= 1;
1860 }
Evan Chengd5026102006-02-14 09:11:59 +00001861 assert(MVT::isInteger(VT));
1862
1863 if (++NumMemOps > Limit)
1864 return false;
Evan Cheng81fcea82006-02-14 08:22:34 +00001865 MemOps.push_back(VT);
1866 Size -= VTSize;
1867 }
Evan Chengd5026102006-02-14 09:11:59 +00001868
1869 return true;
Evan Cheng81fcea82006-02-14 08:22:34 +00001870}
1871
Chris Lattner875def92005-01-11 05:56:49 +00001872void SelectionDAGLowering::visitMemIntrinsic(CallInst &I, unsigned Op) {
Evan Cheng81fcea82006-02-14 08:22:34 +00001873 SDOperand Op1 = getValue(I.getOperand(1));
1874 SDOperand Op2 = getValue(I.getOperand(2));
1875 SDOperand Op3 = getValue(I.getOperand(3));
1876 SDOperand Op4 = getValue(I.getOperand(4));
1877 unsigned Align = (unsigned)cast<ConstantSDNode>(Op4)->getValue();
1878 if (Align == 0) Align = 1;
1879
1880 if (ConstantSDNode *Size = dyn_cast<ConstantSDNode>(Op3)) {
1881 std::vector<MVT::ValueType> MemOps;
Evan Cheng81fcea82006-02-14 08:22:34 +00001882
1883 // Expand memset / memcpy to a series of load / store ops
1884 // if the size operand falls below a certain threshold.
1885 std::vector<SDOperand> OutChains;
1886 switch (Op) {
Evan Cheng038521e2006-02-14 19:45:56 +00001887 default: break; // Do nothing for now.
Evan Cheng81fcea82006-02-14 08:22:34 +00001888 case ISD::MEMSET: {
Evan Chengdb2a7a72006-02-14 20:12:38 +00001889 if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemset(),
1890 Size->getValue(), Align, TLI)) {
Evan Chengd5026102006-02-14 09:11:59 +00001891 unsigned NumMemOps = MemOps.size();
Evan Cheng81fcea82006-02-14 08:22:34 +00001892 unsigned Offset = 0;
1893 for (unsigned i = 0; i < NumMemOps; i++) {
1894 MVT::ValueType VT = MemOps[i];
1895 unsigned VTSize = getSizeInBits(VT) / 8;
Evan Cheng93e48652006-02-15 22:12:35 +00001896 SDOperand Value = getMemsetValue(Op2, VT, DAG);
Evan Chenge2038bd2006-02-15 01:54:51 +00001897 SDOperand Store = DAG.getNode(ISD::STORE, MVT::Other, getRoot(),
1898 Value,
Chris Lattner6f87d182006-02-22 22:37:12 +00001899 getMemBasePlusOffset(Op1, Offset, DAG, TLI),
1900 DAG.getSrcValue(I.getOperand(1), Offset));
Evan Chenge2038bd2006-02-15 01:54:51 +00001901 OutChains.push_back(Store);
Evan Cheng81fcea82006-02-14 08:22:34 +00001902 Offset += VTSize;
1903 }
Evan Cheng81fcea82006-02-14 08:22:34 +00001904 }
Evan Chenge2038bd2006-02-15 01:54:51 +00001905 break;
Evan Cheng81fcea82006-02-14 08:22:34 +00001906 }
Evan Chenge2038bd2006-02-15 01:54:51 +00001907 case ISD::MEMCPY: {
1908 if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemcpy(),
1909 Size->getValue(), Align, TLI)) {
1910 unsigned NumMemOps = MemOps.size();
Evan Chengc3dcf5a2006-02-16 23:11:42 +00001911 unsigned SrcOff = 0, DstOff = 0, SrcDelta = 0;
Evan Cheng6781b6e2006-02-15 21:59:04 +00001912 GlobalAddressSDNode *G = NULL;
1913 std::string Str;
Evan Chengc3dcf5a2006-02-16 23:11:42 +00001914 bool CopyFromStr = false;
Evan Cheng6781b6e2006-02-15 21:59:04 +00001915
1916 if (Op2.getOpcode() == ISD::GlobalAddress)
1917 G = cast<GlobalAddressSDNode>(Op2);
1918 else if (Op2.getOpcode() == ISD::ADD &&
1919 Op2.getOperand(0).getOpcode() == ISD::GlobalAddress &&
1920 Op2.getOperand(1).getOpcode() == ISD::Constant) {
1921 G = cast<GlobalAddressSDNode>(Op2.getOperand(0));
Evan Chengc3dcf5a2006-02-16 23:11:42 +00001922 SrcDelta = cast<ConstantSDNode>(Op2.getOperand(1))->getValue();
Evan Cheng6781b6e2006-02-15 21:59:04 +00001923 }
1924 if (G) {
1925 GlobalVariable *GV = dyn_cast<GlobalVariable>(G->getGlobal());
Evan Chengc3dcf5a2006-02-16 23:11:42 +00001926 if (GV) {
Evan Cheng6781b6e2006-02-15 21:59:04 +00001927 Str = getStringValue(GV);
Evan Chengc3dcf5a2006-02-16 23:11:42 +00001928 if (!Str.empty()) {
1929 CopyFromStr = true;
1930 SrcOff += SrcDelta;
1931 }
1932 }
Evan Cheng6781b6e2006-02-15 21:59:04 +00001933 }
1934
Evan Chenge2038bd2006-02-15 01:54:51 +00001935 for (unsigned i = 0; i < NumMemOps; i++) {
1936 MVT::ValueType VT = MemOps[i];
1937 unsigned VTSize = getSizeInBits(VT) / 8;
Evan Cheng6781b6e2006-02-15 21:59:04 +00001938 SDOperand Value, Chain, Store;
1939
Evan Chengc3dcf5a2006-02-16 23:11:42 +00001940 if (CopyFromStr) {
Evan Cheng6781b6e2006-02-15 21:59:04 +00001941 Value = getMemsetStringVal(VT, DAG, TLI, Str, SrcOff);
1942 Chain = getRoot();
1943 Store =
1944 DAG.getNode(ISD::STORE, MVT::Other, Chain, Value,
1945 getMemBasePlusOffset(Op1, DstOff, DAG, TLI),
1946 DAG.getSrcValue(I.getOperand(1), DstOff));
1947 } else {
1948 Value = DAG.getLoad(VT, getRoot(),
1949 getMemBasePlusOffset(Op2, SrcOff, DAG, TLI),
1950 DAG.getSrcValue(I.getOperand(2), SrcOff));
1951 Chain = Value.getValue(1);
1952 Store =
1953 DAG.getNode(ISD::STORE, MVT::Other, Chain, Value,
1954 getMemBasePlusOffset(Op1, DstOff, DAG, TLI),
1955 DAG.getSrcValue(I.getOperand(1), DstOff));
1956 }
Evan Chenge2038bd2006-02-15 01:54:51 +00001957 OutChains.push_back(Store);
Evan Cheng6781b6e2006-02-15 21:59:04 +00001958 SrcOff += VTSize;
1959 DstOff += VTSize;
Evan Chenge2038bd2006-02-15 01:54:51 +00001960 }
1961 }
1962 break;
1963 }
1964 }
1965
1966 if (!OutChains.empty()) {
1967 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other, OutChains));
1968 return;
Evan Cheng81fcea82006-02-14 08:22:34 +00001969 }
1970 }
1971
Chris Lattner875def92005-01-11 05:56:49 +00001972 std::vector<SDOperand> Ops;
Chris Lattner4108bb02005-01-17 19:43:36 +00001973 Ops.push_back(getRoot());
Evan Cheng81fcea82006-02-14 08:22:34 +00001974 Ops.push_back(Op1);
1975 Ops.push_back(Op2);
1976 Ops.push_back(Op3);
1977 Ops.push_back(Op4);
Chris Lattner875def92005-01-11 05:56:49 +00001978 DAG.setRoot(DAG.getNode(Op, MVT::Other, Ops));
Chris Lattner7a60d912005-01-07 07:47:53 +00001979}
1980
Chris Lattner875def92005-01-11 05:56:49 +00001981//===----------------------------------------------------------------------===//
1982// SelectionDAGISel code
1983//===----------------------------------------------------------------------===//
Chris Lattner7a60d912005-01-07 07:47:53 +00001984
1985unsigned SelectionDAGISel::MakeReg(MVT::ValueType VT) {
1986 return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
1987}
1988
Chris Lattnerc9950c12005-08-17 06:37:43 +00001989void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattner1a908c82005-08-18 17:35:14 +00001990 // FIXME: we only modify the CFG to split critical edges. This
1991 // updates dom and loop info.
Chris Lattnerc9950c12005-08-17 06:37:43 +00001992}
Chris Lattner7a60d912005-01-07 07:47:53 +00001993
Chris Lattner35397782005-12-05 07:10:48 +00001994
1995/// InsertGEPComputeCode - Insert code into BB to compute Ptr+PtrOffset,
1996/// casting to the type of GEPI.
1997static Value *InsertGEPComputeCode(Value *&V, BasicBlock *BB, Instruction *GEPI,
1998 Value *Ptr, Value *PtrOffset) {
1999 if (V) return V; // Already computed.
2000
2001 BasicBlock::iterator InsertPt;
2002 if (BB == GEPI->getParent()) {
2003 // If insert into the GEP's block, insert right after the GEP.
2004 InsertPt = GEPI;
2005 ++InsertPt;
2006 } else {
2007 // Otherwise, insert at the top of BB, after any PHI nodes
2008 InsertPt = BB->begin();
2009 while (isa<PHINode>(InsertPt)) ++InsertPt;
2010 }
2011
Chris Lattnerbe73d6e2005-12-08 08:00:12 +00002012 // If Ptr is itself a cast, but in some other BB, emit a copy of the cast into
2013 // BB so that there is only one value live across basic blocks (the cast
2014 // operand).
2015 if (CastInst *CI = dyn_cast<CastInst>(Ptr))
2016 if (CI->getParent() != BB && isa<PointerType>(CI->getOperand(0)->getType()))
2017 Ptr = new CastInst(CI->getOperand(0), CI->getType(), "", InsertPt);
2018
Chris Lattner35397782005-12-05 07:10:48 +00002019 // Add the offset, cast it to the right type.
2020 Ptr = BinaryOperator::createAdd(Ptr, PtrOffset, "", InsertPt);
2021 Ptr = new CastInst(Ptr, GEPI->getType(), "", InsertPt);
2022 return V = Ptr;
2023}
2024
2025
2026/// OptimizeGEPExpression - Since we are doing basic-block-at-a-time instruction
2027/// selection, we want to be a bit careful about some things. In particular, if
2028/// we have a GEP instruction that is used in a different block than it is
2029/// defined, the addressing expression of the GEP cannot be folded into loads or
2030/// stores that use it. In this case, decompose the GEP and move constant
2031/// indices into blocks that use it.
2032static void OptimizeGEPExpression(GetElementPtrInst *GEPI,
2033 const TargetData &TD) {
Chris Lattner35397782005-12-05 07:10:48 +00002034 // If this GEP is only used inside the block it is defined in, there is no
2035 // need to rewrite it.
2036 bool isUsedOutsideDefBB = false;
2037 BasicBlock *DefBB = GEPI->getParent();
2038 for (Value::use_iterator UI = GEPI->use_begin(), E = GEPI->use_end();
2039 UI != E; ++UI) {
2040 if (cast<Instruction>(*UI)->getParent() != DefBB) {
2041 isUsedOutsideDefBB = true;
2042 break;
2043 }
2044 }
2045 if (!isUsedOutsideDefBB) return;
2046
2047 // If this GEP has no non-zero constant indices, there is nothing we can do,
2048 // ignore it.
2049 bool hasConstantIndex = false;
2050 for (GetElementPtrInst::op_iterator OI = GEPI->op_begin()+1,
2051 E = GEPI->op_end(); OI != E; ++OI) {
2052 if (ConstantInt *CI = dyn_cast<ConstantInt>(*OI))
2053 if (CI->getRawValue()) {
2054 hasConstantIndex = true;
2055 break;
2056 }
2057 }
Chris Lattnerf1a54c02005-12-11 09:05:13 +00002058 // If this is a GEP &Alloca, 0, 0, forward subst the frame index into uses.
2059 if (!hasConstantIndex && !isa<AllocaInst>(GEPI->getOperand(0))) return;
Chris Lattner35397782005-12-05 07:10:48 +00002060
2061 // Otherwise, decompose the GEP instruction into multiplies and adds. Sum the
2062 // constant offset (which we now know is non-zero) and deal with it later.
2063 uint64_t ConstantOffset = 0;
2064 const Type *UIntPtrTy = TD.getIntPtrType();
2065 Value *Ptr = new CastInst(GEPI->getOperand(0), UIntPtrTy, "", GEPI);
2066 const Type *Ty = GEPI->getOperand(0)->getType();
2067
2068 for (GetElementPtrInst::op_iterator OI = GEPI->op_begin()+1,
2069 E = GEPI->op_end(); OI != E; ++OI) {
2070 Value *Idx = *OI;
2071 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
2072 unsigned Field = cast<ConstantUInt>(Idx)->getValue();
2073 if (Field)
2074 ConstantOffset += TD.getStructLayout(StTy)->MemberOffsets[Field];
2075 Ty = StTy->getElementType(Field);
2076 } else {
2077 Ty = cast<SequentialType>(Ty)->getElementType();
2078
2079 // Handle constant subscripts.
2080 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
2081 if (CI->getRawValue() == 0) continue;
2082
2083 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(CI))
2084 ConstantOffset += (int64_t)TD.getTypeSize(Ty)*CSI->getValue();
2085 else
2086 ConstantOffset+=TD.getTypeSize(Ty)*cast<ConstantUInt>(CI)->getValue();
2087 continue;
2088 }
2089
2090 // Ptr = Ptr + Idx * ElementSize;
2091
2092 // Cast Idx to UIntPtrTy if needed.
2093 Idx = new CastInst(Idx, UIntPtrTy, "", GEPI);
2094
2095 uint64_t ElementSize = TD.getTypeSize(Ty);
2096 // Mask off bits that should not be set.
2097 ElementSize &= ~0ULL >> (64-UIntPtrTy->getPrimitiveSizeInBits());
2098 Constant *SizeCst = ConstantUInt::get(UIntPtrTy, ElementSize);
2099
2100 // Multiply by the element size and add to the base.
2101 Idx = BinaryOperator::createMul(Idx, SizeCst, "", GEPI);
2102 Ptr = BinaryOperator::createAdd(Ptr, Idx, "", GEPI);
2103 }
2104 }
2105
2106 // Make sure that the offset fits in uintptr_t.
2107 ConstantOffset &= ~0ULL >> (64-UIntPtrTy->getPrimitiveSizeInBits());
2108 Constant *PtrOffset = ConstantUInt::get(UIntPtrTy, ConstantOffset);
2109
2110 // Okay, we have now emitted all of the variable index parts to the BB that
2111 // the GEP is defined in. Loop over all of the using instructions, inserting
2112 // an "add Ptr, ConstantOffset" into each block that uses it and update the
Chris Lattnerbe73d6e2005-12-08 08:00:12 +00002113 // instruction to use the newly computed value, making GEPI dead. When the
2114 // user is a load or store instruction address, we emit the add into the user
2115 // block, otherwise we use a canonical version right next to the gep (these
2116 // won't be foldable as addresses, so we might as well share the computation).
2117
Chris Lattner35397782005-12-05 07:10:48 +00002118 std::map<BasicBlock*,Value*> InsertedExprs;
2119 while (!GEPI->use_empty()) {
2120 Instruction *User = cast<Instruction>(GEPI->use_back());
Chris Lattnerbe73d6e2005-12-08 08:00:12 +00002121
2122 // If this use is not foldable into the addressing mode, use a version
2123 // emitted in the GEP block.
2124 Value *NewVal;
2125 if (!isa<LoadInst>(User) &&
2126 (!isa<StoreInst>(User) || User->getOperand(0) == GEPI)) {
2127 NewVal = InsertGEPComputeCode(InsertedExprs[DefBB], DefBB, GEPI,
2128 Ptr, PtrOffset);
2129 } else {
2130 // Otherwise, insert the code in the User's block so it can be folded into
2131 // any users in that block.
2132 NewVal = InsertGEPComputeCode(InsertedExprs[User->getParent()],
Chris Lattner35397782005-12-05 07:10:48 +00002133 User->getParent(), GEPI,
2134 Ptr, PtrOffset);
Chris Lattner35397782005-12-05 07:10:48 +00002135 }
Chris Lattnerbe73d6e2005-12-08 08:00:12 +00002136 User->replaceUsesOfWith(GEPI, NewVal);
2137 }
Chris Lattner35397782005-12-05 07:10:48 +00002138
2139 // Finally, the GEP is dead, remove it.
2140 GEPI->eraseFromParent();
2141}
2142
Chris Lattner7a60d912005-01-07 07:47:53 +00002143bool SelectionDAGISel::runOnFunction(Function &Fn) {
2144 MachineFunction &MF = MachineFunction::construct(&Fn, TLI.getTargetMachine());
2145 RegMap = MF.getSSARegMap();
2146 DEBUG(std::cerr << "\n\n\n=== " << Fn.getName() << "\n");
2147
Chris Lattner35397782005-12-05 07:10:48 +00002148 // First, split all critical edges for PHI nodes with incoming values that are
2149 // constants, this way the load of the constant into a vreg will not be placed
2150 // into MBBs that are used some other way.
2151 //
2152 // In this pass we also look for GEP instructions that are used across basic
2153 // blocks and rewrites them to improve basic-block-at-a-time selection.
2154 //
Chris Lattner1a908c82005-08-18 17:35:14 +00002155 for (Function::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) {
2156 PHINode *PN;
Chris Lattner35397782005-12-05 07:10:48 +00002157 BasicBlock::iterator BBI;
2158 for (BBI = BB->begin(); (PN = dyn_cast<PHINode>(BBI)); ++BBI)
Chris Lattner1a908c82005-08-18 17:35:14 +00002159 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
2160 if (isa<Constant>(PN->getIncomingValue(i)))
2161 SplitCriticalEdge(PN->getIncomingBlock(i), BB);
Chris Lattner35397782005-12-05 07:10:48 +00002162
2163 for (BasicBlock::iterator E = BB->end(); BBI != E; )
2164 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(BBI++))
2165 OptimizeGEPExpression(GEPI, TLI.getTargetData());
Chris Lattner1a908c82005-08-18 17:35:14 +00002166 }
Chris Lattnercd6f0f42005-11-09 19:44:01 +00002167
Chris Lattner7a60d912005-01-07 07:47:53 +00002168 FunctionLoweringInfo FuncInfo(TLI, Fn, MF);
2169
2170 for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
2171 SelectBasicBlock(I, MF, FuncInfo);
Misha Brukman835702a2005-04-21 22:36:52 +00002172
Chris Lattner7a60d912005-01-07 07:47:53 +00002173 return true;
2174}
2175
2176
Chris Lattner718b5c22005-01-13 17:59:43 +00002177SDOperand SelectionDAGISel::
2178CopyValueToVirtualRegister(SelectionDAGLowering &SDL, Value *V, unsigned Reg) {
Chris Lattner613f79f2005-01-11 22:03:46 +00002179 SDOperand Op = SDL.getValue(V);
Chris Lattnere727af02005-01-13 20:50:02 +00002180 assert((Op.getOpcode() != ISD::CopyFromReg ||
Chris Lattner33182322005-08-16 21:55:35 +00002181 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
Chris Lattnere727af02005-01-13 20:50:02 +00002182 "Copy from a reg to the same reg!");
Chris Lattner33182322005-08-16 21:55:35 +00002183
2184 // If this type is not legal, we must make sure to not create an invalid
2185 // register use.
2186 MVT::ValueType SrcVT = Op.getValueType();
2187 MVT::ValueType DestVT = TLI.getTypeToTransformTo(SrcVT);
2188 SelectionDAG &DAG = SDL.DAG;
2189 if (SrcVT == DestVT) {
2190 return DAG.getCopyToReg(SDL.getRoot(), Reg, Op);
2191 } else if (SrcVT < DestVT) {
2192 // The src value is promoted to the register.
Chris Lattnerba28c272005-08-17 06:06:25 +00002193 if (MVT::isFloatingPoint(SrcVT))
2194 Op = DAG.getNode(ISD::FP_EXTEND, DestVT, Op);
2195 else
Chris Lattnera66403d2005-09-02 00:19:37 +00002196 Op = DAG.getNode(ISD::ANY_EXTEND, DestVT, Op);
Chris Lattner33182322005-08-16 21:55:35 +00002197 return DAG.getCopyToReg(SDL.getRoot(), Reg, Op);
2198 } else {
2199 // The src value is expanded into multiple registers.
2200 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
2201 Op, DAG.getConstant(0, MVT::i32));
2202 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
2203 Op, DAG.getConstant(1, MVT::i32));
2204 Op = DAG.getCopyToReg(SDL.getRoot(), Reg, Lo);
2205 return DAG.getCopyToReg(Op, Reg+1, Hi);
2206 }
Chris Lattner7a60d912005-01-07 07:47:53 +00002207}
2208
Chris Lattner16f64df2005-01-17 17:15:02 +00002209void SelectionDAGISel::
2210LowerArguments(BasicBlock *BB, SelectionDAGLowering &SDL,
2211 std::vector<SDOperand> &UnorderedChains) {
2212 // If this is the entry block, emit arguments.
2213 Function &F = *BB->getParent();
Chris Lattnere3c2cf42005-01-17 17:55:19 +00002214 FunctionLoweringInfo &FuncInfo = SDL.FuncInfo;
Chris Lattner6871b232005-10-30 19:42:35 +00002215 SDOperand OldRoot = SDL.DAG.getRoot();
2216 std::vector<SDOperand> Args = TLI.LowerArguments(F, SDL.DAG);
Chris Lattner16f64df2005-01-17 17:15:02 +00002217
Chris Lattner6871b232005-10-30 19:42:35 +00002218 unsigned a = 0;
2219 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
2220 AI != E; ++AI, ++a)
2221 if (!AI->use_empty()) {
2222 SDL.setValue(AI, Args[a]);
Chris Lattnerd4382f02005-09-13 19:30:54 +00002223
Chris Lattner6871b232005-10-30 19:42:35 +00002224 // If this argument is live outside of the entry block, insert a copy from
2225 // whereever we got it to the vreg that other BB's will reference it as.
2226 if (FuncInfo.ValueMap.count(AI)) {
2227 SDOperand Copy =
2228 CopyValueToVirtualRegister(SDL, AI, FuncInfo.ValueMap[AI]);
2229 UnorderedChains.push_back(Copy);
2230 }
Chris Lattnere3c2cf42005-01-17 17:55:19 +00002231 }
Chris Lattner6871b232005-10-30 19:42:35 +00002232
2233 // Next, if the function has live ins that need to be copied into vregs,
2234 // emit the copies now, into the top of the block.
2235 MachineFunction &MF = SDL.DAG.getMachineFunction();
2236 if (MF.livein_begin() != MF.livein_end()) {
2237 SSARegMap *RegMap = MF.getSSARegMap();
2238 const MRegisterInfo &MRI = *MF.getTarget().getRegisterInfo();
2239 for (MachineFunction::livein_iterator LI = MF.livein_begin(),
2240 E = MF.livein_end(); LI != E; ++LI)
2241 if (LI->second)
2242 MRI.copyRegToReg(*MF.begin(), MF.begin()->end(), LI->second,
2243 LI->first, RegMap->getRegClass(LI->second));
Chris Lattner16f64df2005-01-17 17:15:02 +00002244 }
Chris Lattner6871b232005-10-30 19:42:35 +00002245
2246 // Finally, if the target has anything special to do, allow it to do so.
2247 EmitFunctionEntryCode(F, SDL.DAG.getMachineFunction());
Chris Lattner16f64df2005-01-17 17:15:02 +00002248}
2249
2250
Chris Lattner7a60d912005-01-07 07:47:53 +00002251void SelectionDAGISel::BuildSelectionDAG(SelectionDAG &DAG, BasicBlock *LLVMBB,
2252 std::vector<std::pair<MachineInstr*, unsigned> > &PHINodesToUpdate,
2253 FunctionLoweringInfo &FuncInfo) {
2254 SelectionDAGLowering SDL(DAG, TLI, FuncInfo);
Chris Lattner718b5c22005-01-13 17:59:43 +00002255
2256 std::vector<SDOperand> UnorderedChains;
Misha Brukman835702a2005-04-21 22:36:52 +00002257
Chris Lattner6871b232005-10-30 19:42:35 +00002258 // Lower any arguments needed in this block if this is the entry block.
2259 if (LLVMBB == &LLVMBB->getParent()->front())
2260 LowerArguments(LLVMBB, SDL, UnorderedChains);
Chris Lattner7a60d912005-01-07 07:47:53 +00002261
2262 BB = FuncInfo.MBBMap[LLVMBB];
2263 SDL.setCurrentBasicBlock(BB);
2264
2265 // Lower all of the non-terminator instructions.
2266 for (BasicBlock::iterator I = LLVMBB->begin(), E = --LLVMBB->end();
2267 I != E; ++I)
2268 SDL.visit(*I);
2269
2270 // Ensure that all instructions which are used outside of their defining
2271 // blocks are available as virtual registers.
2272 for (BasicBlock::iterator I = LLVMBB->begin(), E = LLVMBB->end(); I != E;++I)
Chris Lattner613f79f2005-01-11 22:03:46 +00002273 if (!I->use_empty() && !isa<PHINode>(I)) {
Chris Lattnera2c5d912005-01-09 01:16:24 +00002274 std::map<const Value*, unsigned>::iterator VMI =FuncInfo.ValueMap.find(I);
Chris Lattner7a60d912005-01-07 07:47:53 +00002275 if (VMI != FuncInfo.ValueMap.end())
Chris Lattner718b5c22005-01-13 17:59:43 +00002276 UnorderedChains.push_back(
2277 CopyValueToVirtualRegister(SDL, I, VMI->second));
Chris Lattner7a60d912005-01-07 07:47:53 +00002278 }
2279
2280 // Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
2281 // ensure constants are generated when needed. Remember the virtual registers
2282 // that need to be added to the Machine PHI nodes as input. We cannot just
2283 // directly add them, because expansion might result in multiple MBB's for one
2284 // BB. As such, the start of the BB might correspond to a different MBB than
2285 // the end.
Misha Brukman835702a2005-04-21 22:36:52 +00002286 //
Chris Lattner7a60d912005-01-07 07:47:53 +00002287
2288 // Emit constants only once even if used by multiple PHI nodes.
2289 std::map<Constant*, unsigned> ConstantsOut;
2290
2291 // Check successor nodes PHI nodes that expect a constant to be available from
2292 // this block.
2293 TerminatorInst *TI = LLVMBB->getTerminator();
2294 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
2295 BasicBlock *SuccBB = TI->getSuccessor(succ);
2296 MachineBasicBlock::iterator MBBI = FuncInfo.MBBMap[SuccBB]->begin();
2297 PHINode *PN;
2298
2299 // At this point we know that there is a 1-1 correspondence between LLVM PHI
2300 // nodes and Machine PHI nodes, but the incoming operands have not been
2301 // emitted yet.
2302 for (BasicBlock::iterator I = SuccBB->begin();
Chris Lattner8ea875f2005-01-07 21:34:19 +00002303 (PN = dyn_cast<PHINode>(I)); ++I)
2304 if (!PN->use_empty()) {
2305 unsigned Reg;
2306 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
2307 if (Constant *C = dyn_cast<Constant>(PHIOp)) {
2308 unsigned &RegOut = ConstantsOut[C];
2309 if (RegOut == 0) {
2310 RegOut = FuncInfo.CreateRegForValue(C);
Chris Lattner718b5c22005-01-13 17:59:43 +00002311 UnorderedChains.push_back(
2312 CopyValueToVirtualRegister(SDL, C, RegOut));
Chris Lattner8ea875f2005-01-07 21:34:19 +00002313 }
2314 Reg = RegOut;
2315 } else {
2316 Reg = FuncInfo.ValueMap[PHIOp];
Chris Lattnera2c5d912005-01-09 01:16:24 +00002317 if (Reg == 0) {
Misha Brukman835702a2005-04-21 22:36:52 +00002318 assert(isa<AllocaInst>(PHIOp) &&
Chris Lattnera2c5d912005-01-09 01:16:24 +00002319 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
2320 "Didn't codegen value into a register!??");
2321 Reg = FuncInfo.CreateRegForValue(PHIOp);
Chris Lattner718b5c22005-01-13 17:59:43 +00002322 UnorderedChains.push_back(
2323 CopyValueToVirtualRegister(SDL, PHIOp, Reg));
Chris Lattnera2c5d912005-01-09 01:16:24 +00002324 }
Chris Lattner7a60d912005-01-07 07:47:53 +00002325 }
Misha Brukman835702a2005-04-21 22:36:52 +00002326
Chris Lattner8ea875f2005-01-07 21:34:19 +00002327 // Remember that this register needs to added to the machine PHI node as
2328 // the input for this MBB.
2329 unsigned NumElements =
2330 TLI.getNumElements(TLI.getValueType(PN->getType()));
2331 for (unsigned i = 0, e = NumElements; i != e; ++i)
2332 PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
Chris Lattner7a60d912005-01-07 07:47:53 +00002333 }
Chris Lattner7a60d912005-01-07 07:47:53 +00002334 }
2335 ConstantsOut.clear();
2336
Chris Lattner718b5c22005-01-13 17:59:43 +00002337 // Turn all of the unordered chains into one factored node.
Chris Lattner24516842005-01-13 19:53:14 +00002338 if (!UnorderedChains.empty()) {
Chris Lattnerb7cad902005-11-09 05:03:03 +00002339 SDOperand Root = SDL.getRoot();
2340 if (Root.getOpcode() != ISD::EntryToken) {
2341 unsigned i = 0, e = UnorderedChains.size();
2342 for (; i != e; ++i) {
2343 assert(UnorderedChains[i].Val->getNumOperands() > 1);
2344 if (UnorderedChains[i].Val->getOperand(0) == Root)
2345 break; // Don't add the root if we already indirectly depend on it.
2346 }
2347
2348 if (i == e)
2349 UnorderedChains.push_back(Root);
2350 }
Chris Lattner718b5c22005-01-13 17:59:43 +00002351 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other, UnorderedChains));
2352 }
2353
Chris Lattner7a60d912005-01-07 07:47:53 +00002354 // Lower the terminator after the copies are emitted.
2355 SDL.visit(*LLVMBB->getTerminator());
Chris Lattner4108bb02005-01-17 19:43:36 +00002356
2357 // Make sure the root of the DAG is up-to-date.
2358 DAG.setRoot(SDL.getRoot());
Chris Lattner7a60d912005-01-07 07:47:53 +00002359}
2360
2361void SelectionDAGISel::SelectBasicBlock(BasicBlock *LLVMBB, MachineFunction &MF,
2362 FunctionLoweringInfo &FuncInfo) {
Jim Laskey219d5592006-01-04 22:28:25 +00002363 SelectionDAG DAG(TLI, MF, getAnalysisToUpdate<MachineDebugInfo>());
Chris Lattner7a60d912005-01-07 07:47:53 +00002364 CurDAG = &DAG;
2365 std::vector<std::pair<MachineInstr*, unsigned> > PHINodesToUpdate;
2366
2367 // First step, lower LLVM code to some DAG. This DAG may use operations and
2368 // types that are not supported by the target.
2369 BuildSelectionDAG(DAG, LLVMBB, PHINodesToUpdate, FuncInfo);
2370
Chris Lattnerbcfebeb2005-10-10 16:47:10 +00002371 // Run the DAG combiner in pre-legalize mode.
2372 DAG.Combine(false);
Nate Begeman007c6502005-09-07 00:15:36 +00002373
Chris Lattner7a60d912005-01-07 07:47:53 +00002374 DEBUG(std::cerr << "Lowered selection DAG:\n");
2375 DEBUG(DAG.dump());
2376
2377 // Second step, hack on the DAG until it only uses operations and types that
2378 // the target supports.
Chris Lattnerffcb0ae2005-01-23 04:36:26 +00002379 DAG.Legalize();
Chris Lattner7a60d912005-01-07 07:47:53 +00002380
2381 DEBUG(std::cerr << "Legalized selection DAG:\n");
2382 DEBUG(DAG.dump());
2383
Chris Lattnerbcfebeb2005-10-10 16:47:10 +00002384 // Run the DAG combiner in post-legalize mode.
2385 DAG.Combine(true);
Nate Begeman007c6502005-09-07 00:15:36 +00002386
Evan Cheng739a6a42006-01-21 02:32:06 +00002387 if (ViewISelDAGs) DAG.viewGraph();
Chris Lattner6bd8fd02005-10-05 06:09:10 +00002388
Chris Lattner5ca31d92005-03-30 01:10:47 +00002389 // Third, instruction select all of the operations to machine code, adding the
2390 // code to the MachineBasicBlock.
Chris Lattner7a60d912005-01-07 07:47:53 +00002391 InstructionSelectBasicBlock(DAG);
2392
Chris Lattner7a60d912005-01-07 07:47:53 +00002393 DEBUG(std::cerr << "Selected machine code:\n");
2394 DEBUG(BB->dump());
2395
Chris Lattner5ca31d92005-03-30 01:10:47 +00002396 // Next, now that we know what the last MBB the LLVM BB expanded is, update
Chris Lattner7a60d912005-01-07 07:47:53 +00002397 // PHI nodes in successors.
2398 for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
2399 MachineInstr *PHI = PHINodesToUpdate[i].first;
2400 assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
2401 "This is not a machine PHI node that we are updating!");
2402 PHI->addRegOperand(PHINodesToUpdate[i].second);
2403 PHI->addMachineBasicBlockOperand(BB);
2404 }
Chris Lattner5ca31d92005-03-30 01:10:47 +00002405
2406 // Finally, add the CFG edges from the last selected MBB to the successor
2407 // MBBs.
2408 TerminatorInst *TI = LLVMBB->getTerminator();
2409 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
2410 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[TI->getSuccessor(i)];
2411 BB->addSuccessor(Succ0MBB);
2412 }
Chris Lattner7a60d912005-01-07 07:47:53 +00002413}
Evan Cheng739a6a42006-01-21 02:32:06 +00002414
2415//===----------------------------------------------------------------------===//
2416/// ScheduleAndEmitDAG - Pick a safe ordering and emit instructions for each
2417/// target node in the graph.
2418void SelectionDAGISel::ScheduleAndEmitDAG(SelectionDAG &DAG) {
2419 if (ViewSchedDAGs) DAG.viewGraph();
Evan Chengc1e1d972006-01-23 07:01:07 +00002420 ScheduleDAG *SL = NULL;
2421
2422 switch (ISHeuristic) {
2423 default: assert(0 && "Unrecognized scheduling heuristic");
Evan Chenga6eff8a2006-01-25 09:12:57 +00002424 case defaultScheduling:
2425 if (TLI.getSchedulingPreference() == TargetLowering::SchedulingForLatency)
2426 SL = createSimpleDAGScheduler(noScheduling, DAG, BB);
2427 else /* TargetLowering::SchedulingForRegPressure */
2428 SL = createBURRListDAGScheduler(DAG, BB);
2429 break;
Evan Chengc1e1d972006-01-23 07:01:07 +00002430 case noScheduling:
2431 case simpleScheduling:
2432 case simpleNoItinScheduling:
2433 SL = createSimpleDAGScheduler(ISHeuristic, DAG, BB);
2434 break;
Evan Cheng31272342006-01-23 08:26:10 +00002435 case listSchedulingBURR:
2436 SL = createBURRListDAGScheduler(DAG, BB);
Evan Chengc1e1d972006-01-23 07:01:07 +00002437 }
Chris Lattnere23928c2006-01-21 19:12:11 +00002438 BB = SL->Run();
Evan Chengf9adce92006-02-04 06:49:00 +00002439 delete SL;
Evan Cheng739a6a42006-01-21 02:32:06 +00002440}
Chris Lattnerdcf785b2006-02-24 02:13:54 +00002441
2442/// SelectInlineAsmMemoryOperands - Calls to this are automatically generated
2443/// by tblgen. Others should not call it.
2444void SelectionDAGISel::
2445SelectInlineAsmMemoryOperands(std::vector<SDOperand> &Ops, SelectionDAG &DAG) {
2446 std::vector<SDOperand> InOps;
2447 std::swap(InOps, Ops);
2448
2449 Ops.push_back(InOps[0]); // input chain.
2450 Ops.push_back(InOps[1]); // input asm string.
2451
2452 const char *AsmStr = cast<ExternalSymbolSDNode>(InOps[1])->getSymbol();
2453 unsigned i = 2, e = InOps.size();
2454 if (InOps[e-1].getValueType() == MVT::Flag)
2455 --e; // Don't process a flag operand if it is here.
2456
2457 while (i != e) {
2458 unsigned Flags = cast<ConstantSDNode>(InOps[i])->getValue();
2459 if ((Flags & 7) != 4 /*MEM*/) {
2460 // Just skip over this operand, copying the operands verbatim.
2461 Ops.insert(Ops.end(), InOps.begin()+i, InOps.begin()+i+(Flags >> 3) + 1);
2462 i += (Flags >> 3) + 1;
2463 } else {
2464 assert((Flags >> 3) == 1 && "Memory operand with multiple values?");
2465 // Otherwise, this is a memory operand. Ask the target to select it.
2466 std::vector<SDOperand> SelOps;
2467 if (SelectInlineAsmMemoryOperand(InOps[i+1], 'm', SelOps, DAG)) {
2468 std::cerr << "Could not match memory address. Inline asm failure!\n";
2469 exit(1);
2470 }
2471
2472 // Add this to the output node.
2473 Ops.push_back(DAG.getConstant(4/*MEM*/ | (SelOps.size() << 3), MVT::i32));
2474 Ops.insert(Ops.end(), SelOps.begin(), SelOps.end());
2475 i += 2;
2476 }
2477 }
2478
2479 // Add the flag input back if present.
2480 if (e != InOps.size())
2481 Ops.push_back(InOps.back());
2482}