CGExprAgg.cpp revision f9eede163826dd55a56c479330ef041eaa856417
1//===--- CGExprAgg.cpp - Emit LLVM Code from Aggregate Expressions --------===// 2// 3// The LLVM Compiler Infrastructure 4// 5// This file is distributed under the University of Illinois Open Source 6// License. See LICENSE.TXT for details. 7// 8//===----------------------------------------------------------------------===// 9// 10// This contains code to emit Aggregate Expr nodes as LLVM code. 11// 12//===----------------------------------------------------------------------===// 13 14#include "CodeGenFunction.h" 15#include "CodeGenModule.h" 16#include "clang/AST/AST.h" 17#include "llvm/Constants.h" 18#include "llvm/Function.h" 19#include "llvm/GlobalVariable.h" 20#include "llvm/Support/Compiler.h" 21#include "llvm/Intrinsics.h" 22using namespace clang; 23using namespace CodeGen; 24 25//===----------------------------------------------------------------------===// 26// Aggregate Expression Emitter 27//===----------------------------------------------------------------------===// 28 29namespace { 30class VISIBILITY_HIDDEN AggExprEmitter : public StmtVisitor<AggExprEmitter> { 31 CodeGenFunction &CGF; 32 llvm::IRBuilder &Builder; 33 llvm::Value *DestPtr; 34 bool VolatileDest; 35public: 36 AggExprEmitter(CodeGenFunction &cgf, llvm::Value *destPtr, bool volatileDest) 37 : CGF(cgf), Builder(CGF.Builder), 38 DestPtr(destPtr), VolatileDest(volatileDest) { 39 } 40 41 //===--------------------------------------------------------------------===// 42 // Utilities 43 //===--------------------------------------------------------------------===// 44 45 /// EmitAggLoadOfLValue - Given an expression with aggregate type that 46 /// represents a value lvalue, this method emits the address of the lvalue, 47 /// then loads the result into DestPtr. 48 void EmitAggLoadOfLValue(const Expr *E); 49 50 void EmitAggregateCopy(llvm::Value *DestPtr, llvm::Value *SrcPtr, 51 QualType EltTy); 52 53 void EmitAggregateClear(llvm::Value *DestPtr, QualType Ty); 54 55 void EmitNonConstInit(InitListExpr *E); 56 57 //===--------------------------------------------------------------------===// 58 // Visitor Methods 59 //===--------------------------------------------------------------------===// 60 61 void VisitStmt(Stmt *S) { 62 CGF.WarnUnsupported(S, "aggregate expression"); 63 } 64 void VisitParenExpr(ParenExpr *PE) { Visit(PE->getSubExpr()); } 65 66 // l-values. 67 void VisitDeclRefExpr(DeclRefExpr *DRE) { EmitAggLoadOfLValue(DRE); } 68 void VisitMemberExpr(MemberExpr *ME) { EmitAggLoadOfLValue(ME); } 69 void VisitUnaryDeref(UnaryOperator *E) { EmitAggLoadOfLValue(E); } 70 void VisitStringLiteral(StringLiteral *E) { EmitAggLoadOfLValue(E); } 71 void VisitCompoundLiteralExpr(CompoundLiteralExpr *E) 72 { EmitAggLoadOfLValue(E); } 73 74 void VisitArraySubscriptExpr(ArraySubscriptExpr *E) { 75 EmitAggLoadOfLValue(E); 76 } 77 78 // Operators. 79 // case Expr::UnaryOperatorClass: 80 // case Expr::CastExprClass: 81 void VisitImplicitCastExpr(ImplicitCastExpr *E); 82 void VisitCallExpr(const CallExpr *E); 83 void VisitStmtExpr(const StmtExpr *E); 84 void VisitBinaryOperator(const BinaryOperator *BO); 85 void VisitBinAssign(const BinaryOperator *E); 86 void VisitOverloadExpr(const OverloadExpr *E); 87 void VisitBinComma(const BinaryOperator *E); 88 89 void VisitObjCMessageExpr(ObjCMessageExpr *E); 90 91 92 void VisitConditionalOperator(const ConditionalOperator *CO); 93 void VisitInitListExpr(InitListExpr *E); 94 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) { 95 Visit(DAE->getExpr()); 96 } 97 void VisitVAArgExpr(VAArgExpr *E); 98 99 void EmitInitializationToLValue(Expr *E, LValue Address); 100 void EmitNullInitializationToLValue(LValue Address, QualType T); 101 // case Expr::ChooseExprClass: 102 103}; 104} // end anonymous namespace. 105 106//===----------------------------------------------------------------------===// 107// Utilities 108//===----------------------------------------------------------------------===// 109 110void AggExprEmitter::EmitAggregateClear(llvm::Value *DestPtr, QualType Ty) { 111 assert(!Ty->isAnyComplexType() && "Shouldn't happen for complex"); 112 113 // Aggregate assignment turns into llvm.memset. 114 const llvm::Type *BP = llvm::PointerType::getUnqual(llvm::Type::Int8Ty); 115 if (DestPtr->getType() != BP) 116 DestPtr = Builder.CreateBitCast(DestPtr, BP, "tmp"); 117 118 // Get size and alignment info for this aggregate. 119 std::pair<uint64_t, unsigned> TypeInfo = CGF.getContext().getTypeInfo(Ty); 120 121 // FIXME: Handle variable sized types. 122 const llvm::Type *IntPtr = llvm::IntegerType::get(CGF.LLVMPointerWidth); 123 124 llvm::Value *MemSetOps[4] = { 125 DestPtr, 126 llvm::ConstantInt::getNullValue(llvm::Type::Int8Ty), 127 // TypeInfo.first describes size in bits. 128 llvm::ConstantInt::get(IntPtr, TypeInfo.first/8), 129 llvm::ConstantInt::get(llvm::Type::Int32Ty, TypeInfo.second/8) 130 }; 131 132 Builder.CreateCall(CGF.CGM.getMemSetFn(), MemSetOps, MemSetOps+4); 133} 134 135void AggExprEmitter::EmitAggregateCopy(llvm::Value *DestPtr, 136 llvm::Value *SrcPtr, QualType Ty) { 137 assert(!Ty->isAnyComplexType() && "Shouldn't happen for complex"); 138 139 // Aggregate assignment turns into llvm.memmove. 140 const llvm::Type *BP = llvm::PointerType::getUnqual(llvm::Type::Int8Ty); 141 if (DestPtr->getType() != BP) 142 DestPtr = Builder.CreateBitCast(DestPtr, BP, "tmp"); 143 if (SrcPtr->getType() != BP) 144 SrcPtr = Builder.CreateBitCast(SrcPtr, BP, "tmp"); 145 146 // Get size and alignment info for this aggregate. 147 std::pair<uint64_t, unsigned> TypeInfo = CGF.getContext().getTypeInfo(Ty); 148 149 // FIXME: Handle variable sized types. 150 const llvm::Type *IntPtr = llvm::IntegerType::get(CGF.LLVMPointerWidth); 151 152 llvm::Value *MemMoveOps[4] = { 153 DestPtr, SrcPtr, 154 // TypeInfo.first describes size in bits. 155 llvm::ConstantInt::get(IntPtr, TypeInfo.first/8), 156 llvm::ConstantInt::get(llvm::Type::Int32Ty, TypeInfo.second/8) 157 }; 158 159 Builder.CreateCall(CGF.CGM.getMemMoveFn(), MemMoveOps, MemMoveOps+4); 160} 161 162 163/// EmitAggLoadOfLValue - Given an expression with aggregate type that 164/// represents a value lvalue, this method emits the address of the lvalue, 165/// then loads the result into DestPtr. 166void AggExprEmitter::EmitAggLoadOfLValue(const Expr *E) { 167 LValue LV = CGF.EmitLValue(E); 168 assert(LV.isSimple() && "Can't have aggregate bitfield, vector, etc"); 169 llvm::Value *SrcPtr = LV.getAddress(); 170 171 // If the result is ignored, don't copy from the value. 172 if (DestPtr == 0) 173 // FIXME: If the source is volatile, we must read from it. 174 return; 175 176 EmitAggregateCopy(DestPtr, SrcPtr, E->getType()); 177} 178 179//===----------------------------------------------------------------------===// 180// Visitor Methods 181//===----------------------------------------------------------------------===// 182 183void AggExprEmitter::VisitImplicitCastExpr(ImplicitCastExpr *E) { 184 assert(CGF.getContext().typesAreCompatible( 185 E->getSubExpr()->getType().getUnqualifiedType(), 186 E->getType().getUnqualifiedType()) && 187 "Implicit cast types must be compatible"); 188 Visit(E->getSubExpr()); 189} 190 191void AggExprEmitter::VisitCallExpr(const CallExpr *E) { 192 RValue RV = CGF.EmitCallExpr(E); 193 assert(RV.isAggregate() && "Return value must be aggregate value!"); 194 195 // If the result is ignored, don't copy from the value. 196 if (DestPtr == 0) 197 // FIXME: If the source is volatile, we must read from it. 198 return; 199 200 EmitAggregateCopy(DestPtr, RV.getAggregateAddr(), E->getType()); 201} 202 203void AggExprEmitter::VisitObjCMessageExpr(ObjCMessageExpr *E) { 204 RValue RV = RValue::getAggregate(CGF.EmitObjCMessageExpr(E)); 205 206 // If the result is ignored, don't copy from the value. 207 if (DestPtr == 0) 208 return; 209 210 EmitAggregateCopy(DestPtr, RV.getAggregateAddr(), E->getType()); 211} 212 213void AggExprEmitter::VisitOverloadExpr(const OverloadExpr *E) { 214 RValue RV = CGF.EmitCallExpr(E->getFn(), E->arg_begin(), 215 E->arg_end(CGF.getContext())); 216 217 assert(RV.isAggregate() && "Return value must be aggregate value!"); 218 219 // If the result is ignored, don't copy from the value. 220 if (DestPtr == 0) 221 // FIXME: If the source is volatile, we must read from it. 222 return; 223 224 EmitAggregateCopy(DestPtr, RV.getAggregateAddr(), E->getType()); 225} 226 227void AggExprEmitter::VisitBinComma(const BinaryOperator *E) { 228 CGF.EmitAnyExpr(E->getLHS()); 229 CGF.EmitAggExpr(E->getRHS(), DestPtr, false); 230} 231 232void AggExprEmitter::VisitStmtExpr(const StmtExpr *E) { 233 CGF.EmitCompoundStmt(*E->getSubStmt(), true, DestPtr, VolatileDest); 234} 235 236void AggExprEmitter::VisitBinaryOperator(const BinaryOperator *E) { 237 CGF.WarnUnsupported(E, "aggregate binary expression"); 238} 239 240void AggExprEmitter::VisitBinAssign(const BinaryOperator *E) { 241 // For an assignment to work, the value on the right has 242 // to be compatible with the value on the left. 243 assert(CGF.getContext().typesAreCompatible( 244 E->getLHS()->getType().getUnqualifiedType(), 245 E->getRHS()->getType().getUnqualifiedType()) 246 && "Invalid assignment"); 247 LValue LHS = CGF.EmitLValue(E->getLHS()); 248 249 // Codegen the RHS so that it stores directly into the LHS. 250 CGF.EmitAggExpr(E->getRHS(), LHS.getAddress(), false /*FIXME: VOLATILE LHS*/); 251 252 if (DestPtr == 0) 253 return; 254 255 // If the result of the assignment is used, copy the RHS there also. 256 EmitAggregateCopy(DestPtr, LHS.getAddress(), E->getType()); 257} 258 259void AggExprEmitter::VisitConditionalOperator(const ConditionalOperator *E) { 260 llvm::BasicBlock *LHSBlock = llvm::BasicBlock::Create("cond.?"); 261 llvm::BasicBlock *RHSBlock = llvm::BasicBlock::Create("cond.:"); 262 llvm::BasicBlock *ContBlock = llvm::BasicBlock::Create("cond.cont"); 263 264 llvm::Value *Cond = CGF.EvaluateExprAsBool(E->getCond()); 265 Builder.CreateCondBr(Cond, LHSBlock, RHSBlock); 266 267 CGF.EmitBlock(LHSBlock); 268 269 // Handle the GNU extension for missing LHS. 270 assert(E->getLHS() && "Must have LHS for aggregate value"); 271 272 Visit(E->getLHS()); 273 Builder.CreateBr(ContBlock); 274 LHSBlock = Builder.GetInsertBlock(); 275 276 CGF.EmitBlock(RHSBlock); 277 278 Visit(E->getRHS()); 279 Builder.CreateBr(ContBlock); 280 RHSBlock = Builder.GetInsertBlock(); 281 282 CGF.EmitBlock(ContBlock); 283} 284 285void AggExprEmitter::VisitVAArgExpr(VAArgExpr *VE) { 286 llvm::Value *ArgValue = CGF.EmitLValue(VE->getSubExpr()).getAddress(); 287 llvm::Value *V = Builder.CreateVAArg(ArgValue, CGF.ConvertType(VE->getType())); 288 if (DestPtr) 289 // FIXME: volatility 290 Builder.CreateStore(V, DestPtr); 291} 292 293void AggExprEmitter::EmitNonConstInit(InitListExpr *E) { 294 295 const llvm::PointerType *APType = 296 cast<llvm::PointerType>(DestPtr->getType()); 297 const llvm::Type *DestType = APType->getElementType(); 298 299 if (const llvm::ArrayType *AType = dyn_cast<llvm::ArrayType>(DestType)) { 300 unsigned NumInitElements = E->getNumInits(); 301 302 unsigned i; 303 for (i = 0; i != NumInitElements; ++i) { 304 llvm::Value *NextVal = Builder.CreateStructGEP(DestPtr, i, ".array"); 305 Expr *Init = E->getInit(i); 306 if (isa<InitListExpr>(Init)) 307 CGF.EmitAggExpr(Init, NextVal, VolatileDest); 308 else 309 // FIXME: volatility 310 Builder.CreateStore(CGF.EmitScalarExpr(Init), NextVal); 311 } 312 313 // Emit remaining default initializers 314 unsigned NumArrayElements = AType->getNumElements(); 315 QualType QType = E->getInit(0)->getType(); 316 const llvm::Type *EType = AType->getElementType(); 317 for (/*Do not initialize i*/; i < NumArrayElements; ++i) { 318 llvm::Value *NextVal = Builder.CreateStructGEP(DestPtr, i, ".array"); 319 if (EType->isSingleValueType()) 320 // FIXME: volatility 321 Builder.CreateStore(llvm::Constant::getNullValue(EType), NextVal); 322 else 323 EmitAggregateClear(NextVal, QType); 324 } 325 } else 326 assert(false && "Invalid initializer"); 327} 328 329void AggExprEmitter::EmitInitializationToLValue(Expr* E, LValue LV) { 330 // FIXME: Are initializers affected by volatile? 331 if (E->getType()->isComplexType()) { 332 CGF.EmitComplexExprIntoAddr(E, LV.getAddress(), false); 333 } else if (CGF.hasAggregateLLVMType(E->getType())) { 334 CGF.EmitAnyExpr(E, LV.getAddress(), false); 335 } else { 336 CGF.EmitStoreThroughLValue(CGF.EmitAnyExpr(E), LV, E->getType()); 337 } 338} 339 340void AggExprEmitter::EmitNullInitializationToLValue(LValue LV, QualType T) { 341 if (!CGF.hasAggregateLLVMType(T)) { 342 // For non-aggregates, we can store zero 343 const llvm::Type *T = 344 cast<llvm::PointerType>(LV.getAddress()->getType())->getElementType(); 345 // FIXME: volatility 346 Builder.CreateStore(llvm::Constant::getNullValue(T), LV.getAddress()); 347 } else { 348 // Otherwise, just memset the whole thing to zero. This is legal 349 // because in LLVM, all default initializers are guaranteed to have a 350 // bit pattern of all zeros. 351 // There's a potential optimization opportunity in combining 352 // memsets; that would be easy for arrays, but relatively 353 // difficult for structures with the current code. 354 llvm::Value *MemSet = CGF.CGM.getIntrinsic(llvm::Intrinsic::memset_i64); 355 uint64_t Size = CGF.getContext().getTypeSize(T); 356 357 const llvm::Type *BP = llvm::PointerType::getUnqual(llvm::Type::Int8Ty); 358 llvm::Value* DestPtr = Builder.CreateBitCast(LV.getAddress(), BP, "tmp"); 359 Builder.CreateCall4(MemSet, DestPtr, 360 llvm::ConstantInt::get(llvm::Type::Int8Ty, 0), 361 llvm::ConstantInt::get(llvm::Type::Int64Ty, Size/8), 362 llvm::ConstantInt::get(llvm::Type::Int32Ty, 0)); 363 } 364} 365 366void AggExprEmitter::VisitInitListExpr(InitListExpr *E) { 367 if (E->isConstantExpr(CGF.getContext(), 0)) { 368 // FIXME: call into const expr emitter so that we can emit 369 // a memcpy instead of storing the individual members. 370 // This is purely for perf; both codepaths lead to equivalent 371 // (although not necessarily identical) code. 372 // It's worth noting that LLVM keeps on getting smarter, though, 373 // so it might not be worth bothering. 374 } 375 376 // Handle initialization of an array. 377 if (E->getType()->isArrayType()) { 378 const llvm::PointerType *APType = 379 cast<llvm::PointerType>(DestPtr->getType()); 380 const llvm::ArrayType *AType = 381 cast<llvm::ArrayType>(APType->getElementType()); 382 383 uint64_t NumInitElements = E->getNumInits(); 384 385 if (E->getNumInits() > 0) { 386 QualType T1 = E->getType(); 387 QualType T2 = E->getInit(0)->getType(); 388 if (CGF.getContext().getCanonicalType(T1).getUnqualifiedType() == 389 CGF.getContext().getCanonicalType(T2).getUnqualifiedType()) { 390 EmitAggLoadOfLValue(E->getInit(0)); 391 return; 392 } 393 } 394 395 uint64_t NumArrayElements = AType->getNumElements(); 396 QualType ElementType = E->getType()->getAsArrayType()->getElementType(); 397 398 unsigned CVRqualifier = 399 CGF.getContext().getCanonicalType(E->getType())->getAsArrayType() 400 ->getElementType().getCVRQualifiers(); 401 402 for (uint64_t i = 0; i != NumArrayElements; ++i) { 403 llvm::Value *NextVal = Builder.CreateStructGEP(DestPtr, i, ".array"); 404 if (i < NumInitElements) 405 EmitInitializationToLValue(E->getInit(i), 406 LValue::MakeAddr(NextVal, CVRqualifier)); 407 else 408 EmitNullInitializationToLValue(LValue::MakeAddr(NextVal, CVRqualifier), 409 ElementType); 410 } 411 return; 412 } 413 414 assert(E->getType()->isRecordType() && "Only support structs/unions here!"); 415 416 // Do struct initialization; this code just sets each individual member 417 // to the approprate value. This makes bitfield support automatic; 418 // the disadvantage is that the generated code is more difficult for 419 // the optimizer, especially with bitfields. 420 unsigned NumInitElements = E->getNumInits(); 421 RecordDecl *SD = E->getType()->getAsRecordType()->getDecl(); 422 unsigned NumMembers = SD->getNumMembers() - SD->hasFlexibleArrayMember(); 423 unsigned CurInitVal = 0; 424 bool isUnion = E->getType()->isUnionType(); 425 426 // Here we iterate over the fields; this makes it simpler to both 427 // default-initialize fields and skip over unnamed fields. 428 for (unsigned CurFieldNo = 0; CurFieldNo != NumMembers; ++CurFieldNo) { 429 FieldDecl *CurField = SD->getMember(CurFieldNo); 430 if (CurField->getIdentifier() == 0) { 431 // Initializers can't initialize unnamed fields, e.g. "int : 20;" 432 continue; 433 } 434 // FIXME: volatility 435 LValue FieldLoc = CGF.EmitLValueForField(DestPtr, CurField, isUnion,0); 436 if (CurInitVal < NumInitElements) { 437 // Store the initializer into the field 438 // This will probably have to get a bit smarter when we support 439 // designators in initializers 440 EmitInitializationToLValue(E->getInit(CurInitVal++), FieldLoc); 441 } else { 442 // We're out of initalizers; default-initialize to null 443 EmitNullInitializationToLValue(FieldLoc, CurField->getType()); 444 } 445 446 // Unions only initialize one field. 447 // (things can get weird with designators, but they aren't 448 // supported yet.) 449 if (E->getType()->isUnionType()) 450 break; 451 } 452} 453 454//===----------------------------------------------------------------------===// 455// Entry Points into this File 456//===----------------------------------------------------------------------===// 457 458/// EmitAggExpr - Emit the computation of the specified expression of 459/// aggregate type. The result is computed into DestPtr. Note that if 460/// DestPtr is null, the value of the aggregate expression is not needed. 461void CodeGenFunction::EmitAggExpr(const Expr *E, llvm::Value *DestPtr, 462 bool VolatileDest) { 463 assert(E && hasAggregateLLVMType(E->getType()) && 464 "Invalid aggregate expression to emit"); 465 466 AggExprEmitter(*this, DestPtr, VolatileDest).Visit(const_cast<Expr*>(E)); 467} 468